Chapter 1
Chapter 1
Fundamentals of C++
2
Constants
• refers to fixed values that do not change during the
execution of a program.
• Syntax of constant declaration and initialization:
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
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.
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 (+ + / - -):
Eg. : a = 5; a=5;
b=++a; b=--a;
Result a=b=6; a=b=4;
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 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
if (x == 100) if (x ==100)
cout<<"x is 100"; {
cout<<"x is ";
cout<< x;
}
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:
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
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 …
int n = 0;
for(; n <= 100;)
{
cout<<(++n);
41
}
Exercise
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.
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:
55
Thank You
?
56