Chapter One
Fundamentals of C++
Mulugeta G. AND DaMANA d.
1
Variables and Constants
Variables
• are names given to a memory location in a
computer where we can store values.
• Each variable stores a single value at a
time and of particular type.
• The memory size that will be allotted to a
variable depends on the type of value we
store in it.
2
Constants
• refers to fixed values that do not change during the
execution of a program.
• Syntax of constant declaration and initialization:
const type var_name=value;
Eg. const float pi=3.14;
• The const declaration is allowed on both global
and local variables, but is especially useful for
global variables.
3
Variable Declaration and Initialization
Variable Declaration
• In order to use a variable in C++, we must first
declare it specifying which of the data types to be.
• Syntax of variable declaration:
Type var_name;;
For example: int a; float mynumber;
• We can also declare several variables at the same
time
Example: int a, b, c; Declares three variables (a, b
and c) of type int , and has exactly the same meaning
as if we had written:
int a;
int b; int a, b, c;
int c; 4
Variable Initialization
• we can give variables a value as we declare
them by placing an equal sign and a value
after the variable name.
• The general form of variable initialization is:
type var_name=value;
Example:
char ch=’a’;
int sum=0;
float balance =1234.25
Global and local variables ?
5
Global and Local variables
Local Variables
• Variables that are declared in a certain
code block (like function or control
structures block)
• can be referenced only by statements
inside the block in which the variables
are declared.
• Block of code begins with an opening
curly brace and terminates with closing
curly brace.
6
Global variables
• are variables that are known throughout a
program
• They are created by declaring them outside
of any function, including the main ( )
function.
• In the following program the variable radius
is declared outside of all functions in a
program.
• it is recommended to declare global
variables at the top of the program following
the header files. 7
Example of Global and Local Variables
#include<iostream.h>
float r=2.5, p = 3.14;
void area(void);
void circum(void); Void func1() Void func2()
int main( ) { { {
area(); int x; int x;
circum(); x = 10; X = -10
return 1; } }
} The value of x is different
void area(void) {
float a;
a= p*r*r;
}
Void circum(void) {
float c;
c= 2*p*r;
}
8
Input and output statements in C++
• In c++ , the #include <iostream.h>
preprocessor directive includes the
iostream.h header file in our program.
– The iostream.h enables us to use the cin and
cout functions.
• cin -input function that allow a program to
accept input to the program
• cout – an output function use to display
output to the visual display unit.
9
The following program illustrates the usage of the two functions in detail.
#include <iostream.h> cin>>a>>b; is an input statement and
causes the program to wait for the user to
int main () type two numbers.
{ If we enter two values, say 10 and 20 then
int a, b, c; 10 will be assigned to a, 20 to b.
The operator >> is known as extraction (or)
cout<<”enter values of a, b”; get from operator.
cin>>a>>b;
c=a+b; cout<<”The result is:”<<c; is an output
statement causes the string in quotation
cout<<”The result is: “<<c; marks to be displayed on the screen as it is
return 0; and then the content of the variable c is
} displayed .
The operator << is known as insertion (or)
put to operator
10
Sample program 1: Write a c++ program to calculate area of a circle for given diameter
d, using formula r2 where r=d/2.
#include<iostream.h> #include<iostream.h>
int main() int main ()
{ {
float A, pi=3.1415; float c, f;
float d, r; cout<<”Enter the temperature in
cout<<”enter the diameter of circle\n”; farenheit:”;
cin>>d; cin>>f;
r=d / 2; c=(5.0 / 9)*(f - 32);
A= pi * r * r; cout<<”The temperature in celcious is:
cout<< “Area of circle is”<<A; ”<<c;
return 0; return 0;
} }
sample program 2: Write a c++ program to read the temperature in Fahrenheit and
convert it into Celsius. (Formula: c= (5.0/9)*(f-32)).
11
Operators
• is a symbol that tells the computer to
perform certain mathematical (or) logical
manipulations.
• used in programs to manipulate data and
variables.
• C++ operators can be classified into number
of categories. They include:-
1. Arithmetic Operators:
– C++ provides all the basic arithmetic operators
like add (+), subtract (-), multiply (*), divide (/), and
mod (%). mod gives remainder of division.
– Example of mod: if a = 10; b = 3;
c = a % b; c = 1; 12
2. Relational operators:
• relate the operands on either side of them
– Like: less than(<), less than or equal(<=),
equal(==),Greater than(>),
Greater than or equal(>=)and
not equal(!=).
3. Logical operators:
– && (meaning logical AND),
– || (logical OR),
– ! (logical NOT).
13
Truth Table for AND and OR Operations
A B A && B A|| B
false false false false
false true false true
true false false true
true true true true
14
4. Assignment operators:
• used to assign the result of an expression to a
variable
• The symbol is ‘= ‘sign.
• They are 3 types.
– Simple assignment a = 9;
– Multiple assignment a = b = c = 36;
– Compound assignment a + = 15; (add 15 to a
equal to a =a +15;)
b - = 5; (subtract 5 from b).
c * = 6; (Multiply c by 6).
15
5. Auto increment / decrement (+ + / - -):
• used to automatically increment and decrement the value of a
variable by 1.
• there are 2 types.
A. Prefix auto increment / decrement
Adds /subtracts 1 to the operand & result is assigned to the
variable on the left.
Eg. : a = 5; a=5;
b=++a; b=--a;
Result a=b=6; a=b=4;
B. Postfix auto increment / decrement
This first assigns the value to the variable on the left & then
increments/decrements the operand.
Eg. : a = 5; a=5;
b=a++; b=a--;
Result b=5, a=6 b=5, a=4;
• Generally a=a+1 can be written as ++a, a++ or a+=1.
• Similarly a=a-1 can be written as a--, --a or a -= 1.
16
6. Conditional operator (ternary operator):
• Conditional expressions are of the following form.
Exp1? Exp2: Exp3;
• Exp1 is evaluated first if the result is true then exp2 is
evaluated else exp3 is evaluated and that value
becomes the value of the expression.
• For example, consider the following statements.
a=10;
b=15;
x = (a>b)? a : b; in this example x will be assigned the value of b.
(x=15)
17
Control Statements
• A program is usually not limited to a linear
sequence of instructions.
• During its process it may split, repeat code
or take decisions.
• A block is a group of statements which are
separated by semicolons (;), but grouped
together in a block enclosed in braces: { }:
{ statement1;
statement2;
statement3;
}
18
• A statement can be either a simple statement
(a simple instruction ending with a semicolon)
or a compound statement (several
instructions grouped in a block).
• In a simple statement, we do not need to
enclose it in braces ({}). But in the case of
compound statement it must be enclosed
between braces ({}), forming a block.
19
• Control statements alter the flow of the program
• Used to cause the flow of control to advance and
branch based on changes to the state of a
program.
• Control statements are categorized in to three.
Control Statements
Selection Stat.
Iteration Stat.
Jump
Statements
20
A. Selection Statements
• It is also called as a decision making statements.
• used to choose different paths of execution based
upon the outcome of an expression or the state of a
variable.
• There are two types of selection/decisions statements
Selection
Statements
If Statements
Switch
Statements
21
If Statements
• If statement is used to test the condition.
• It checks Boolean condition: true or false.
• There are three types of if statements in C++. These are:-
If Statements
Simple if
If else
If-else-if Ladder
22
Simple If Statement
• The statements will be evaluated if the value of the
condition is true.
Syntax:
if (Condition)
{
statement1;
}
rest_of_program
Fig. 1 Simple If Statement Flow chart
• Condition is the expression that is being evaluated.
23
Example
• If this condition is true, statement is executed. If it is
false, statement is ignored (not executed)
• For example,
if (x == 100) if (x ==100)
cout<<"x is 100"; {
cout<<"x is ";
cout<< x;
}
• If more than a single statement to be executed in case
that the condition is true we can specify a block using
braces { }:
24
Example 1: Example 2:
#include<iostream.h> #include<iostream.h>
int main() int main()
{ {
int a = 10, b=20;
int a = 10, b=20;
if (a < b){
if (a < b)
cout<<"a is less than b \n";
cout<<"a is less than b"; cout<<"block statement ";
return 0; }
} return 0;
}
Exercise
• Write a program to check a student is passed
• Write a program to display “you are adult” when age is greater
than 18.
• Write a program to check a given number is Even 25
If-Else Statement
• If-else followed by an optional else statement, which
executes when the Boolean expression is false.
if (Condition)
{
statement1;
}
else
{
statement2;
}
next_statement;
• Statement 1 is evaluated if the value of the condition is
true, otherwise statement 2 is evaluated.
• It is used to take decision based on a single condition
26
Example: 1 Example: 2
#include<iostream.h>
int main( ) if (x == 100)
{ cout<<"x is 100";
Else
int age=17;
cout<<"x is not 100";
if (age>18)
cout<<"You Can Vote";
else
cout<<"Voting is not allowed";
return 0; }
Exercise:
Write a program using if-else statement for:
A. Student is passed or failed
B. To identify a given number is positive or Negative
C. Write a program to check a given number is Odd or Even 27
If-else-if ladder Statement
• Executes one condition from multiple statements.
• very useful to test various conditions using single
if...else if statement.
• Used when:
– An if can have zero or one else's and it must come
after any else if's.
– An if can have zero to many else if's and they must
come before the else.
– Once an else if succeeds, none of the remaining else
if's or else's will be tested.
28
Cont’d …
• Syntax:
if(condition1){
Statement 1 ;
}
else if(condition2)
{
Statement 2 ;
}
else if(condition3)
{
Statement 3;
}
...
else{
Statement n;
} 29
Example: 1 Example: 2
#include<iostream.h>
int main() if (x > 0)
{ cout<<"x is positive";
int x=30; else if (x < 0)
cout<<"x is negative";
if (x==10)
Else
cout<<"Value of X is 10"; cout<<"x is 0";
else if(x==20)
cout<<"Value of X is 20";
else if(x==30)
cout<<"Value of X is 30";
else
cout<<"unknown value";
return 0;
}
30
Exercise:
• Write a program that displays grade of a student
using fixed scale system.
• Write a code that accepts three integer values from
the user then it displays:
– The maximum integer number
– The minimum integer number
• Write a program to display days of a week using if
else if ladder.
31
Switch Statements
• executes one statement from multiple conditions [as if else if ]
• allows a variable to be tested for equality against a list of
values.
• Each value is called a case, and the variable being switched on
is checked for each case.
• You can have any number of case statements.
• Syntax:
switch(expression) {
case value 1:
// statements;
break;
case value 2:
// Statements
break;
default : // Optional } 32
Cont’d …
• When a break statement is reached, the switch terminates,
and the flow of control jumps to the next line following the
switch statement.
• If no break appears, the flow of control will fall through to
subsequent cases until a break is reached.
N.B: No break is needed in the default case
33
34
Example 1
#include<iostream.h> case 'D':
int main( ) cout<<"Satsfactory";
{ break;
char grade='B'; case 'F':
switch(grade){ cout<<"You Failed, Work Hard";
case 'A': break;
cout<<"Excellent"; default:
break; cout<<"Invalid Input";
case 'B': }
case 'C': return 0;
cout<<"Well done"; }
break;
35
Switch example if-else equivalent
switch (x) { if (x == 1)
case 1:cout<< "x is 1"; {cout<< "x is 1"; }
break;
else if (x == 2) {
case 2:cout<< "x is 2";
break;
cout<< "x is 2"; }
default:cout<< "value of x else {cout<< "value of x
unknown"; } unknown"; }
Exercise
• Write a program to display days of a week using switch
statement
• Write a program to perform the arithmetic operations
using switch [ +, -, * and / ]
36
B. Iteration Statements
• Also known as a looping statements.
• It allows to you to execute a statement or block of
statements repeatedly.
• Executes a block of statements when a particular
condition is true
• There are three types of loops in C++:
• for loops
• while loops
• do-while loops
37
For Loop
Syntax:
for (initialization; Condition; increme/decrement ) {
statement;
}
How for loop works:
• The initialization step is executed first, and only once.
– This step allows you to declare and initialize variables.
– You are not required to put a statement here, as long as a semicolon
appears.
• Next, the condition is evaluated.
– If it is true, the body of the loop is executed.
– If it is false, the body of the loop does not execute and flow of
control jumps to the next statement just after the for loop.
• After the body of the for loop executes, the flow of control
jumps back up to the increm/decr statement.
– This statement allows you to update variables. 38
• For loop allows you
to efficiently write a
loop that needs to
be executed a
specific number of
times.
• A for loop is useful
when you know how
many times a task is
to be repeated.
for loop is used to iterate a part of the
program several times.
If the number of iteration is fixed, it is
39
recommended to use for loop.
Example 1: Example: 2
#include<iostream.h>
int main(){ int sum = 0;
for(int num = 0; num<= 10;num++) for(int i = 1; i <= 10;i++) {
{ sum += i;
if(num % 2 == 0) }
cout<<"even: "<<num;
else • What is the value
cout<<"odd: "<<num;
} of sum?
return 0;
} Solution
Solution
prints out each integer from 1+2+3+4+5+6+7
0 to 10, + 8 + 9 + 10 = 55
correctly labeling them even
or odd
40
Cont’d …
• If there is more than one variable to set up or
increment they are separated by a comma.
for(i=0, j=0; i*j<100;i++,j+=2){
cout<<(i * j);
}
• You do not have to fill all three control expressions
but you must still have two semicolons.
int n = 0;
for(; n <= 100;)
{
cout<<(++n);
41
}
Exercise
1. write a program using for loop
A. counts up starting from 10-20
B. count down from 10-0
// count up using for loop // countdown using a for loop
#include <iostream.h> #include <iostream.h>
//using namespace std; int main (){
int main () for (int n=10; n>0; n--)
{ // for loop execution {
cout << n << ", ";
for(int a = 10; a <=20; a = a + 1 ) }
{ cout << "FIRE!";
cout<< "value of a: " << a <<endl; return 0;
} }
return 0;
} // outputis:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
value of a: 10………..20
42
While Loop
• This while loop executes as long as the given logical
expression between parentheses is true.
• Syntax: initialization;
while (expression){
statement;
Increment/decrement;
}
• The expression is tested at the beginning of the loop, so if
it is initially false, the loop will not be executed at all.
• if the boolean_expression result is true, then the actions
inside the loop will be executed. This will continue as long
as the expression result is true.
43
Cont’d … Example 1:
#include<iostream.h>
int main(){
int sum = 0;
int i = 1;
while (i <= 10){
sum += i;
i++;
}
cout<<"Sum="<<sum;
return 0;
}
What is the value of sum? Solution
1+2+3+4+5+6+7+8
+ 9 + 10=55
Sum= 55 44
Example 2:
#include<iostream.h> Output
int main( ){ value of x : 10
int x = 10;
value of x : 11
while( x < 20 ) {
value of x : 12
cout<<"value of x : "<< x;
x++; value of x : 13
cout<<"\n"; value of x : 14
} value of x : 15
return 0; } value of x : 16
Exercise: value of x : 17
1. write a program using while loop value of x : 18
A. counts up starting from 1-50 value of x : 19
B. count down starting from user input 45
do … while
• It is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
Syntax:
initialization;
do {
// Statements;
// increment/decrement;
}
while(Boolean_expression);
46
Cont’d …
• do…while repetition statement is similar to the while
statement.
• do…while statement tests the condition after executing
the loop’s body.
• Therefore, the body always executes at least once.
When a do…while statement terminates, execution
continues with the next statement in sequence.
47
Example
#include<iostream.h> Output
int main( ) { value of x : 10
int x = 10; value of x : 11
do { value of x : 12
value of x : 13
cout<<"value of x : " <<x ; value of x : 14
x++; value of x : 15
cout<<"\n"; value of x : 16
} value of x : 17
while( x < 20 ); value of x : 18
value of x : 19
return 0;
}
48
Jump Statements
• Also known as a loop control statements
• Loop control statements change execution from its normal
sequence.
goto
49
Break Statement
• It uses the break keyword in the given looping statements.
• break is used to break loop or switch statement.
• Two usages of break in C++
– It breaks the current flow of the program at specified
condition.
– In case of inner loop, it breaks only inner loop.
50
Example 1
// break loop if (n==3) {
example cout<<"countdown aborted!";
#include break;
<iostream> }
int main (){ }
int n; return 0;
for (n=10; n>0; n-- }
) // 10, 9, 8, 7, 6, 5, 4, 3, countdown
{ aborted
cout<< n <<", ";
51
Continue Statements
• This statement is used only within looping
statements
• It continues the current flow of the program and
skips the remaining code at specified condition
• When the continue statement is encountered, the
next iteration starts.
// continue loop example if (n==5) continue;
#include <iostream> cout<< n <<", ";
Using namespace std; }
int main (){ cout<<"FIRE!\n";
for (int n=10; n>0; n--) return 0;
{ }
//10,9,8,7,6,4,3,2,1,fire
52
Syntax: Example:
#include<iostream.h>
int main( ){
for(int i=1;i<=10;i++){
if(i%2==0)
continue;
cout<<i;
}
return 0;
}
53
goto statement
• allows to make an absolute jump to another
point in the program.
• You should use this feature with caution since its
execution causes an unconditional jump
• The destination point is identified by a label,
which is then used as an argument for the goto
statement.
• A label is made of a valid identifier followed by a
colon (:)
54
• Example, here is our countdown loop using
goto:
// goto loop example cout<< n <<", ";
#include <iostream> n--;
Using namespace std; if (n>0) goto loop;
int main () cout<<"FIRE!\n";
{ return 0;
int n=10; }
loop: 10,9,8,7,6,5,4,3,2,1,fire
55
Thank You
?
56