Professional Documents
Culture Documents
C++ MAK Sheet
C++ MAK Sheet
Abdul Khalek
Department of Statistics
University of Rajshahi
Rajshahi-6205, Bangladesh
Note: This class note is not sufficient for the preparation of the examination. It is prepared just to give basic
concepts of C++. Detail contents will be discussed in the class. The students are suggested to follow the
class-lectures, to solve the home tasks, and to read the books (given in the syllabus). Most welcome your
comments to improve this class note in future.
© CPP_MAK_Stat.RU 3
Definition: Program
Types of Instructions
There are basically three types of instructions in C++:
(a) Type Declaration Instruction – This instruction is used
to declare the type of variables used in a C++ program.
(b) Arithmetic Instruction – This instruction is used to
perform arithmetic operations on constants and variables.
(c) Control Instruction – This instruction is used to control
the sequence of execution of various statements in a
C++ program.
© CPP_MAK_Stat.RU 4
Programing Language:
There are many different languages that can be
used to program a computer. These can be
classified into three groups:
Low-level Language (machine language).
High-level Language (Fortran, C++, BASIC etc.)
© CPP_MAK_Stat.RU 5
Historical Perspective
The C++ programming language was created by Bjarne
Stroustrup and his team at Bell Laboratories (AT&T, USA).
The earliest versions, which were originally referred to as “C
with classes,” date back to 1980. C++ was derived from the C
programming language: ++ is the increment operator in C.
As early as 1989 an ANSI Committee (American National
Standards Institute) was founded to standardize the C++
programming language. The aim was to have as many
compiler vendors and software developers as possible agree
on a unified description of the language in order to avoid the
confusion caused by a variety of dialects.
In 1998 the ISO (International Organization for Standardization)
approved a standard for C++ (ISO/IEC 14882).
© CPP_MAK_Stat.RU 6
© CPP_MAK_Stat.RU 8
© CPP_MAK_Stat.RU 9
Screen output
Enjoy yourself with C++!
© CPP_MAK_Stat.RU 10
Example 01:
Ramesh’s basic salary is input through the keyboard. His dearness allowance
is 20% of basic salary, and house rent allowance is 50% of basic salary. Write a
program to calculate his gross salary.
Computer Language
Machine language
Machine language is a low-level language comprised of binary
digits (ones and zeros).
• Only the language computer directly understands
• Defined by hardware design
• Generally consist of strings of numbers
‐ Ultimately 0s and 1s
• Instruct computers to perform elementary operations
‐ One at a time
• Cumbersome for humans
Example:
1 2 3 4 5 6 7 8
13 = 0 0 0 0 1 1 0 1
47 = 0 0 1 0 1 1 1 1 1 byte
-21 = 1 0 0 1 0 1 0 1
© CPP_MAK_Stat.RU 14
What is Compiler?
A compiler is system software which converts programming
language code into binary format in single steps. In other
words, compiler is a system software which can take input
from other any programming language and convert it into
lower level machine dependent language.
© CPP_MAK_Stat.RU 16
© CPP_MAK_Stat.RU 17
© CPP_MAK_Stat.RU 18
New line
Output
// Program for temperature conversion
Fahrenheit Celsius
#include<stdio.h>
0 ‐17
main()
20 ‐6
{
40 4
int Fah, Cel; 60 15
int low, upper, step; 80 26
low = 0; 100 37
upper = 300; 120 48
step = 20; 140 60
Fah = low; 160 71
while(Fah <= upper){ 180 82
Cel = (5/9)*(Fah - 32); 200 93
printf("%d \t%d\n", Fah, Cel); 220 104
Fah = Fah + step; 240 115
} 260 126
280 137
}
300 148
© CPP_MAK_Stat.RU 21
Sample-01: Programs
Output
// Program for temperature conversion using FOR statement Fahrenheit Celsius
#include<stdio.h> 0 -17.78
main() 20 -6.67
{ 40 4.45
int Fah; 60 15.56
for (Fah=0; Fah <= 300; Fah = Fah + 20) 80 26.67
printf("%3d %8.2f\n", Fah, (5.0/9.0)*(Fah-32)); 100 37.78
} 120 48.89
140 60.00
160 71.12
180 82.23
200 93.34
220 104.45
240 115.56
260 126.67
280 137.78
300 148.89
© CPP_MAK_Stat.RU 22
Output
Fahrenheit Celsius
// Program for temperature conversion using FOR statement
0 -17.78
#include<stdio.h> 20 -6.67
#define lower 0 40 4.45
#define upper 300 60 15.56
#define step 20 80 26.67
main() 100 37.78
{ 120 48.89
int fah; 140 60.00
for(fah=lower; fah<=upper; fah=fah+step) 160 71.12
printf("%3d %12.2f\n", fah, (5.0/9.0)*(fah- 180 82.23
32)); 200 93.34
} 220 104.45
240 115.56
260 126.67
280 137.78
300 148.89
© CPP_MAK_Stat.RU 23
Sample-01: Programs
// Write a C++ program that displays the memory space required by each fundamental type on screen.
#include <iostream>
using namespace std;
int main()
{
cout << "\nSize of Fundamental Types\n"
<< " Type Number of Bytes\n"
<< "----------------------------------" << endl;
cout << " char: " << sizeof(char) << endl;
cout << " short: " << sizeof(short)<< endl;
cout << " int: " << sizeof(int) << endl;
cout << " long: " << sizeof(long) << endl;
cout << " float: " << sizeof(float)<< endl;
cout << " double: " << sizeof(double)<<endl;
cout << " long double: " << sizeof(long double)<< endl;
return 0;
}
© CPP_MAK_Stat.RU 24
© CPP_MAK_Stat.RU 25
Sample-01: Programs
© CPP_MAK_Stat.RU 26
© CPP_MAK_Stat.RU 27
© CPP_MAK_Stat.RU 28
Features of C++
Mid-Level
Portable Structured
Rich
Simple Library
Memory Object
C++ Features
Management Oriented
Extensible Recursion
Features of C++
© CPP_MAK_Stat.RU 34
7) Speed
The compilation and execution time of C++ language is
fast.
8) Pointer
C++ provide the feature of pointers. We can directly
interact with memory by using the pointers. We can use
pointers for memory, structures, functions, array etc.
9) Recursion
In C++, we can call the function within the function. It
provides code reusability for every function.
© CPP_MAK_Stat.RU 35
Features of C++
10) Extensible
C++ language is extensible because it can easily adopt
new features.
11) Object Oriented
C++ is object oriented programming (OOP) language.
OOPs makes development and maintenance easier.
12) Compiler based
C++ is a compiler based programming language, it
means without compilation no C++ program can be
executed. First we need to compile our program using
compiler and then we can execute our program.
© CPP_MAK_Stat.RU 36
Digits:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols:
~ ‘ ! @ # % ^ & * () _ ‐ + = | \ {} [] : ; “ <> , . ? / $
© CPP_MAK_Stat.RU 37
© CPP_MAK_Stat.RU 38
a, b, …, z Lowercase * Asterisk
! Exclamation + Plus
' Single quotation , Comma
" Double quotation - Minus/hyphen
# Number sign . Period
$ Dollar sign / Slash
% Percent sign : Colon
& Ampersand sign ; Semi-colon
© CPP_MAK_Stat.RU 39
© CPP_MAK_Stat.RU 40
Character Meaning
\a Audible alert (bell)
\b Back space
\n New line
\t Horizontal tab
\v Vertical tab
\f Form feed
\r Carriage return
\0 string terminating character
© CPP_MAK_Stat.RU 41
Types of
Constants
Primary Secondary
Constants Constants
© CPP_MAK_Stat.RU 42
© CPP_MAK_Stat.RU 43
Definitions: Constants
© CPP_MAK_Stat.RU 44
Example: +326.34
-482.0
100.75
© CPP_MAK_Stat.RU 45
Definitions: Constants
Floating-point Constants
© CPP_MAK_Stat.RU 46
Example: 'A'
‘I'
‘5'
‘='
© CPP_MAK_Stat.RU 48
Exercise: Constants
© CPP_MAK_Stat.RU 50
Definitions: Variables
© CPP_MAK_Stat.RU 52
char float
int double
© CPP_MAK_Stat.RU 53
Definitions: Declaration
A declaration tells the compiler the name and type of a variable
used in the program. In its simplest form, a declaration consists
of the type, the name of the variable, and a terminating
semicolon:
char c;
int i;
float f;
Several variables of the same type also can be declared in one
declaration, separating them with commas:
int i1, i2;
A declaration for a variable can also contain an initial value. This
initializer consists of an equals sign and an expression, which is
usually a single constant:
int i = 1;
int i1 = 10, i2 = 20;
© CPP_MAK_Stat.RU 54
Examples
Variable name Validity? Remark
john Valid
ph_value Valid
char Invalid char is a keyword.
mark Valid
price$ Invalid Dollar sign is illegal.
group one Invalid Blank space is not permitted.
25th Invalid Name can not begin with digit.
average_number Valid First eight characters are significant.
average number Invalid Blank space is not permitted.
Exercise: Variables
© CPP_MAK_Stat.RU 56
© CPP_MAK_Stat.RU 57
Definitions: Variable
© CPP_MAK_Stat.RU 59
© CPP_MAK_Stat.RU 60
© CPP_MAK_Stat.RU 61
Arithmetic Instruction
An arithmetic instruction in C consists of a variable name on the
left hand side of = and variable names and constants connected
using operators on the right hand side of =.
Ex.: int ad ;
float kot, deta, alpha, beta, gamma ;
ad = 3200 ;
kot = 0.0056 ;
deta = alpha * beta / gamma + 3.2 * 2 / 5 ;
Here,
*, /, -, + are the arithmetic operators.
= is an assignment operator.
ad is an integer variable.
kot, deta, alpha, beta, gamma are real variables.
© CPP_MAK_Stat.RU 62
© CPP_MAK_Stat.RU 63
Definitions:
© CPP_MAK_Stat.RU 64
© CPP_MAK_Stat.RU 65
Definitions:
© CPP_MAK_Stat.RU 66
Forth = Assignment
© CPP_MAK_Stat.RU 67
© CPP_MAK_Stat.RU 68
Expression
© CPP_MAK_Stat.RU 70
© CPP_MAK_Stat.RU 71
Exercise:
Example: What will be the output of the following programs?
# include <stdio.h>
int main( )
{
int i = 2, j = 3, k, l ;
float a, b ;
k=i/j*j;
l=j/i*i;
a=i/j*j;
b=j/i*i;
printf ( "%d %d %f %f\n", k, l, a, b ) ;
return 0 ;
Output:
} 0 2 0.000000 2.000000
© CPP_MAK_Stat.RU 72
© CPP_MAK_Stat.RU 73
© CPP_MAK_Stat.RU 75
Definitions: Declaration
© CPP_MAK_Stat.RU 77
There are certain rules about the form of a C++ program that are
applicable to all C++ programs. These are as under:
(a) Each instruction in a C++ program is written as a separate
statement.
(b) The statements in a program must appear in the same order
in which we wish them to be executed.
(c) Blank spaces may be inserted between two words to improve
the readability of the statement.
(d) All statements should be in lower case letters.
(e) C++ has no specific rules for the position at which a statement
is to be written in a given line. That’s why it is often called a
free-form language.
(f) Every C++ statement must end with a semicolon ( ; ). Thus ;
acts as a statement terminator.
© CPP_MAK_Stat.RU 78
© CPP_MAK_Stat.RU 79
© CPP_MAK_Stat.RU 80
© CPP_MAK_Stat.RU 81
Basic Commands
%d print as integer
© CPP_MAK_Stat.RU 83
© CPP_MAK_Stat.RU 84
© CPP_MAK_Stat.RU 85
Definitions: Expression
© CPP_MAK_Stat.RU 86
© CPP_MAK_Stat.RU 88
i=2*3/4+4/4+8-2+5/8
Stepwise evaluation of this expression is shown below:
i=2*3/4+4/4+8-2+5/8
i=6/4+4/4+8-2+5/8 operation: *
i=1+4/4+8-2+5/8 operation: /
i = 1 + 1+ 8 - 2 + 5 / 8 operation: /
i=1+1+8-2+0 operation: /
i=2+8-2+0 operation: +
i = 10 - 2 + 0 operation: +
i=8+0 operation : -
i=8 operation: +
© CPP_MAK_Stat.RU 90
Arithmetic Operators
All multiplication (*), division (/) and modular division (%)
perform first.
All addition (+) and subtraction (-) next.
When the order of precedence of operators is the same,
such as in multiplication and division, operators will be
performed in order from left to right.
© CPP_MAK_Stat.RU 91
Parentheses Rule
© CPP_MAK_Stat.RU 92
/***************************************************************************/
/* PROGRAM TO CONVER DAYS INTO MONTHS AND DAYS */
/* Page No: 49 (Balagurusamy, 2nd Edition) */
/***************************************************************************/
#include<stdio.h>
main()
{
int months, days;
printf("Enter days\n");
scanf("%d", &days);
months = days / 30;
days = days % 30;
printf("Months = %d and Days = %d", months, days);
}
© CPP_MAK_Stat.RU 93
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
An expression containing relational operator is termed as relational
expression. The value of relational expression is either one or zero. It is one if
the specified relation is true and zero if the relation is false.
When the arithmetic expression are used on either side of relational
operators, the arithmetic operation will be evaluated first and then the results
compared.
Relational expressions are used in decision statement such as if and while.
© CPP_MAK_Stat.RU 94
Examples
If i = 1, j = 2 and k = 3
Expression Interpretation Value
i<j True 1
i + j >= k True 1
i + k = i +5 False 0
k != 3 False 0
j == 2 True 1
© CPP_MAK_Stat.RU 95
The operators which combine two or more relational expressions are known
as logical operators. C++ has the following three logical operators:
Operator Meaning
&& logical AND
logical OR
! logical NOT
Examples
Statement with Statement with simple
shorthand operator assignment operator
a += 1 a = a +1
a -= 1 a = a -1
a *= n + 1 a = a * (n + 1)
a /= n + 1 a = a / (n + 1)
a %= b a=a%b
© CPP_MAK_Stat.RU 98
Example:
i++ i=i+1 j-- j=j-1
++i i=i+1 --j j=j-1
© CPP_MAK_Stat.RU 99
Examples
Example-1: m = 5;
y = ++m; [In this case y = 6 and m = 6]
A prefix operator first adds 1 to the operand and then the result is
assigned to the variable on the left.
Example-2: m = 5;
y = m++; [In this case y = 5 and m = 6]
A postfix operator first assigns the value to the variable on the left
and then increments the operand.
m += n++ - j +10;
If m, n and j have the values 1, 2 and 3 respectively, then determine
the value of m.
© CPP_MAK_Stat.RU 100
if statement
The if keyword is used to executive a statement or block, if,
and only if, a condition is fulfilled. The if statement has a
simple structure.
if(condition)
Statement (or group of statements)
© CPP_MAK_Stat.RU 101
Start
True False
Statement 1 if (Condition) Statement 2
Print Output
Stop
© CPP_MAK_Stat.RU 102
if else statement
We have seen that the if structure executes its block of
statement(s) only when the condition is true, otherwise the
statements are skipped. The it/else structure allows the
programmer to specify that a different block of statement(s)
is to be executed when the condition is false. The structure
of if/else selection is as follows.
if(condition)
{
statement(s);
}
else
{
statement(s);
}
© CPP_MAK_Stat.RU 103
Sample: Program
#include<iostream>
using namespace std;
main()
{
int OmarAge, AliAge;
OmarAge = 12;
if(OmarAge > AliAge)
cout << "Omar is older than Ali";
}
© CPP_MAK_Stat.RU 104
Exercise
// What will be the output of the following programs
# include <stdio.h>
int main( )
{
int i = 2, j = 3, k, l ;
float a, b ;
k=i/j*j;
l=j/i*i;
a=i/j*j;
b=j/i*i;
printf ( "%d %d %f %f\n", k, l, a, b ) ;
}
Answer: a = 2 b = -2 c = 2 d = -2
© CPP_MAK_Stat.RU 107
© CPP_MAK_Stat.RU 109
Definitions: Algorithm
© CPP_MAK_Stat.RU 111
Circle Connector
Corrector
© CPP_MAK_Stat.RU 112
1) Start
2) Read two numbers as n1 and n2.
3) if n1 > n2 then set large = n1, otherwise large = n2.
4) Print the value of large.
5) end.
© CPP_MAK_Stat.RU 113
Example-01: Flowchart
Flowchart to find largest of two numbers
#include <iostream>
using namespace std;
int main()
{
int n1, n2; Start
cout<<"Enter first number:";
cin>>n1;
cout<<"Enter second number:";
cin>>n2;
if(n1>n2)
{ Read n1, n2
cout<<“1st number "<<n1<<“Largest";
}
else
{
cout<<“2nd number "<<n2<<" Largest";
} Yes No
}
return 0;
is n1 > n2
Print n2
Print n1
End
© CPP_MAK_Stat.RU 114
© CPP_MAK_Stat.RU 115
Example-02: Flowchart
Flowchart to find the largest of three numbers A, B and C:
START
A, B, C
B C C A
END
© CPP_MAK_Stat.RU 116
#include<iostream>
using namespace std;
int main() {
int num1,num2,num3;
cout<<" Enter value for first number: ";
cin>>num1;
cout<<" Enter value for second number: ";
cin>>num2;
cout<<" Enter value for third number: ";
cin>>num3;
if(num1>num2&&num1>num3) {
cout<<" First number is greatest:"<<endl<<"whick is= "<<num1;
} else if(num2>num1&&num2>num3) {
cout<<" Second number is greatest"<<endl<<"whick is= "<<num2;
} else {
cout<<" Third number is greatest"<<endl<<"whick is= "<<num3;
}
return 0;
}
© CPP_MAK_Stat.RU 117
int main() {
float n1, n2, n3;
return 0;
}
© CPP_MAK_Stat.RU 118
int main() {
float n1, n2, n3;
return 0;
}
© CPP_MAK_Stat.RU 119
int main() {
float n1, n2, n3;
return 0;
}
© CPP_MAK_Stat.RU 120
Stop
© CPP_MAK_Stat.RU 121
Example-04: Flowchart
Problem: While purchasing certain items, a discount of 10% is offered if the
quantity purchased is more than 1000. If quantity and price per item are input
through the keyboard, write a program to calculate the total expenses.
© CPP_MAK_Stat.RU 122
© CPP_MAK_Stat.RU 123
Definitions: Arrays
MyArray[0] = 10
MyArray[4] = 10
10 20 30 40 50
MyArray[0] MyArray[1] MyArray[2] MyArray[3] MyArray[4]
© CPP_MAK_Stat.RU 124
rows
Array[0][0] Array[0][1] Array[0][2] Array[0][3] Array[0][4]
10 20 30 40 50
Array[0][0] Array[0][1] Array[0][2] Array[0][3] Array[0][4]
60 70 80 90 100
Array[1][0] Array[1][1] Array[1][2] Array[1][3] Array[1][4]
© CPP_MAK_Stat.RU 125
Sample: Program
Reserve
© CPP_MAK_Stat.RU 126
MyVar[i][j][k] ; I = 1, 2, 3; j = 1, 2, 3, 4; k = 1, 2, …, 5
© CPP_MAK_Stat.RU 127
Sample: Program
Reserve
© CPP_MAK_Stat.RU 128
IF statement
IF-ELSE Statement
IF ELSE-IF Statement
NESTED IF Statement
SWITCH Statement
TERNARY Statement
BREAK Statement
© CPP_MAK_Stat.RU 129
Definitions: IF Statement
False
{
Condition float a, b, c, d;
printf("Enter four integer values: \n");
True scanf("%d %d %d %d", &a, &b, &c, &d);
if(c-d!=0)
Statements {
d = (a+b)/(c-d);
Output
printf("Ratio = %f ", d);
}
End
}
Flowchart of simple if statement
© CPP_MAK_Stat.RU 131
Start
True False
Condition
Statements Statements
Statements
© CPP_MAK_Stat.RU 133
© CPP_MAK_Stat.RU 134
Start
False
Condition 1
False
Condition 2
True False
Condition n
True
True
© CPP_MAK_Stat.RU 137
Sample: Program
#include<iostream>
using namespace std;
int main() {
int score;
cout<< " Enter your score between 0-100\n"; cin >> score;
if(score >= 90)
{
cout << "Your Grade: A\n"; } else if(score >= 50 && score < 90)
{
cout << "Your Grade: B\n"; } else if (score >= 35 && score < 50)
{
cout << "Your Grade: C\n"; }
else
{
cout << "Your Grade: Failed\n"; }
return 0;
}
© CPP_MAK_Stat.RU 138
Start
True
Condition-1
True False
False Condition-2
Stop
© CPP_MAK_Stat.RU 139
#include<iostream>
using namespace std;
int main()
{
int a = 1000;
int b = 2500;
if(a == 100)
{
if(b == 200)
{
cout << "Value of a is 1000 and b is 2500" << endl;
}
}
cout << "The Exact Value of a is : " << a << endl;
cout << "The Exact Value of b is : " << b << endl;
return 0;
}
© CPP_MAK_Stat.RU 140
© CPP_MAK_Stat.RU 141
Repetitive Structures
Construction of Loop
initialization
A program loop consists of two segments:
initialization of counters and variables Enter
control statement
Condition
body of the loop
The control statement tests certain conditions Body of the
loop
and then directs the repeated execution of the
statements contained in the body of the loop. Exit
Program Loop
© CPP_MAK_Stat.RU 142
© CPP_MAK_Stat.RU 143
Repetitive Structures
while Statement
© CPP_MAK_Stat.RU 144
© CPP_MAK_Stat.RU 145
Repetitive Structures
#include<stdio.h>
main()
{
int n, count;
float x, s1, s2, s3, s4, mean, c2, c3, c4, b1, b2, r1,r2,r3,r4;
printf("Enter the value of n\n");
scanf("%d", &n);
How to use while statement s1 = 0.0; s2 = 0.0; s3 = 0.0; s4 = 0.0;
count = 1;
while(count <= n)
{
scanf("%f", &x);
s1 = s1 + x;
s2 = s2 + x*x;
Problem: s3 = s3 + x*x*x;
Calculate the s4 = s4 + x*x*x*x;
mean, variance,
1, 2, 2, 3, 3, 3, count++;
skewness and 4, 4, 4, 5, 5, 6, }
kurtosis of the 7, 8, 8, 10 mean = s1/n;
r1 = s1/n; r2 = s2/n; r3 = s3/n; r4 = s4/n;
data:
c2 = r2 - r1 * r1;
c3 = r3 - 3*r2*r1 + 2*(r1*r1*r1);
c4 = r4 - 4*r3*r1 + 6*r2*(r1*r1) - 3*r1*r1*r1*r1;
b1 = (c3*c3)/(c2*c2*c2);
b2 = c4/(c2*c2);
printf("Mean = %f\n", mean);
printf("Variance = %f\n", c2);
printf("Skewness = %f\n", b1);
printf("Kurtosis = %f\n", b2);
return (0);
}
© CPP_MAK_Stat.RU 146
On reaching the do-while statement, the program proceeds to evaluate the body of
the loop first. At the end of the loop, the condition in the while statement is
evaluated. If the condition is true, the program continues to evaluate the body of
the loop once again. This process continues as long as the condition is true.
When the condition becomes false, the loop will be terminated and the control
goes the statement that appears immediately after the while statement.
Since the condition is evaluated at the bottom of the loop, the do-while statement
provides an exit-controlled loop and therefore the body of the loop is always
executed at least once.
© CPP_MAK_Stat.RU 147
Repetitive Structures
do-while Statement
EXAMPLE
----------
sum = 0; Note the segments:
n = 1;
initialization
do
{ body of the loop
sum = sum + n*n;
n = n + 1; control statement
}
while(n <= 10)
printf(“Sum of square = %d\n”, sum);
---------
© CPP_MAK_Stat.RU 148
do-while Statement
#include<stdio.h>
main()
{
EXAMPLE:
int n, count;
Compute the following series: float x, sum
printf("Enter the value of n\n");
1 + 1/2 + 1/3 + + 1/n scanf("%d", &n);
sum = 0.0;
count = 1;
{
sum = sum + 1/count;
count = count + 1;
}
while(count <= n)
printf(“\nResult = %f”, sum);
return (0);
}
© CPP_MAK_Stat.RU 149
Repetitive Structures
for Statement
The for statement is the most commonly used looping statement in C. it is
an entry-controlled loop. The general form of the for statement if
for(initialization; condition; increment)
{
body of the loop;
}
Where initialization is used to initialize the control variables using
assignment statements. The value of control variable is tested using
condition. The condition is a relational expression. If the condition is true,
the body of the loop is executed, otherwise the loop is terminated. When
the body of the loop is executed, the increment is used to alter the value
of the control variables using a unary or assignment statement. Then
control is transferred back to the for statement and the new value of the
control variable is again tested to see whether it satisfies the loop
condition. If the condition is satisfied, the body of the loop is again
executed. This process continues till the value of the control variable fails
to satisfy the condition.
© CPP_MAK_Stat.RU 150
for Statement
EXAMPLE
© CPP_MAK_Stat.RU 151
Repetitive Structures
for Statement
#include<stdio.h>
main()
{
EXAMPLE: int n, count;
float x, sum
printf("Enter the value of n\n");
Compute the following series: scanf("%d", &n);
sum = 0.0;
1 + 1/2 + 1/3 + + 1/n for(count = 1; count <= n; count++)
{
sum = sum + n/count;
count = count + 1;
}
printf(“\nResult = %f”, sum);
return (0);
}
© CPP_MAK_Stat.RU 152
© CPP_MAK_Stat.RU 153
The for loop in C++ has several capabilities that are not found in
other loop constructions.
More than one variable can be initialized at a time in the for
statement. The statements
p = 1;
for(n = 0; n < 17; ++n)
Can be written as
for(p = 1, n = 0; n < 17; ++n)
Like the initialization section, the increment section may also
have more than one part. For example:
for(n = 1, m = 50; n < m; n = n + 1, m = m - 1)
{
p = m/n;
printf(“%d %d %d\n”, n, m, p);
}
© CPP_MAK_Stat.RU 154
© CPP_MAK_Stat.RU 155
© CPP_MAK_Stat.RU 156
Nesting of loop, that is, one for statement within another for
statement, is allowed in C. for example, two loops can be nested
as follows:
EXAMPLE
------------;
------------;
For(row = 1; row <= ROWMAX; ++row)
{
for(column = 1; column <= COLMAX; ++column)
{
y = row*column;
printf(“%4d”, y);
}
printf(“\n”);
}
------------;
------------;
© CPP_MAK_Stat.RU 158
© CPP_MAK_Stat.RU 161
GOTO Statement
The goto statement is used to alter the normal sequence of program execution
by transferring control to some other part of the program. In its general form,
the goto statement is written as
goto label;
Where label is any valid variable name that is placed immediately before the
statement where the control is to be transferred and the label must be followed
by a colon.
Main()
goto label; Label: {
-----------; statement; double x, y;
-----------; -----------; read:
----------; -----------; scanf(“%f”, &x)
label: ----------; If(x < 0) goto read;
statement; Goto label; y = sqrt(x);
printf(“%f %f\n”, x);
goto read;
}
© CPP_MAK_Stat.RU 162
Switch
Expression
Yes
Case - 1 Statement-1
No
Yes
Case - 2 Statement-2
No
Yes
Case - 2 Statement-3
No Default
Statement End
End Switch
Switch
© CPP_MAK_Stat.RU 164
Thanks a lot
Forest