Download as pdf or txt
Download as pdf or txt
You are on page 1of 83

Dr. Md.

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.

Main Recommended Books

For Exercise: Let Us C by Yashavant Kanetkar

© MAK_C++ Class Note 1


Definition: Program

 Language: A way to communicate with


human and computers.
 Program: A specific sequence of steps to
solve a particular problem.
 Programing Language: A language which is
used to write a program

© CPP_MAK_Stat.RU 3

Definition: Program

Program: A program is nothing but a set of instructions.

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

© MAK_C++ Class Note 2


Definition: Language

A program is a sequence of instructions that can


be executed by a computer. C++ (pronounced
see-plus-plus) is one of the most powerful
programming languages available.

 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

© MAK_C++ Class Note 3


Basic Steps: C++ Program
The following three steps are required to create and translate a
C++ program:
1. First, a text editor is used to save the C++ program in a text
file. In other words, the source code is saved to a source file.
2. The source file is put through a compiler for translation. If
everything works as planned, an object file made up of
machine code is created. The object file is also referred to as
a module.
3. Finally, the linker combines the object file with other modules
to form an executable file. These further modules contain
functions from standard libraries or parts of the program that
have been compiled previously.
It is important to use the correct file extension for the source file’s
name. Although the file extension depends on the compiler you
use, the most commonly found file extensions are .cpp and .cc.
© CPP_MAK_Stat.RU 7

Basic Steps: Example


 main() function is the entry point of any C++ program. It is the
point at which execution of program is started.
 When a C++ program is executed, the execution control goes
directly to the main() function.
 Every C++ program have a main() function.
main()
{
............
............
}

 main: is a name of function which is predefined function in C++


library.

© CPP_MAK_Stat.RU 8

© MAK_C++ Class Note 4


Basic Steps: Example

void main() Int main()


{ {
............ ............
............ ............
} }
In above syntax;
 void: is a keyword in C++ language, void means nothing,
whenever we use void as a function return type then that
function nothing return. here main() function no return any
value.
 In place of void we can also use int return type of main()
function, at that time main() return integer type value.

© CPP_MAK_Stat.RU 9

Basic Steps: Example


#include <iostream>
using namespace std;
int main()
{
cout << "Enjoy yourself with C++!" << endl;
return 0;
}

Screen output
Enjoy yourself with C++!

© CPP_MAK_Stat.RU 10

© MAK_C++ Class Note 5


Example: A program with some functions and comments
#include <iostream>
using namespace std;
void line(), message(); // Prototypes
int main()
{
cout << "Hello! The program starts in main()." << endl;
line();
message();
line();
cout << "At the end of main()." << endl;
return 0;
}
void line() // To draw a line.
{
cout << "--------------------------------" << endl;
}
void message() // To display a message.
{
cout << "In function message()." << endl;
}
© CPP_MAK_Stat.RU 11

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.

/* Calculate Ramesh’s gross salary */


# include <stdio.h>
int main( )
{
float bp, da, hra, grpay ;
printf ( "\nEnter Basic Salary of Ramesh: " ) ;
scanf ( "%f", &bp ) ;
da = 0.4 * bp ;
hra = 0.2 * bp ;
grpay = bp + da + hra ;
printf ( "Basic Salary of Ramesh = %f\n", bp ) ;
printf ( "Dearness Allowance = %f\n", da ) ;
printf ( "House Rent Allowance = %f\n", hra ) ;
printf ( "Gross Pay of Ramesh is %f\n", grpay ) ;
return 0 ;
}
© CPP_MAK_Stat.RU 12

© MAK_C++ Class Note 6


Example 02:
The distance between two cities (in kilometers) is input through the keyboard.
Write a program to convert and print this distance in meters, feet, inches and
centimeters.
/* Conversion of distance */
# include <stdio.h>
int main( )
{
float km, m , cm, ft, inch ;
printf ( "\nEnter the distance in Kilometers: " ) ;
scanf ( "%f", &km ) ;
m = km * 1000 ;
cm = m * 100 ;
inch = cm / 2.54 ;
ft = inch / 12 ;
printf ( "Distance in meters = %f\n", m ) ;
printf ( "Distance in centimeter = %f\n", cm ) ;
printf ( "Distance in feet = %f\n", ft ) ;
printf ( "Distance in inches = %f\n", inch ) ;
return 0 ;
}
© CPP_MAK_Stat.RU 13

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

© MAK_C++ Class Note 7


Computer Language
 High-level languages
High-level languages use English-like statements and
symbols, and are independent of the type of computer.

Example: C++, Cobol, Fortran, Pascal, Ada etc.


• Similar to everyday English, use common mathematical
notations
• Single statements accomplish substantial tasks
• Translator programs (compilers)
‐ Convert to machine language
• Interpreter programs
‐ Directly execute high-level language programs
Example:
if A < B, then B is rich.
© CPP_MAK_Stat.RU 15

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

© MAK_C++ Class Note 8


About C++
C++ (pronounced, see-plus-plus) is known to be the most
powerful and widely used programming language.
Bjarne Stroustrup developed in 1979 at American
Telephone & Telegraph (AT&T), at Bell Labs, New Jersy,
USA. Initially, its named was C Class, then in the year 1983
it was renamed as C++.
C++ is a general purpose high level, compiler based and
object oriented programming (OOP) language.
 General purpose programming language
 Case-sensitive
 Object-Oriented, procedural and functional program.
Source: https://www.w3adda.com/cplusplus-tutorial/cpp-history

© CPP_MAK_Stat.RU 17

Structure of a C++ program


A C++ program is structured in a specific and particular manner.
In C++, a program is divided into the following three sections:
1) Standard Libraries
2) Main Function
3) Function Body
// Sample program to display output
#include<stdio.h> Standard Libraries
main() Main function
{
printf("Hello, world! \n");
printf("This is the first c++ program"); Function body
}

© CPP_MAK_Stat.RU 18

© MAK_C++ Class Note 9


Structure of C++ Programs (1): Library – stdio.h

// Sample program to display output Single line comments


#include<stdio.h> Include information about standard library
main() Define a function named main that
receives no argument value
{ beginning of block for main
printf("Hello, world! \n");
output statement
printf("This is the first c++ program");
} end of block for main

New line

printf is a keyword to DISPLAY the OUTPUT


scanf is a keyword to READ the INPUT
© CPP_MAK_Stat.RU 19

Structure of C++ Programs (2): Library - iostream

1 // sample C++ program comment


2 #include <iostream> preprocessor directive
3 using namespace std; which namespace to use
4 int main() beginning of function named main
5 { beginning of block for main
6 cout << "Hello, there!"; output statement
7 return 0; send 0 back to the operating system
8 } end of block for main

Multiple Line Comments


/*
Comment line 1
Comment line 2
Comment line 3
*/
© CPP_MAK_Stat.RU 20

© MAK_C++ Class Note 10


Sample-01: Programs

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

© MAK_C++ Class Note 11


Sample-01: Programs

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

© MAK_C++ Class Note 12


Sample-01: Programs
// Calculating powers with the standard function pow()
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x = 2.5, y;
y = pow(x, 3.0);
y = pow(x, 3);
cout << "2.5 raised to 3 yields: " << y << endl;
// Calculating with pow() is possible:
cout << "2 + (5 raised to the power 2.5) yields: “
<< 2.0 + pow(5.0, x) << endl;
return 0;
}

