Assiut University
Course Title: Programming Fundamentals
Course Code: CS141
Prof. Khaled F. Hussain
Basic Elements of C++
Reference
• D. S. Malik, “C++ Programming: From Problem Analysis to Program
Design”, Cengage Learning
Comments
• The program that you write should be clear not only to you, but also to the reader of your
program.
• Comments are for the reader, not for the compiler.
• So, when a compiler compiles a program to check for the syntax errors, it completely
ignores comments.
• There are two common types of comments in a C++ program
• single-line comments
• Single-line comments begin with // and can be placed anywhere in the line.
cout << "7 + 8 = " << 7 + 8 << endl; //prints: 7 + 8 = 15
• multiple-line comments.
• Multiple-line comments are enclosed between /* and */. The compiler ignores
anything that appears between /* and */.
/*
You can include comments that can
occupy several lines.
*/
Tokens
• The smallest individual unit of a program written in any language is called a token.
• C++’s tokens are divided into
• Special Symbols
+ - * /
. ; ? ,
<= != == >=
• Reserved Words (Keywords)
• int, float, double, char, const, void, return…etc.
• Identifiers
• Consist of letters, digits, and the underscore character (_)
• Must begin with a letter or underscore
• C++ is case sensitive
• The following are legal identifiers in C++:
• first
• conversion
• payRate
Whitespaces
• Include blanks, tabs, and newline characters
• Can be used to make the program readable
Data Types
• Simple Data Types
• Integral: integers (numbers without a decimal)
• char, short, int, long, bool
• Floating-point: decimal numbers
• float, Range: -3.4E+38 to 3.4E+38 (four bytes)
• Double, Range: -1.7E+308 to 1.7E+308 (eight bytes)
• Enumeration type: user-defined data type
• Structured
• Pointers
A type-safety violation
(“implicit narrowing”)
// Beware: C++ does not prevent you from trying to put a large value
// into a small variable (though a compiler may warn)
int main()
{ a 20000
int a = 20000;
??
char c = a; c: ?
int b = c;
if (a != b) // != means “not equal”
cout << "oops!: " << a << "!=" << b << '\n';
else
cout << "Wow! We have large characters\n";
}
• Try it to see what value b gets on your machine
A technical detail
• In memory, everything is just bits; type is what gives meaning to the bits
(bits/binary) 01100001 is the int 97 is the char 'a'
(bits/binary) 01000001 is the int 65 is the char 'A'
(bits/binary) 00110000 is the int 48 is the char '0'
char c = 'a';
cout << c; // print the value of character c, which is a
int i = c;
cout << i; // print the integer value of the character c, which is 97
• This is just as in “the real world”:
• What does “42” mean?
• You don’t know until you know the unit used
• Meters? Feet? Degrees Celsius? $s? a street number? Height in inches? …
9
Arithmetic Operators, Operator Precedence,
and Expressions
• C++ arithmetic operators: +,-,?*,/,%
• Operators can be unary or binary
• Mixed expression:
• Has operands of different data types
• Contains integers and floating-point
6 / 4 + 3.9
• Type Conversion (Casting)
• Implicit type Conversion: when value of one type is automatically changed to
another type
• Cast operator: provides explicit type conversion
static_cast<dataTypeName>(expression)
Mixed Expression
• 3 / 2 + 5.5 = 1 + 5.5 = 6.5
• 15.6 / 2 + 5 = 7.8 + 5 = 12.8
Precedence
Precedence (Cont.)
• i + j * k is equivalent to i + (j * k)
• -i * - j is equivalent to (-i) * (-j)
• +i + j / k is equivalent to (+i ) + (j / k)
Expressions
• formulate the following expressions as programs:
• ab – c
• (m + n) (x + y)
• (ab / c)
• 3n2 +2n + 1
• n2 + 10
• (1/2) · n2 + 20
• 2 - (1/n)
The following program illustrates the effect of presence
of parenthesis in expressions
main ()
{
float a, b, c, x, y, z;
a = 9;
b = 12;
c = 3;
x = a - b / 3 + c * 2 - 1;
y = a - b / (3 + c) * (2 - 1);
z = a - ( b / (3 + c) * 2) - 1;
cout << x << '\n' ;
cout << y << '\n' ;
cout << z << '\n' ;
}
Output x = 10.00 y = 7.00 z = 4.00
Assignment Operators
• i = 5;
• j = i;
• k =10*i+ j ;
• int i;
• float f;
• i=72.99f;
• f=136;
Assignment Operators (Cont.)
• i = j = k = 0; // (i = (j = (k = 0)))
• int i;
• float f;
• f=i=33.3f;
• i is assigned the value 33, then f is assigned 33.0 (not 33.3. as you
might think).
Assignment Operators (Cont.)
• i=i+2;
• i+=2;
• v +=e adds v to e, storing the result in v
• v -= e subtracts e from v, storing the result in v
• v*= e multiplies v by e, storing the result in v
• v/= e divides v by , storing the result in v
• v%= e computes the remainder when v is divided by e,
storing the result in v
• i+=j+=k; // i+=(j+=k);
string Type
• string Type provides operations to find the length of a string, extract
part of a string, and compare strings.
• Null: a string with no characters
• Each character has relative position in string
• Position of first character is 0
• “Faculty of" position of ‘F’ is 0
• The length of “Faculty of" is 10
Allocating Memory with Constants and
Variables
• Named constant: A memory location whose content is not allowed to
change during program execution.
• const dataType identifier = value;
const double CONVERSION = 2.54;
const int NO_OF_STUDENTS = 20;
const char BLANK = ' ';
Allocating Memory with Constants and
Variables (Cont.)
• Variable: A memory location whose content may change during
program execution.
• The syntax for declaring one variable or multiple variables is:
• dataType identifier, identifier, . . .;
double amountDue;
int counter;
char ch;
int x, y;
string name;
Assignment Statement
• The assignment statement takes the following form:
• variable = expression;
• = is called the assignment operator
int num1, num2;
double sale;
char first;
string str;
num1 = 4;
num2 = 4 * 5 - 11;
sale = 0.02 * 1000;
first = 'D';
str = "It is a sunny day.";
Input (Read) Statement
• cin >> variable >> variable ...;
int feet;
int inches;
Suppose the input is:
23 7
Next, consider the following statement:
cin >> feet >> inches;
• This statement first stores the number 23 into the variable feet and then the number 7 into the
variable inches.
Increment and Decrement Operators
• Pre-increment: ++variable
• Post-increment: variable++
• Pre-decrement: --variable
• Post-decrement: variable--
• What is the difference between the following?
x = 10; x = 10;
y = ++x; y = x++;
Output
• cout << expression or manipulator << expression or manipulator...;
• endl manipulator causes the insertion point to move to the beginning of the next line.
Commonly Used Escape Sequences
EXAMPLE
cout << "Hello there.\nMy name is James.";
or:
cout << "Hello there.";
cout << "\nMy name is James.";
or:
cout << "Hello there.";
cout << endl << "My name is James.";
In each case, the output of the statements is:
Hello there.
My name is James.
EXAMPLE
The output of the C++ statements:
cout << "Count...\n....1\n.....2\n......3";
or:
cout << "Count..." << endl << "....1" << endl
<< ".....2" << endl << "......3";
is:
Count...
....1
.....2
......3
EXAMPLE
The output of the statement:
cout << "The string \"Sunny\" contains five characters." << endl;
is:
The string "Sunny" contains five characters.
Preprocessor Directives
• The general syntax to include a header file (provided by the IDE) in a C++ program is:
#include <headerFileName>
• For example, the following statement includes the header file iostream in a C++ program:
#include <iostream>
namespace
• There are several ways you can use an identifier declared in the
namespace std.
• One way to use cin and cout is to refer to them as std::cin and std::cout
throughout the program.
• Another option is to include the following statement in your program:
using namespace std;
You can then refer to cin and cout without using the prefix std::.
string
• To use the string type, Include the following preprocessor
directive:
#include <string>
Creating a C++ Program
• The syntax of the function main has the following form:
int main()
{
statement_1
.
.
.
statement_n
return 0;
}
function main
The body of the function main contains two types of statements:
• Declaration statements
int a, b, c;
double x, y;
• Executable statements
a = 4; //assignment statement
cin >> b; //input statement
cout << a << " " << b << endl; //output statement
Debugging: Understanding and Fixing Syntax
Errors
1. #include <iostream>
2.
3. using namespace std;
4.
5. int main()
6. {
7. int num
8.
9. num = 18;
10.
11. tempNum = 2 * num;
12.
13. cout << "Num = " << num << ", tempNum = " < tempNum << endl;
14.
15. return ;
16. }
This program is very hard to read (syntactically correct)
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num; double height;
string name;
cout << "Enter an integer: "; cin >> num; cout << endl;
cout<<"num: "<<num<<endl;
cout<<"Enter the first name: "; cin>>name;
cout<<endl; cout <<"Enter the height: ";
cin>>height; cout<<endl;
cout<<"Name: "<<name<<endl;cout<<"Height: "
<<height; cout <<endl;return 0;
}
This program is easier to read
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num;
double height;
string name;
cout << "Enter an integer: ";
cin >> num;
cout << endl;
This program is easier to read (Cont.)
cout << "num: " << num << endl;
cout << "Enter the first name: ";
cin >> name;
cout << endl;
cout << "Enter the height: ";
cin >> height;
cout << endl;
cout << "Name: " << name << endl;
cout << "Height: " << height << endl;
return 0;
}
Simple and Compound Assignment
Statement
Compound Assignment
Simple Assignment Statement Statement
• i = i + 5; • i += 5;
• counter = counter + 1; • counter += 1;
• sum = sum + number; • sum += number;
• amount = amount * (interest + • amount *= interest + 1;
1); • x /= y + 5;
• x = x / ( y + 5);