© CPP_MAK_Stat.RU 25

Sample-01: Programs

// Circumference and area of a circle with radius 2.5


#include <iostream>
using namespace std;
const double pi = 3.141593;
int main()
{
double area, circuit, radius = 1.5;
area = pi * radius * radius;
circuit = 2 * pi * radius;
cout << "\nTo Evaluate a Circle\n" << endl;
cout << "Radius\t\t: " << radius << endl;
cout << "Circumference\t: " << circuit << endl;
cout << "Area\t\t: " << area << endl;
return 0;
}

© CPP_MAK_Stat.RU 26

© MAK_C++ Class Note 13


Special Characters for Program Structure

Character Name Description

// Double Slash Begins a comment

# Number Sign Begins preprocessor directive

Encloses filename used in


<> Open, Close Brackets
#include directive

() Open, Close Parentheses Used when naming function

{} Open, Close Braces Encloses a group of statements

"" Open, Close Quote Encloses string of characters

; Semicolon Ends a programming statement

© CPP_MAK_Stat.RU 27

Steps in Executing a C++ Program


 Creating the program.
 Linking the program with functions that are needed from
the C library
 Saving the program. (optional)
 Compiling the program.
 Fixing the syntax errors.
 Executing the program.

Compiling the program: F9

Executing the program: F10

© CPP_MAK_Stat.RU 28

© MAK_C++ Class Note 14


Why to learn C++
 C++ is a working professionals to become a great Software
Engineer.
 C++ is very close to hardware, so you get a chance to work at a
low level which gives you lot of control in terms of memory
management, better performance and finally a robust software
development.
 C++ programming gives us a clear understanding about Object
Oriented Programming (OOP).
 C++ is one of the ever green programming languages and loved
by millions of software developers.
 C++ is the most widely used programming languages in
applications and systems programming.
 C++ really teaches the difference between compiler, linker
and loader, different data types. storage classes, variable types
their scopes etc.
© CPP_MAK_Stat.RU 29

Difference between C and C++


SL C C++
1) C follows the procedural C++ is a object-Oriented
programming language. programming language.
2) The extension of a C program file The extension of a C++ program
is *.c file is *.cpp
3) Data is less secured in C. In C++, you can modifiers for class
members to make it inaccessible
for outside users.
4) C follows the top-down approach. C++ follows the button-up
approach.
5) C does not support function C++ supports function overloading
overloading
6) C does not support inline function C++ supports inline function
7) C does not support reference C++ supports reference variables.
variables.
8) C does not have namespace C++ have namespace feature
feature
© CPP_MAK_Stat.RU 30

© MAK_C++ Class Note 15


Difference between C and C++
SL C C++
9) In C, scanf() and printf() are C++ mainly uses stream cin and
mainly used for input/output. cout to perform input and output
operations
10) Operator overloading is not Operator overloading is possible
possible in C. in C++.
11) C programs are divided into C++ programs are divided into
procedures and modules. functions and classes.
12) C does not provide the feature of C++ supports the feature of
namespace. namespace.
13) Exception handling is not easy in C++ provides exception handling
C. It has to perform using other using try and catch block
functions.
14) C does not support the C++ support the inheritance.
inheritance.
15) C is function driven language C++ is an object driven language
© CPP_MAK_Stat.RU 31

Features of C++

Mid-Level
Portable Structured

Rich
Simple Library

Memory Object
C++ Features
Management Oriented

Extensible Recursion

Faster Compiler Pointers


Based
© CPP_MAK_Stat.RU 32

© MAK_C++ Class Note 16


Features of C++
1) Simple
C++ is a simple language in the sense that it provides
structured approach, rich set of library functions, data types
etc.
2) Machine Independent or Portable
Unlike assembly language, c++ programs can be executed
in many machines with little bit or no change. But it is not
platform independent.
3) Mid-level programming language
C++ is also used to do low level programming. It is used to
develop system applications such ass kernel, driver etc. It
also supports the feature of high level language. That is why
it is known as mid-level language.
© CPP_MAK_Stat.RU 33

Features of C++

4) Structured Programming Language


C++ is structured programming language in the sense
that we can break the program into parts using
functions. So, it is easy to understand and modify.
5) Rich Library
C++ provides a lot of inbuilt functions that makes the
development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In
C++ language, we can free the allocated memory at any
time by calling the free() function.

© CPP_MAK_Stat.RU 34

© MAK_C++ Class Note 17


Features of C++

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

© MAK_C++ Class Note 18


Basic Steps: Learning C++ Language
Steps in learning C++ language:
Alphabets Constants
Digits Variables Instruction Program
Special Symbols Keywords

Character Set: Alphabets, Digits and Special Symbols:


Alphabets:
Upper case: A, B, …, Z
Lower case: a, b, …, z

Digits:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Symbols:
~ ‘ ! @ # % ^ & * () _ ‐ + = | \ {} [] : ; “ <> , . ? / $

© CPP_MAK_Stat.RU 37

Definitions: Character Set

The set of characters that may appear in a legal C++


program is called character set. This set includes some
graphic as well as non-graphic characters.
 The graphic characters are those that may be
printed.
 The non-graphic characters are represented by
escape sequences consisting of a backslash (\)
followed by a letter.

The graphic characters, other than decimal digits,


letters, and blank, are referred to as special
characters.

© CPP_MAK_Stat.RU 38

© MAK_C++ Class Note 19


Definitions: Character Set: Graphic characters (1)

Character Meaning Character Meaning


0, 1, …, 9 Decimal digits ( Left parenthesis
A, B, …, Z Uppercase ) Right parenthesis

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

Definitions: Character Set: Graphic characters (2)

Character Meaning Character Meaning


< Less than ^ Caret/circumflex
= Equal to _ Underscore
> Greater than ] Right bracket
? Question mark { Left brace
@ “At” sign  Vertical bar
[ Left bracket } Right brace
\ Backslash ~ Tilde
` Back quotation Blank space

© CPP_MAK_Stat.RU 40

© MAK_C++ Class Note 20


Definitions: Character Set: Non-Graphic characters

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

Definitions: Constants, Variable and Keyword

A constant is an entity that doesn’t change, whereas, a variable


is an entity that may change. A keyword is a word that carries
special meaning.

Types of
Constants

Primary Secondary
Constants Constants

• Integer constant • Array


• Real constant • Pointer
• Character constant • Structure
• Union
• Enumeration etc.

© CPP_MAK_Stat.RU 42

© MAK_C++ Class Note 21


Definitions: Integer Constants

Rules for Constructing Integer Constants


(a) An integer constant must have at least one digit.
(b) It must not have a decimal point.
(c) It can be either positive or negative. If no sign precedes an
integer constant, it is assumed to be positive.
(d) No commas or blanks are allowed within an integer
constant.
(e) The allowable range for integer constants is -2147483648
to +2147483647.

Example: 426 +782 -8000 7605 -54023

© CPP_MAK_Stat.RU 43

Definitions: Constants

Rules for Constructing Real Constants


An integer constant is an integer-valued number. Thus, it
consists of a sequence of digits. Integer constants can be
written in three different number systems: decimal, Octal and
hexadecimal.

 Decimal Integer Constant: A decimal integer constant


consists of any combination of digits taken from the set 0
through 9, preceded by an optional – or + sign. If the constant
contain two or more digits, the first digit must be something
other than 0.
Valid decimal integer constants Invalid decimal integer constants
0 1 743 -321 654321 1,321 12 21 090 $43 1-2-3

© CPP_MAK_Stat.RU 44

© MAK_C++ Class Note 22


Definitions: Real Constants

Rules for Constructing Real Constants


Real constants are often called Floating Point constants. The
real constants could be written in two forms - Fractional form and
Exponential form. Following rules must be observed while
constructing real constants expressed in fractional form:
(a) A real constant must have at least one digit.
(b) It must have a decimal point.
(c) It could be either positive or negative.
(d) Default sign is positive.
(e) No commas or blanks are allowed within a real constant.

Example: +326.34
-482.0
100.75
© CPP_MAK_Stat.RU 45

Definitions: Constants

Floating-point Constants

A floating-point constant is a number that contains


either a decimal point or an exponent (or both)

Valid floating-point constants


0. 1. 0.0743 .0321 2E-8

0.0e-3 1.66E+8 .12121e12

Invalid floating-point constants


1 2E10.2 3E 10

© CPP_MAK_Stat.RU 46

© MAK_C++ Class Note 23


Definitions: Real Constants

Rules for Constructing Real Constants in Exponential Form


Following rules must be observed while constructing real
constants expressed in exponential form:
(a) The mantissa part and the exponential part should be
separated by a letter e or E.
(b) The mantissa part may have a positive or negative sign.
(c) Default sign of mantissa part is positive.
(d) The exponent must have at least one digit, which must be a
positive or negative integer. Default sign is positive.
(e) Range of real constants expressed in exponential form is
-3.4e38 to 3.4e38.
Example: +3.2e-5
4.1e8
-0.2E+3
© CPP_MAK_Stat.RU 47

Definitions: Character Constants

Rules for Constructing Character Constants


(a) A character constant is a single alphabet, a single
digit or a single special symbol enclosed within
single inverted commas.
(b) Both the inverted commas should point to the left.
For example, ’A’ is a valid character constant
whereas ‘A’ is not.

Example: 'A'
‘I'
‘5'
‘='

© CPP_MAK_Stat.RU 48

© MAK_C++ Class Note 24


Definitions: Constants

Single Character Constants


Single character constant (or simply character constant) contains a
single character enclosed within a pair of single quote marks.
Examples of character constants are:
‘5’ ‘X’ ‘;’ ‘’
Note that the character constant ‘5’ is not the same as the number 5.
The last constant is a blank space.

 Several character constants and their corresponding values as defined by


ASCII (American Standard Code for Information Interchange) character set
are shown below:
constants values
‘A’ 65
‘x’ 120
‘3’ 51
‘’ 32
© CPP_MAK_Stat.RU 49

Exercise: Constants

© CPP_MAK_Stat.RU 50

© MAK_C++ Class Note 25


Definitions: Variables

A variable is an identifier that is used to store a specified type of


data value. Unlike constants that remain unchanged during the
execution of a program, a variable may take different values at
different times during program execution.

Rules for Constructing Variable Names


(a) A variable name is any combination of 1 to 31 alphabets, digits or
underscores. Some compilers allow variable names whose length could
be up to 247 characters. Still, it would be safer to stick to the rule of 31
characters. Do not create unnecessarily long variable names as it adds
to your typing effort.
(b) The first character in the variable name must be an alphabet or
underscore. But discouraging to use underscore as first character.
(c) No commas or blanks are allowed within a variable name.
(d) No special symbol other than an underscore (gross_sal) can be used in
a variable name.
© CPP_MAK_Stat.RU 51

Definitions: Variables

 Location in memory where value can be stored


 Common data types
• int - integer numbers (%4d)
• char – characters (%12c)
• double - floating point numbers (%7.3f)
 Declare variables with name and data type before use
• int integer1;
• int integer2;
• int sum;
 Can declare several variables of same type in one
declaration
• int integer1, integer2, sum;

© CPP_MAK_Stat.RU 52

© MAK_C++ Class Note 26


Definitions: Data Type

 char – a single byte character.


 int – an integer number – usually 4 bytes.
 float – a single precision real number
– usually 4 bytes.
 double – a double precision real number
– usually 8 bytes.

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

© MAK_C++ Class Note 27


Definitions: Variables

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.

 If only the first eight characters are recognized by a computer then


average_hight average_weight
mean the same thing to the computer.
© CPP_MAK_Stat.RU 55

Exercise: Variables

© CPP_MAK_Stat.RU 56

© MAK_C++ Class Note 28


Exercise: Variables

© CPP_MAK_Stat.RU 57

Definitions: Variable

Variable is defined as the reserved memory space which stores a


value of a definite data type. The value of the Variable is not
constant, instead it allows changes. There are mainly five types of
variables supported in C++.
• Local variable
• Global variable
• Static variable
• Automatic variable
• External variable
Local Variable: Any variable that is declared at the inside a code
block or a function and has the scope confined to that particular
block of code or function is called to be a local variable.
void MyData(){
int LocalVar = 10;
}
© CPP_MAK_Stat.RU 58

© MAK_C++ Class Note 29


Definitions: Global Variables

Any variable that is declared at the outside a code block or a


function and has the scope across the entire program and allows
any function to change it's value is known as Global Variable.

int GlobalVar = 10;


void MyData()
{
int LocalVar = 20;
}

© CPP_MAK_Stat.RU 59

Definitions: Types of Instructions

There are three types of instructions in C++:


a) Type Declaration Instruction – This instruction is used to
declare the types 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 60

© MAK_C++ Class Note 30


Definitions: Types of Instructions

Type Declaration Instruction


This instruction is used to declare the types of variables being
used in the program. The type declaration instruction is written at
the beginning of main( ) function. A few examples are shown
below.
int bas ;
float rs, grosssal ;
char name, code ;

© CPP_MAK_Stat.RU 61

Definitions: Types of Instructions

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

© MAK_C++ Class Note 31


Definitions:

Integer and Float Conversions


To effectively develop C++ programs, it is necessary to
understand the rules used for implicit conversion of floating point
and integer values. These are mentioned below. Note them
carefully.
a) An arithmetic operation between an integer and integer
always yields an integer result.
b) An operation between a real and real always yields a real
result.
c) An operation between an integer and real always yields a real
result. In this operation, the integer is first promoted to a real
and then the operation is performed. Hence the result is real.

© CPP_MAK_Stat.RU 63

Definitions:

Integer and Float Conversions


To effectively develop C++ programs, it is necessary to
understand the rules used for implicit conversion of floating point
and integer values. These are mentioned below. Note them
carefully.
a) An arithmetic operation between an integer and integer
always yields an integer result.
b) An operation between a real and real always yields a real
result.
c) An operation between an integer and real always yields a real
result. In this operation, the integer is first promoted to a real
and then the operation is performed. Hence the result is real.

© CPP_MAK_Stat.RU 64

© MAK_C++ Class Note 32


Definitions:

Integer and float conversion


Operation Result Operation Result
5/2 2 2/5 0
5.0/2 2.5 2.0/5 0.4
5/2.0 2.5 2/5.0 0.4
5.0/2.0 2.5 2.0/5.0 0.4

© CPP_MAK_Stat.RU 65

Definitions:

Type conversion in assignments

© CPP_MAK_Stat.RU 66

© MAK_C++ Class Note 33


Definitions: Hierarchy of Operations

The priority or precedence in which the operations are performed


is called the hierarchy of operations.

Priority Operators Description


First () Parenthesis

Second * , /, % Multiplication, Division, Modular division

Third +, - Addition, Subtraction

Forth = Assignment

© CPP_MAK_Stat.RU 67

Exercise: Hierarchy of Operations

Problem: Determine the hierarchy of operations and


evaluate the following expression, assuming that k is a float
variable:
k=3/2*4+3/8
Solution:
k=3/2*4+3/8
k=1*4+3/8 operation: /
k=4+3/8 operation: *
k=4+0 operation: /
k=4 operation: +

© CPP_MAK_Stat.RU 68

© MAK_C++ Class Note 34


Exercise: Hierarchy of Operations
Example: Determine the hierarchy of operations and evaluate the
following expression, assuming that i is an integer variable:
i=2*3/4+4/4+8-2+5/8
Solution:
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 69

Expression

Algebraic expressions and their C++ equivalent

Algebraic Expression C++ Expression


ab – cd a*b – c*d
(m + n)(a + b) (m + n)*(a + b)
3x2 + 2x + 5 3*x*x + 2*x + 5
𝑎 𝑏 𝑐
(a + b +c)/(d + e)
𝑑 𝑒
2𝑏𝑦 𝑥
( 2*b*y/(d+1) – x/(3*(z+y)))
𝑑 1 3 𝑧 𝑦

area = r2 area = pi * r * r

© CPP_MAK_Stat.RU 70

© MAK_C++ Class Note 35


Expression

© 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

© MAK_C++ Class Note 36


Exercise:
Example: What will be the output of the following programs?
# include <stdio.h>
int main( )
{
int a, b, c, d ;
a=2%5;
b = -2 % 5 ;
c = 2 % -5 ;
d = -2 % -5 ;
printf ( "a = %d b = %d c = %d d = %d\n", a, b, c, d ) ;
return 0 ;
}
Output:
a =2 b = ‐2 c = 2 d = ‐2

© CPP_MAK_Stat.RU 73

Exercise: Find area of a triangle, given its sides


/* Find area of a triangle, given its sides */
# include <stdio.h>
# include <math.h> /* for sqrt( ) */
int main( )
{
float a, b, c, sp, area ;
printf ( "\nEnter sides of a triangle: " ) ;
scanf ( "%f %f %f", &a, &b, &c ) ;
sp = ( a + b + c ) / 2 ;
area = sqrt ( sp * ( sp - a ) * ( sp - b ) * ( sp - c ) ) ;
printf ( "Area of triangle = %f\n", area ) ;
return 0 ;
} Output:
Enter sides of a triangle: 4 5 6
Area of triangle = 9.921567
© CPP_MAK_Stat.RU 74

© MAK_C++ Class Note 37


Definitions: Arrays

The array is another kind of variable that is used extensively in C++.


An array is an identifier (or, variable) that refers to a collection of data
items that all have the same name and same type. The individual
array elements are distinguished from one another by the value that
is assigned to a subscript. The subscript associated with each
element is shown in squared braces. Example, xx[20]

 Each array element is referred to by an array name followed by


one or more subscripts.
 Each subscript must be expressed as a non-negative integer,
an integer variable or a more complex integer expression.
 The number of subscripts determines the dimensionality of the
array. For example, x[i] refers to an element in the one-
dimensional array x, y[i][j] refers to an element in the two-
dimensional array y. Higher-dimensional arrays can be formed by
adding additional subscript in the same manner.

© CPP_MAK_Stat.RU 75

Definitions: Declaration

A declaration associates a group of variables with a specific data type.


All variables must be declared before they can appear in executable
statements.
A declaration consists of a data type, followed by one or more variable
names, ending with a semicolon. Each array variable must be
followed by a pair of square brackets, containing a positive integer
which specifies the size of the array.

Example: In C program the following type of declarations are


frequently used:
int a, total, c = 5, count[10];
float b, root1, root2, value[50];
char flag, text[80];
double ratio;
© CPP_MAK_Stat.RU 76

© MAK_C++ Class Note 38


Definitions: Keywords and Identifiers

 Every C++ words is classified as either a keyword or an


identifier.
 All keywords have fixed meaning that cannot be changed and
must be written in lowercase.

© CPP_MAK_Stat.RU 77

Basic Structure: C++ Program

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

© MAK_C++ Class Note 39


Definitions: Input/Output Functions

An input/output function can be accessed from anywhere within


a program simply by writing the function name, followed by a list
of argument enclosed in parentheses. Some commonly used
input/output functions are:
 Single character input – The getchar Function
 Single character output – The putchar Function
 Entering input data – The scanf Function
 Writing output data – The printf Function
 The gets and puts Functions.

© CPP_MAK_Stat.RU 79

Definitions: printf and its purpose


printf( ) and its Purpose
C++ does not contain any instruction to display output on the screen. All
output to screen is achieved using readymade library functions. One
such function is printf( ). Let us understand this function with respect to
our program.
(a) Once the value of interest is calculated it needs to be displayed on
the screen. We have used printf( ) to do so.
(b) For us to be able to use the printf( ) function, it is necessary to use
#include <stdio.h> at the beginning of the program. #include is a
preprocessor directive.
(c) The general form of printf( ) function is,

© CPP_MAK_Stat.RU 80

© MAK_C++ Class Note 40


Definitions: scanf and its purpose
scanf( ) and its Purpose
scanf( ) function is a counter-part of the printf( ) function. printf( )
outputs the values to the screen whereas scanf( ) receives them from
the keyboard.
printf ( "Enter values of p, n, r" ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
The first printf( ) outputs the message ‘Enter values of p, n, r’ on the
screen.
The use of ampersand (&) before the variables in the scanf( ) function
is a must. & is an ‘Address of’ operator. It gives the location number
(address) used by the variable in memory.
When we say &a, we are telling scanf( ) at which memory location
should it store the value supplied by the user from the keyboard.

© CPP_MAK_Stat.RU 81

Basic Commands

printf : Use to print the Character, Result or Output


scanf : Use to Read Character or a Value Assign
int  %d char  %c string  %s float  %f

Header Files #include<conio.h>


#include<stdio.h>
#include<math.h>
Semicolon  ;
Open & Close Braces {
----
}
clrscr(); : Clear screen
getch(); : Hold Screen
© CPP_MAK_Stat.RU 82

© MAK_C++ Class Note 41


Format: Output Display Format

%d print as integer

%6d print as integer, at least 6 characters wide

%f print as floating point

%6f print as floating point, at least 6 characters wide

%.2f print as floating point, 2 characters after decimal point

%6.2f print as floating point, at least 6 wide and 2 after


decimal point

© CPP_MAK_Stat.RU 83

Integer and Float Conversions


In order to effectively develop C++ programs, it will be necessary
to understand the rules that are used for the implicit conversion of
floating point and integer values in C++.
(a) An arithmetic operation between an integer and integer
always yields an integer result.
(b) An operation between a real and real always yields a real
result.
(c) An operation between an integer and real always yields a real
result.

© CPP_MAK_Stat.RU 84

© MAK_C++ Class Note 42


Definitions: Assignment Statement

Assignment statement is used to assign values to variables


and has the form:
variable = expression
 Here expression may be a constant, another variable to which a
value has previously been assigned, or a formula which the
computer can evaluate.
 Here the “equal (=)” symbol is not a statement of algebraic equality,
rather it is a replacement statement and must be read as “is
assigned”. That is, the value of the variable on the left hand side of =
is set equal to the value of the quantity (or the expression) on the
right.
 The statement year = year +1 means that the “new value” of year is
equal to the “old value” of year plus 1.
 if A = 50.0 and B = 205.0 then A = B implies A = 205.0.

© CPP_MAK_Stat.RU 85

Definitions: Expression

Algebraic Expression C++ Expression


ab - cd a*b–c*d
(m + n)(a + b) (m + n)*(a + b)
3x2 + 2x + 5 3*x*x + 2*x + 5
𝑎 𝑏 𝑐
(a + b + c)/(d + e)
𝑑 𝑒
2𝐵𝑌 𝑥
2*b*y/(d+1) – x/2*(z + y)
𝑑 1 2 𝑧 𝑦
12𝑥 5𝑥 1
𝑟 r = 12*x*x*x/4*x + 5*x*x/3*x + 1/3*x
4𝑥 3𝑥 3𝑥
𝑥 3 𝑥
𝑧 z=(x+3)*x*x*x/(y-3)*(y+8)
𝑦 3 𝑦 8

© CPP_MAK_Stat.RU 86

© MAK_C++ Class Note 43


Definitions: Operators

An operator is a symbol that tells the computer to perform a


certain mathematical or logical manipulations. Operators are
used in programs to manipulate data and variables. They
usually form a mathematical or logical expression.
The operators used in C++ can be classified into a number of
categories. They include:
1) Arithmetic operators.
2) Relational operators.
3) Logical Operators.
4) Assignment operators.
5) Increment and decrement operators.
6) Conditional operators.
7) Bitwise operators.
8) Special operators.
© CPP_MAK_Stat.RU 87

Definitions: (1) Arithmetic Operations


There are five arithmetic operators available in C++. They are –
addition, subtraction, multiplication, division and remainder after
integer division. Arithmetic operators are used for numeric data.
Arithmetic Operators Symbol
Addition or unary plus + Note: C++ includes a class of
operators that act upon a
Subtraction or unary minus - single operand to produce a
Multiplication * new value. Such operators are
known as unary operator. For
Division / example: ‐(5) = ‐ 5
Modulus (Remainder) %

If a = 10 and b = 3 If a = 10.0 and b = 3.0 Note: If one operand is


floating-point type and the
a+b 13 a+b 13.0 other is an integer or a
a-b 7 a-b 7.0 character, the integer and
character will be converted
a*b 30 a*b 30.0 to the floating-point type.
a/b 3 a/b 3.33 For example:
a%b 1 a%b not used 7 + 3.12 = 10.12

© CPP_MAK_Stat.RU 88

© MAK_C++ Class Note 44


Rules: Precedence Order
Precedence Category Operator Associativity
1 Postfix (), [] Left to right
2 Unary +a, -a, !~a (logical not), ++a, - -a Right to left
3 Multiplicative *, /, % Left to right
4 Additive +, - Left to right
5 Shift << (left), >> (right) Left to right
6 Relational <, <=, >, >= Left to right
7 Equality ==, != Left to right
8 Bitwise AND & Left to right
9 Bitwise XOR ^ Left to right
10 Bitwise OR | Left to right
11 Logical AND && Left to right
12 Logical OR || Left to right
13 Conditional ?, : Right to left
14 Assignment =, +=, -=, *=, /=, %=,>>,= <, &=, ^=, |= Right to left
15 Comma , Left to right
© CPP_MAK_Stat.RU 89

Example: Precedence Rule

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

© MAK_C++ Class Note 45


Definitions: Precedence Rule

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.

Priority Operators Description


First *, /, % Multiplication, Division, Remainder
Second +, - Addition, Subtraction
Third = Assignment

© CPP_MAK_Stat.RU 91

Definitions: Precedence Rule

Parentheses Rule

 Whenever the parentheses are used, the


expression within the parentheses assume highest
priority.
 If two or more set of parentheses appear one after
another, the expression contained in the left-most
set is evaluated first and the right-most in the last.
 Parentheses may be nested, and in such case,
evaluation of the expression will proceed outward
from the innermost set of parentheses.

© CPP_MAK_Stat.RU 92

© MAK_C++ Class Note 46


Example
Write a program to convert days into months and days

/***************************************************************************/
/* 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

Definitions: (2) Relational Operators

Comparison between two quantities can be done by the help of relational


operators. C++ support six relational operators which are shown as follows:

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

© MAK_C++ Class Note 47


Definitions: Relational Operators

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

Definitions: (3) Logical Operators

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

 Like the relational expressions, a logical expression also yields a


value of one or zero.
If i = 7, j = 5.52 and k = 3
Expression Interpretation Value
(i >= 6) && (k ==3) True 1
(i < 5)  (k == 3) True 1
!i ==7 False 0
© CPP_MAK_Stat.RU 96

© MAK_C++ Class Note 48


Definitions: (4) Assignment Operators

Assignment operators are used to assign the result of an expression to a


variable. There are several assignment operators in C. The most commonly
used assignment is = and has the form of
identifier = expression;
where identifier generally represents a variable, and expression presents a
constant, a variable or a more complex expression.
In addition C has a set of “shorthand” assignment operators of the form
variable operator = expression;
Where variable is a variable, operator is a C binary arithmetic operator,
operator = is known as the shorthand operator, and expression is an
expression.

 The assignment statement


variable operator= expression
is equivalent to
variable = variable operator expression
 x += y + 1 is equivalent to x = x + (y + 1)
© CPP_MAK_Stat.RU 97

Definitions: Assignment Operators

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

© MAK_C++ Class Note 49


Definitions: (5) Increment/Decrement Operators

There are two commonly used unary operators: the increment


operator, ++, and the decrement operator, --. The operator ++
adds 1 to the operand while -- subtracts 1. they take the
following form:
++m or m++;
--m or m--;
Where ++m is equivalent to m = m + 1; (or, m +=1;)
And --m is equivalent to m = m – 1; (or, m -=1;)

 Example:
i++ i=i+1 j-- j=j-1
++i i=i+1 --j j=j-1

© CPP_MAK_Stat.RU 99

Definitions: Increment/Decrement Operators

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

© MAK_C++ Class Note 50


Definition: (6) Conditional Statements

Conditional statements are used to make decisions based


on a given condition. If the condition evaluates to TRUE, a
set of statements is executed, otherwise another set of
statements is executed.
if statement
if-else statement

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

Definition: Conditional Statement

if (Asad’s height is greater than six feet)


Asad can be a member of team

Start

True False
Statement 1 if (Condition) Statement 2

Print Output

Stop

© CPP_MAK_Stat.RU 102

© MAK_C++ Class Note 51


Definition: Conditional Statement

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

© MAK_C++ Class Note 52


Sample: Program
include<iostream.h>
using namespace std;
main()
{
int OmarAge, AliAge;
cout<< "Please Enter OmarAge: ";
cin>> OmarAge;
cout<< "Please Enter AliAge: ";
cin>> AliAge;
if(OmarAge > AliAge)
{
cout << "Omar is Older than Ali";
}
{
if(OmarAge < AliAge)
{
cout << "Omar is younger than Ali";
}
}
}
© CPP_MAK_Stat.RU 105

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: 0 2 0.000000 2.000000


© CPP_MAK_Stat.RU 106

© MAK_C++ Class Note 53


Exercise
// What will be the output of the following programs
# include <stdio.h>
int main( )
{
int a, b, c, d ;
a=2%5; 2%5=2 7%5=2
b = -2 % 5 ; -2 % 5 = -2
c = 2 % -5 ; 2 % -5 = 2
d = -2 % -5 ; -2 % -5 = -2
printf ( "a = %d b = %d c = %d d = %d\n", a, b, c, d ) ;
return 0 ;
}

Answer: a = 2 b = -2 c = 2 d = -2
© CPP_MAK_Stat.RU 107

Definitions: (7) Bitwise operators

These operators are used to perform bit operations.


Decimal values are converted into binary values which
are the sequence of bits and bit wise operators work
on these bits.
Bit wise operators in C++ language are
 & (bitwise AND)
 | (bitwise OR)
 ~ (bitwise NOT)
 ^ (XOR)
 << (left shift)
 >> (right shift).
© CPP_MAK_Stat.RU 108

© MAK_C++ Class Note 54


Definitions: Library functions

Many activities in C++ are carried out by library function. These


functions perform file access, mathematical computations, graphics,
memory management, and data conversion among other things.
The following are some library functions used in C++:
Library functions Description
abs(x) absolute value of the integer argument x
fabs(x) absolute value of a floating-point number x
exp(x) calculates the exponential e to the x
log(x) calculates the natural logarithm of x
log10(x) calculates the base 10 logarithm of x
pow(x,y) calculates x to the power of y
pow10(p) calculates 10 to the power of p
sin(x) computes the sine of the input value x
sqrt(x) positive square root of the argument x

© CPP_MAK_Stat.RU 109

Definitions: Algorithm

The sequence of steps to be performed in order to solve a


problem by the computer is known as an algorithm.

Benefits of using Algorithms:


The use of algorithms provides a number of benefits. One of
these benefits is in the development of the procedure itself,
which involves identification of the processes, major decision
points, and variables necessary to solve the problem.
Developing an algorithm allows and even forces examination of
the solution process in a rational manner. By using an algorithm,
decision making becomes a more rational process. An algorithm
serves as a mnemonic device and helps ensure that variables or
parts of the problem are not ignored. Presenting the solution
process as an algorithm allows more precise communication.
Finally, separation of the procedure steps facilitates division of
labour and development of expertise.
© CPP_MAK_Stat.RU 110

© MAK_C++ Class Note 55


Definitions: Flowchart

Flowchart is a graphical or symbolic representation of an


algorithm. It is the diagrammatic representation of the step-by-
step solution to a given problem.

A Flowchart is a type of diagram (graphical or symbolic) that


represents an algorithm or process. Each step in the process is
represented by a different symbol and contains a short
description of the process step. The flow chart symbols are
linked together with arrows showing the process flow direction. A
flowchart typically shows the flow of data in a process, detailing
the operations/steps in a pictorial format which is easier to
understand than reading it in a textual format.

© CPP_MAK_Stat.RU 111

Definitions: Flowchart Symbols

Name Symbol Use in Flowchart

Oval Start/End Start and End of the program

Parallelogram Input/Output Input/Output operation

Rectangle Process control Process to be carried out

Diamond Decision Decision to be made

Rectangle with Predefined


Invoke a sub-routine
double struck Process

Circle Connector
Corrector

Arrow line Direction of logic

© CPP_MAK_Stat.RU 112

© MAK_C++ Class Note 56


Example-01: Algorithm

Example 1. Design an algorithm and the corresponding flowchart


for getting the larger value between two given numeric values.

Algorithm to find largest of two numbers

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

© MAK_C++ Class Note 57


Example-02: Algorithm

To find largest of three numbers


1) Start.
2) input 3 numbers: A, B, and C.
3) if A > B then go to step 5.
4) if B > C then print B is largest, otherwise print C is largest
and go to step 6.
5) if A > C then print A is largest, otherwise print C is largest.
6) end.

© CPP_MAK_Stat.RU 115

Example-02: Flowchart
Flowchart to find the largest of three numbers A, B and C:

START

A, B, C

Yes Is No Is Yes Is Yes


B > C? A > B? A > C?
No
No

B C C A

END
© CPP_MAK_Stat.RU 116

© MAK_C++ Class Note 58


Example-02: Program

#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

Example-02: Program using if statement


// Example 2: Find Largest Number Using if Statement
#include <iostream>
using namespace std;

int main() {
float n1, n2, n3;

cout << "Enter three numbers: ";


cin >> n1 >> n2 >> n3;

if(n1 >= n2 && n1 >= n3)


cout << "Largest number: " << n1;

if(n2 >= n1 && n2 >= n3)


cout << "Largest number: " << n2;

if(n3 >= n1 && n3 >= n2)


cout << "Largest number: " << n3;

return 0;
}

© CPP_MAK_Stat.RU 118

© MAK_C++ Class Note 59


Example-02: Program using if … else statement

// Example 2: Find Largest Number Using if...else Statement


#include <iostream>
using namespace std;

int main() {
float n1, n2, n3;

cout << "Enter three numbers: ";


cin >> n1 >> n2 >> n3;

if((n1 >= n2) && (n1 >= n3))


cout << "Largest number: " << n1;
else if ((n2 >= n1) && (n2 >= n3))
cout << "Largest number: " << n2;
else
cout << "Largest number: " << n3;

return 0;
}

© CPP_MAK_Stat.RU 119

Example-02: Program using nested if … else statement


// Example 3: Find Largest Number Using Nested if...else statement
#include <iostream>
using namespace std;

int main() {
float n1, n2, n3;

cout << "Enter three numbers: ";


cin >> n1 >> n2 >> n3;

if (n1 >= n2) {


if (n1 >= n3)
cout << "Largest number: " << n1;
else
cout << "Largest number: " << n3;
}
else {
if (n2 >= n3)
cout << "Largest number: " << n2;
else
cout << "Largest number: " << n3;
}

return 0;
}
© CPP_MAK_Stat.RU 120

© MAK_C++ Class Note 60


Example-03

Example 3. Design an algorithm and the corresponding


flowchart for adding the test scores as given below:
26, 49, 98, 87, 62, 75
Algorithm or flowchart as follows:
Start
1. Start
2. sum = 0 sum = 0.0
3. Get a value
4. sum = sum + value Get a value
5. Go to step 3 to get next Value if value
is available.
6. Print the value of sum sum = sum + value
7. Stop
print sum

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.

/* Calculation of total expenses */


# include <stdio.h>
int main( )
{
int qty, dis = 0 ;
float rate, tot ;
printf ( "Enter quantity and rate " ) ;
scanf ( "%d %f", &qty, &rate) ;
if ( qty > 1000 )
dis = 10 ;
tot = ( qty * rate ) - ( qty * rate * dis / 100 ) ;
printf ( "Total expenses = Rs. %f\n", tot ) ;
return 0 ;
}

© CPP_MAK_Stat.RU 122

© MAK_C++ Class Note 61


Definitions: Arrays

An array is defined as the collection of similar type of


data items stored at contiguous memory locations. The
array is the simplest data structure where each data
element can be randomly accessed by using its index
number.
There are three different types of Arrays, namely:
• One-Dimensional Array
• Two-Dimensional Array
• Multi-Dimensional Array

© CPP_MAK_Stat.RU 123

Definitions: Arrays

The One-dimensional array can be defined as an array with


single row and multiple columns. The elements in lD array
are accessed using their index numbers.

MyArray[0] MyArray[1] MyArray[2] MyArray[3] MyArray[4]

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

© MAK_C++ Class Note 62


Definitions: Arrays

The two-dimensional array can be defined as an array of


arrays. The 20 array is organized as matrices which can be
represented as the collection of rows and columns. The
elements of the array are accessed using their intersection
coordinates.

rows
Array[0][0] Array[0][1] Array[0][2] Array[0][3] Array[0][4]

Array[1][0] Array[1][1] Array[1][2] Array[1][3] Array[1][4] columns

Array[0][0] = 10 Array[0][1] = 20 Array[0][4] = 30 Array[1][4] = 100

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

© MAK_C++ Class Note 63


Definitions: Arrays

The multi-dimensional array can be defined as an array of


arrays. The 3D array is organized as 3D matrix which can be
represented as the collection of multiple rows and columns.
The elements of the array are accessed using their 3D
intersection coordinates.
(1, 1, 1) (1, 1, 2) (1, 1, 3) (1, 1, 4) (1, 1, 5)

(1, 4, 1) (1, 4, 2) (1, 4, 3) (1, 4, 4) (1, 4, 5)

(2, 1, 1) (2, 1, 2) (2, 1, 3) (2, 1, 4) (2, 1, 5)

(2, 4, 1) (2, 4, 2) (2, 4, 3) (2, 4, 4) (2, 4, 5)

(3, 1, 1) (3, 1, 2) (3, 1, 3) (3, 1, 4) (3, 1, 5)

(3, 4, 1) (3, 4, 2) (3, 4, 3) (3, 4, 4) (3, 4, 5)

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

© MAK_C++ Class Note 64


Definitions: Selective Statement

Selective Statement consists of a test for a condition


followed by two or more alternative paths for the program to
follow. The program selects one of the paths depending on
the test for the condition.

 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

The general form of a simple if statement is


if(expression)
{
statement-block;
}
Where the statement-block may be a single statement or a
group of statements. If the expression (relational or logical) is
true, the statement-block will be executed; otherwise the
statement-block will be skipped and the next statement following
the if statement is executed.
NOTE: If statement-block contain single statement, the simple if statement
can be written as
if(expression) statement;
© CPP_MAK_Stat.RU 130

© MAK_C++ Class Note 65


Selective: IF Statement

Start /* Illustration of if Statement */


#include<stdio.h>
Input
main()

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

Selective: IF-ELSE Statement

The if-else statement is an extension of the simple if statement. The


general form of this statement is
if(expression)
{
True-block statement(s);
}
else
{
False-block statement(s);
}
If the expression (relational or logical) is true, the true-block
statement(s) are executed; otherwise the false-block statement(s) are
is executed. In either case, either true-block or false block will be
executed, not both.
© CPP_MAK_Stat.RU 132

© MAK_C++ Class Note 66


Definitions: IF-ELSE Statement

IF-ELSE statement in C++ language is defined as a


programming conditional statement that has two Statement
blocks over a condition. if proved true, then the if block will be
executed and if false, then the else block will be executed.

Start

True False
Condition

Statements Statements

Statements
© CPP_MAK_Stat.RU 133

Selective: IF-ELSE Statement

/*Illustration of simple if Statement*/


#include<stdio.h>
main()
/*Illustration of if-else Statement*/
{
#include<stdio.h>
float a, b, c, d, ratio;
main()
printf(“Enter four integer values”);
{
scanf(“%d %d %d %d”, &a, &b, &c, &d);
float a, b, c, d, ratio;
if(c – d != 0)
printf(“Enter four integer values”);
{
scanf(“%d %d %d %d”, &a, &b, &c, &d);
ratio = (a+b)/(c-d);
if(c – d != 0)
printf(“Ratio = %f”, ratio);
{
}
ratio = (a+b)/(c-d);
}
printf(“Ratio = %f”, ratio);
}
else
printf(“c – d = %d”, c – d);
}

© CPP_MAK_Stat.RU 134

© MAK_C++ Class Note 67


Selective: IF-ELSE Statement
/* SOLUTION OF A QUATRADIC EQUATION */
#include<stdio.h>
#include <math.h>
main()
{
float a, b, c, dis, root1, root2;
printf(“Input the values of a, b and c\n”);
scanf(“%f %f %f”, &a, &b, &c);
dis = b*b – 4*a*c;
if(dis < 0)
printf(“\n\nROOTS ARE IMAGINARY\n\n”);
else
{
root1 = (-b + sqrt(dis))/(2*a);
root2 = (-b – sqrt(dis))/(2*a);
printf(“Root1 = %5.2f\nRoot2 = %5.2f\n”, root1, root2);
}
}
© CPP_MAK_Stat.RU 135

Example: ELSE-IF Ladder

Grading of student in an academic #include<stdio.h>


institution. The grading is done Main()
according to the following rules: {
int marks;
Average marks Grade
80 to 100 A+ char grade;
60 to 79 A printf(“Enter the marks\n);
50 to 59 A- scanf(“%d”, marks);
40 to 49 D if(marks > 79)
00 to 39 Fail grade = “A”
else if(marks > 59)
grade = “B”
else if(marks >49)
grade = “C”;
else if(marks > 39)
grade = “D”;
else
grade = “Fail”;
printf(“Grade = %s”, grade);
}
© CPP_MAK_Stat.RU 136

© MAK_C++ Class Note 68


Definitions: if-else ladder Control Statements

If-else ladder in C++ Language is defined as a programming


conditional statement that has multiple else-if statement blocks.
If any of the condition is true, then the control will exit the else-if
ladder and execute the next set of statements.

Start

False
Condition 1
False
Condition 2
True False
Condition n
True
True

Statements 1 Statements 2 Statements n Statements

© 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

© MAK_C++ Class Note 69


Definitions: Nested if Control Statements

Nested if statement in C++ language is defined as a


programming conditional statement that comprises of
another if statement inside the previous if statement.

Start

True
Condition-1

True False
False Condition-2

Statements-1 Statements-2 Statements-3

Stop

© CPP_MAK_Stat.RU 139

Definitions: Nested if Control Statements

#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

© MAK_C++ Class Note 70


Repetitive Structures

In the repetitive structure, a sequence of statements is


repeatedly executed as long as some condition is satisfied. It
is also known as iterative structure or program loop.

The C language provides three program loops. They are


 the while Statement
 the do-while statement
 the for statement

© 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

© MAK_C++ Class Note 71


Repetitive Structures

Entry & Exit Control Loop

Depending on the position of the control


Enter statement in the loop, a program loop Enter
structure is classified in to two types:
False  entry-controlled loop Body of
Condition the loop
 exit-controlled loop
True In the entry-controlled loop, the control
Body of the conditions are tested before the start of the False
loop loop execution. If the conditions are not Condition
satisfied, then the body of the loop will not
be executed. True
Exit In the case of the exit-controlled loop, the Exit
test is performed at the end of the body of
Entry control the loop and therefore the body is Exit control
executed unconditionally for the first time.

© CPP_MAK_Stat.RU 143

Repetitive Structures
while Statement

The simplest of the looping structure in C is the while statement.


The basic format of the while statement is
while(condition)
{
body of the loop;
}
The while is an entry-controlled loop statement. The condition is
evaluated and if the condition is true, the body of the loop is
executed. After execution of the body, the condition is once
again evaluated and if it is true, the body is executed again. This
process of repeated execution of the body continues until the
condition finally becomes false and the control is transferred out
of the loop.

© CPP_MAK_Stat.RU 144

© MAK_C++ Class Note 72


Repetitive Structures
while Statement
EXAMPLE

Note the segments:


----------
 initialization
sum = 0;
n = 1;  control statement
while(n <= 10)  body of the loop
{
sum = sum + n*n;
n = n + 1;
}
printf(“Sum of square = %d\n”, sum);
---------

© 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

© MAK_C++ Class Note 73


Repetitive Structures
do-while Statement
When the loop is constructed using the while statement, the test for condition is
carried out before the loop is executed. Sometimes, however, it is desirable to have
a loop with the test for condition after the loop is executed. This can be
accomplished by means of do-while statement. The general form of the do–
while statement is
do
{
body of the loop;
}
while(condition);

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

© MAK_C++ Class Note 74


Repetitive Structures

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

© MAK_C++ Class Note 75


Repetitive Structures

for Statement
EXAMPLE

---------- Note the segments:


sum = 0;
for(n = 1; n <= 10; n = n + 1)  initialization
{
sum = sum + n*n;  control statement
n = n + 1;
}  body of the loop
printf(“Sum of square = %d\n”, sum);
---------

© 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

© MAK_C++ Class Note 76


Repetitive Structures

Comparison of the Three Loops

while do-while For


n = 1; n = 1; For(n=1; n<=10; ++n)
while(n <= 10) do {
{ { ---------;
---------; ---------; ---------;
---------; ---------; }
n = n + 1; n = n + 1;
} }
while(n <= 10)

© CPP_MAK_Stat.RU 153

Additional Features: for Loop

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

© MAK_C++ Class Note 77


Additional Features: for Loop
 The condition may have any compound relation and the
relation need not be limited only to the loop control variable.
For example:
sum = 0;
for(i = 1, im < 50 && sum < 100; i = i + 1)
{
sum = sum + i;
printf(“%d \n”, sum);
}

 It is also permissible to use expressions in the assignment


statements of initialization and increment sections. For
example:
for(x = (m+n)/2; x > 0; x = x/2)

© CPP_MAK_Stat.RU 155

Additional Features: for Loop

 Another unique aspect of for loop is that one or more


sections can be omitted, if necessary. For example:
m = 5;
for( ; m != 100 ; )
{
printf(“%d %d %d\n”, n, m, p);
m = m + 1;
}

© CPP_MAK_Stat.RU 156

© MAK_C++ Class Note 78


Nesting of for Loop

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:

for(i = 1; i <= 10; ++i)


{
-----------;
-----------;
for(j = 1; j <= 5; ++j)
{ Outer
Inner
-----------; loop
loop
-----------;
}
-----------;
-----------;
}
© CPP_MAK_Stat.RU 157

Nesting of for Loop

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

© MAK_C++ Class Note 79


Jumping Out of a Loop
Include<stdio.h> Break Statement
main()
{
int m;
float x, sum, average;
printf(“Enter the value one after another\n”);
printf(“Enter a NEGATIVE number at the end\n\n”);
sum=0;
for(m = 1; m <= 1000: ++m);
{
scanf(“%f”, &x);
if(x < 0)
break;
sum += x;
}
average = sum/(float)(m-1);
printf(“Number of values = %d\n”, m-1);
printf(“Sum of the values = %f\n”, sum);
printf(“Average of the values = %f\n”, average);
}
© CPP_MAK_Stat.RU 159

Jumping Out of a Loop


#Include<stdio.h> Break Statement
#include<math.h>
main()
{
int count, negative;
double number, sqroot;
printf(“Enter 99999 to STOP\n”);
printf(“Enter numbers\n\n”);
count = 0; negative = 0;
while(count <= 1000);
{
scanf(“%f”, &number);
if(number == 99999)
break; /* EXIT FROM THE LOOP */
if(number < 0)
{
printf(“Number is negative);
negative++;
continue; /* SKIP REST OF THE LOOP 8/
sqroot = sqrt(number);
printf(“Number = %lf\nSquare root = %lf\n\n”, number, sqroot);
count++;
}
average = sum/(float)(m-1);
printf(“Number of item done = %d\n\n”, count);
printf(“Negative items = %f\n”, negative);
}
© CPP_MAK_Stat.RU 160

© MAK_C++ Class Note 80


Example: Fit a Regression Model
#include<stdio.h>
#include<math.h>
main()
{
int n, i;
float y, x, sx, sy, ssx, ssy, sxy, cor, a, b;
printf("Nomber of observation (pairs)\n");
scanf("%d", &n);
printf("Enter the values pair-wise\n");
sy = 0; sx = 0; ssy = 0; ssx = 0; sxy = 0;
for(i=1;i<= n; i++)
{
scanf("%f %f", &y, &x);
sy = sy + y;
sx = sx + x;
ssy = ssy + y*y;
ssx = ssx + x*x;
sxy = sxy + x*y;
}
cor = (n*sxy - sx*sy)/sqrt((n*ssx - sx*sx)*(n*ssy - sy*sy));
b = (n*sxy - sx*sy)/(n*ssx - sx*sx);
a = (sy - b*sx)/n;
printf("Correlation coefficient = %f\n\n",cor);
printf("Fitted Line is Y = %6.2f + %5.2f X\n", a, b);
return(0);
}

© 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

© MAK_C++ Class Note 81


Problem
Main()
Problem: Find Min, {

Max, Mean, Range of Int count;


Float value, high, low, sum, average, range;
the given data:
Sum = 0; count = 0;
24, 30, 18, 32, 23 Printf(“Enter numbers; input a NEGATIVE number to end\n”)
27, 38, 24, 19, 28 Input:
Scanf(“%f”, &value);
If(value < 0) goto output;
Count = count + 1;
If(count == 1)
High = low = value;
Else if(value > high)
High = value;
Else if(value < low)
Low = value;
Sum = sum + value;
Goto output;
Output:
Average = sum/count;
Range = high – low;
Printf(“\n\nTotal value : %d\n”, count);
Printf(“Highest vale:%f\nLowest value: %f\n”, high, low);
Printf(“Range :%f\nAverage :%f\n”, range, average);
}
© CPP_MAK_Stat.RU 163

Definitions: Switch Control Statements


Switch case in C++ language is defined as a programming selection
statement that checks for a possible match to the provided condition
against the variable cases. If none of the cases match, then the control
will executed the default statement block.

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

© MAK_C++ Class Note 82


Definitions: Switch Control Statements
#include<iostream>
using namespace std;
int main()
{
int x = 3;
switch (x)
{
case 1:
cout << "Choice is 1";
break;
case 2:
cout << "Choice is 2";
break;
case 3:
cout << "Choice is 3";
break;
default:
cout << "Choice other than 1, 2 and 3";
break;
}
return 0;
}
© CPP_MAK_Stat.RU 165

Thanks a lot

Forest

© MAK_C++ Class Note 83

You might also like