Programming With C++ - CP-II
Programming With C++ - CP-II
C and C++ are popular programming languages used for developing system software,
embedded systems, and application software.
C language was developed by Dennis Ritchie at Bell Labs in the 1970s.
C++ was developed by Bjarne Stroustrup in the 1980s as an extension of the C language.
C and C++ are compiled languages, which means that they require a compiler to translate
the code into machine language that the computer can understand.
C is a procedural programming language, meaning it follows a set of procedures or
functions to execute the program.
C++ is an object-oriented programming language, meaning it uses objects to define and
manipulate data and functions in the program.
Both languages are known for their efficiency, flexibility, and portability across different
operating systems and hardware platforms.
2
C++ was created by Bjarne Stroustrup in the early 1980s as an extension of the C
programming language.
Stroustrup wanted to add features to C that would make it easier to write complex programs,
particularly in the area of object-oriented programming.
The first version of C++ was called "C with Classes" and included features like classes,
inheritance, and virtual functions.
C++ gained popularity in the 1990s as a powerful language for developing large-scale
software projects, such as video games and operating systems.
C++ is still widely used today in a variety of applications, from scientific simulations to
finance and trading systems.
The standardization of C++ began in the mid-1990s with the creation of the ISO C++
standard, which defined the language and its features.
Today, C++ continues to evolve with new features and updates being added to the language,
while still maintaining backward compatibility with older code. 3
C is a language that is widely used in computer programming because it is fast,
efficient, and easy to learn.
C is used to create a wide range of software applications, including operating
systems, device drivers, and embedded systems.
C is portable, meaning it can be used on different types of computers and
operating systems with minimal changes.
C is a structured language, meaning it is organized and easy to read, making it less
prone to errors and easier to maintain.
C is a great language for learning programming because it teaches fundamental
concepts that can be applied to other programming languages.
4
C++ is a language that builds on the strengths of C and adds new features that
make it even more powerful.
C++ supports object-oriented programming, which allows for easier code reuse
and more organized code.
C++ is used to create a wide range of software applications, including video
games, desktop applications, and scientific simulations.
C++ is a great language for developing large-scale software projects because it
allows for modular programming, meaning that code can be broken down into
smaller, more manageable pieces.
C++ has a large community and extensive libraries, making it easier to find
solutions to common programming problems.
5
C is a procedural programming language, while C++ is an object-oriented programming
language. This means that C++ has some extra features that allow for more complex programs to
be written, but also means that C++ can be a bit more complicated to learn.
C++ includes all of the features of C, but also adds some extra ones. For example, C++ includes
classes, which are like blueprints for creating objects. These classes can make it easier to write
complex programs.
C++ has a wider range of applications than C. C is often used for developing operating systems,
device drivers, and other low-level systems programming, while C++ is used for a wider range of
applications, including games, desktop applications, and web applications.
C++ has a larger standard library than C. This means that there are more built-in functions and
data structures that you can use in C++ without having to write them yourself.
Overall, C and C++ are both powerful programming languages that can
be used to create a wide range of applications. However, C++ has some extra features that make it a
bit more versatile, but also a bit more complex to learn. If you are interested in programming and
want to learn more, both C and C++ can be great languages to start with.
6
Identifiers +
Character Set Keywords Instructions
A-Z
a-z
• Data Type Declaration Instructions
0-9 • Variables
• Input & Output Instructions
( ) { } ;+ - _ • Constants
• Arithmetic Instructions
& % ! == • Keywords
• Control Instructions
=/*^#~
||
Program
7
The character set in C/C++ includes letters, digits, escape characters, white space character
(blank space) and special characters that can be used in the source code of a program.
The basic character set of letters includes: 26 letters of the English alphabet (both uppercase and
lowercase), the 10 decimal digits, set of special characters, such as dot, comma, hash, less than,
greater than, equal to, asterisk (*), ampersand (&) and so on. While Escape character set includes
characters starting with backslash (\) which are used for formatting text, some of escape
characters are \n for newline, \t to tab (4 spaces), \” for double quotes and so on.
The extended character set includes additional characters, such as non-Latin characters used in
other languages, and can vary depending on the implementation of the language.
8
Reserved words in C/C++ are words with a special
meaning in the programming language and cannot be
used as variable names or other identifiers in the
program.
C language has 32 reserved words, while C++ language
has 89 reserved words.
Examples of reserved words in both languages include
"if," "else," "while," "for," and "return.“
These words are reserved because they have a specific
purpose in the language and using them for other
purposes could cause errors or unexpected behavior in
the program.
9
User-defined words in C/C++ are variable names, function names, and other identifiers created
by the programmer.
User-defined words can be composed of letters, digits, and underscores, but must follow certain
rules, such as starting with a letter or underscore and not being the same as a reserved word.
Using descriptive and meaningful user-defined words can make the program easier to read and
understand.
The number of user-defined words in a program can vary widely depending on the size and
complexity of the program.
10
C language has a total of 128 characters in its character set, while C++ language has a total of 256
characters.
The number of reserved words in C language is fixed at 32, while the number of reserved words
in C++ language can vary between implementations.
The number of user-defined words in a program can vary widely, but it is recommended to use
meaningful and descriptive names to improve program readability and maintainability.
Examples of user-defined words in C/C++ include variable names like "counter" or "sum,"
function names like "calculateArea" or "printResults," and class names like "Person" or "Car."
11
1. Identifiers must begin with a letter or an underscore, but not a digit. After first letter or
underscore, you can use numbers, letters or additional underscores as well.
Valid identifier examples: “A21_," "_sum," "name_1_"
Invalid identifier examples: "3number," "#result," "-value"
3. Identifiers are case-sensitive, meaning uppercase and lowercase letters are treated as different
characters.
Valid identifier examples: "firstName," "FIRSTNAME," "FirstName"
Invalid identifier examples: "first name," "first_name," "First Name"
4. Identifiers should not have spaces between them, and should not be the same as reserved
words.
Valid identifier examples: "no_of_students," "max_speed," "total_cost"
Invalid identifier examples: "if," "else," “no of students"
12
Constants are values that remain fixed during the execution of a program. In C/C++, there are two
types of constants: numeric constants and non-numeric constants.
1. Numeric constants: Numeric constants represent numeric values, such as integers, floating-
point numbers, and other numerical values. Numeric constants can be represented in several
formats, including:
Integer constants: These are whole numbers, either positive or negative, and can be represented
in different formats:
Decimal format: represented in base 10, such as 42, -99, etc.
Octal format: represented in base 8, such as 052, -077, etc. (starts with 0)
Hexadecimal format: represented in base 16, such as 0x2A, -0x63, etc. (starts with 0x)
Floating-point constants: These represent real numbers, either positive or negative, and have a
fractional component. They can be represented in either decimal or scientific notation
(exponential real constants).
Decimal Format: represented with a decimal point, such as 3.14, -0.001, etc.
Scientific notation format: represented with an exponent, such as 1.23e-5, 2.34E+2, etc.
13
1. Non-numeric constants: Non-numeric constants represent non-numeric values, such as
characters and strings, and are represented in different formats:
Character constants: These are single characters enclosed in single quotes, such as 'A', '$', etc.
Valid Character Constants: ‘+’ , ‘-’, ‘1’, ‘9’ , ‘z’, ‘ ’
Invalid Character Constants: ‘-1’, ‘bb’
String constants: These are a sequence of characters enclosed in double quotes, such as "Hello,
World!", "This is Physics IV", etc.
Symbolic constants: These are values that are given a name using the #define preprocessor
directive, and represent a fixed value that cannot be changed during the execution of the program.
14
We can divide all these constants into two categories:
Primary Constants
Integer
Real of Floating Point
Character
Double (high-precision floating points with more memory size)
Void
Secondary Constants
Array
String
Pointers
Classes
Struct
Enumerators
Union
15
Variables are used in programming to store and manipulate data.
A variable is a named location in memory where data can be stored and retrieved during the
execution of a program.
A variable name must be unique in a program.
Few Examples
1a, 33var, 3b, %x, $physics etc. are invalid variable names as these are not following the naming rules
discussed previously.
a1, var33, b3, _a, _physics, var_2 all are valid variable names following the discussed rules.
Spaces are not allowed like a b is an invalid variable name but ab is a valid name.
if, while, for, int, do, return float, char, etc. are invalid variable names as these are
predefined/reserved words in C/C++ language.
16
As we know that variables can hold different type of data. In C/C++, data may be divided into
integer, float and character as discussed previously.
Variables that hold integer data are known as integer variable. Integer variable can further be
divided into:
Signed Integers: These integers are either positive or negative
Unsigned Integers: These integers are always positive.
Also, sometimes we want to store very large number and sometimes we want to store very small
number, C++ provides us a way i.e., long and short keywords:
long: Hold larger values like 4 bytes
short: Hold smaller values like 2 bytes
Like integers, floating-point variables has also varieties depending upon the problem we want to
solve. The table on the next page can help us conceptualize better
17
NAME TYPE SIZE RANGE
char Character 1 byte -128 to 127
unsigned char Unsigned Character 1 byte 0 to 255
int Integer 2 byte -32768 to 32767
unsigned int Unsigned Integer 2 byte 0 to 65,535
signed int Signed Integer 2 byte -32768 to 32767
short int Short Integer 2 byte 0 to 65,535
unsigned short int Unsigned short int 2 byte -32768 to 32767
long int Long integer 4 byte -2,147,483,648 to 2,147,483,647
unsigned long int Unsigned long int 4 byte 0 to 4,294,967,295
float Floating point 4 byte −3.4 𝑥1038 𝑡𝑜 3.4 𝑥1038
double Double floating point 8 byte −1.7 𝑥10308 𝑡𝑜 1.7 𝑥10308
long double Long double float 10 byte −1.7 𝑥104932 𝑡𝑜 1.7 𝑥104932
18
19
#include<headerfilename1.h>
Header Files
#include<headerfilename2.h>
void main() {
INSTRUCTION #1;
INSTRUCTION #2;
Main Function INSTRUCTION #3;
Instructions written by
Body …
the programmer
…
INSTRUCTION #N;
}
The instructions we provide
Semicolon (;) represents the
will always be located inside
end of instruction / line end.
the main function. 20
Preprocessor Directives: A command in a C/C++ program that is processed by the preprocessor
before compilation, such as the "#include" directive which is used to include header files in a
program or #define to define constants, etc.
Header files: Contain function declarations, constants, and other declarations that are needed by a
program to access external resources or to use functions that are not defined in the current source
file. Header files are included in a C/C++ program using the "#include" preprocessor directive.
Examples of header files in C/C++ include "stdio.h" for standard input and output functions like
printf() & scanf() and “iostream.h” for using classes and functions for input and output operations
in C++, such as the "cin" and "cout" objects for reading and writing data to the console or black
screen.
Main function: The main function is the entry point of a C/C++ program, where the execution of
the program begins. Every C/C++ program must have a main function, which is declared as "int
main()" in C & C++. There are multiple ways to declare it.
Semicolons: These are used in C/C++ to indicate the end of a statement or expression. Every
statement in C/C++ must end with a semicolon, or a compiler error will occur. Examples of
statements that require semicolons in C/C++ include variable declarations, function calls, and
control flow statements.
21
Header files: Header files contain declarations of functions, classes, structures, and other types of
data that are needed by a program to access external resources or to use functions that are not
defined in the current source file. Header files typically have the file extension ".h" or ".hpp".
Header files are included in a C/C++ program using the "#include" preprocessor directive.
Header files are typically used to declare functions, classes, and other types of data that are
defined in libraries, so that the program can access them.
Libraries: Libraries are collections of pre-compiled code that can be linked with a program to
provide additional functionality or to speed up program execution. Libraries can contain
compiled object code, static libraries, or dynamic shared libraries. Libraries are linked with a
C/C++ program using the linker, either statically or dynamically. Libraries can contain functions,
classes, structures, and other types of data that can be used by a program.
22
In computer programming, an instruction is a command that tells a computer
processor what to do.
It is an order given to a computer processor by a computer program.
At the lowest level, each instruction is a sequence of 0s and 1s that describes a
physical operation the computer is to perform.
We will discuss the following instructions in detail in upcoming lectures:
i. Data Type Declaration Instruction
ii. Input & Output Instruction
iii. Arithmetic Instruction
iv. Control Instructions
23
Each variable (memory location) has an associated datatype.
Each datatype requires different amount of memory & has some specific operations
which can be performed over it.
Datatype specifies type of data that the variable can store like integer, float, character,
double, etc.
Datatypes that are also keywords (predefined) are known as primitive data types.
We can also create our own datatypes known as non-primitive datatypes.
Few datatypes that we discussed so far include:
Integer (int)
Floating Point/ Real (float)
Character (char)
Double Floating Point (double)
Void
24
Now the question is: “How to instruct CPU to create a memory space of specific size
so that we can store data?”
So, there’s a general sentence/instruction format that we can use to declare or
initialize a variable of certain datatype. The general formula is:
Declaration only as
<datatype> <variable name>
or
Declaration + Initialization as
<datatype> <variable name> = <value>
Let’s now understand it with few examples on next slide.
25
Instruction to declare 2 variables named a & b which can store integer:
int a , b;
a b
or we can also declare them in two separate lines as:
int a;
int b;
Instruction to declare a variable named f1 which can store float: f1
float f1;
Instruction to declare a variable named ch which can store character: ch
char ch;
Instruction to declare a variable named d1 to store double floating number:
double d1;
d1
26
We can declare and initialize variable at the same time as well:
int a = 20;
a
or we can also do it in two separate lines as:
20
int a;
a = 20;
Lets declare and initialize a float named f1:
float f1 = 22.2; f1
or we can also write it in two separate lines as: 22.2
float f1;
f1 = 22.2;
Character can also be declared and initialized as: ch
char ch = ‘+’; +
27
A sample C program to demonstrate datatype declaration & initialization:
#include <stdio.h>
#include <conio.h> Final State of the variables after
FLOW OF THE PROGRAM
28
Practice Problem
What is wrong with the following program. Highlight the issues in each line if exist.
#include <iostream.h>
using namespace std;
void main() { • The instruction int 12a; will throw an error as
variable name cannot start with a number.
int 12a;
• The instruction float f2 will throw an error as it
float f2 doesn’t contain line separator ;
char $1; • The instruction char $1; will throw an error as
int a2 = 20, f2 = 30; variable name cannot start with a special
float f2; character except underscore.
f2 = 20.2;
int num1 = 122.8;
}
29
There are so many devices in computer that can be used for input or output like mouse,
keyboard, printer, USB, monitor, etc.
Some of them are standard/default devices i.e., present in every computing device. For
example:
Monitor is a standard Output Device
Keyboard is a standard Input Device
30
printf() is an output instruction used to display messages/prompts on monitor
screen.
printf() is not a keyword but a predefined function.
It is part of the standard input/output library stdio.h
printf() can be used to display two types of messages on screen:
1. Printing text as it is.
2. Printing values of expression or value of variables
We will learn how to print text on screen as well as value of variables & how to
combine both to get maximum benefits out of it.
31
Let’s use printf() to print text as it is.
Just enclose anything in double quotes (“”) & printf() will print it as it is.
Example 1
C language code Output
#include <stdio.h>
Welcome to Physics-IVHow are you?
#include <conio.h>
void main() {
printf(“Welcome to Physics-IV”);
printf(“How are you?”);
}
Why no space between Physics-IV and How are you?
Why “How are you?” is not on next/new line?
These are other escape sequences as well but these are enough to understand the
idea for now.
33
Now, let’s rewrite our previous example using escape sequences to add text on new
line.
35
Now, let’s learn how to use printf() to print the expressions or value/content of
variables.
Example
Code Output
As enclosing anything in double
#include <stdio.h> x y f1 ch quotes (“”) tells printf() to print it
#include <conio.h> as it is. That’s why we cannot see the
void main() { values of x, y, f1 & ch.
int x, y = 15; But, how to instruct printf() that x, y,
float f1 = 22.6; f1 & ch are not simply
char ch; text/alphabets but variables with
x = 20; some data stored in them ??
ch = ‘9’;
printf(“x y f1 ch”); FORMAT SPECIFIERS are the solution to this problem.
}
36
Format Specifiers are special symbols that instruct input/output instructions about
existence & type of variables.
The format specifiers are used in C for input / output purposes.
Using this concept, we can instruct compiler about the variable & the type of data it
has.
Format specifiers in C always start a % symbol.
printf() will never print format specifiers on screen as these are not printable but
only instructing printf() about the variable & its datatype.
37
List of some basic format specifiers:
%d for integer
%f for float
%c for character (char)
%lf for double
Lets see with examples how to use these to print the content of variable on screen.
38
Code
#include <stdio.h> Output Printing one by one
#include <conio.h>
20 15 22.6 9 printf(“%d”,x); -> 20
void main() { printf(“%d”,y); -> 15
int x, y = 15; printf(“%f”,f1); -> 22.6
float f1 = 22.6; printf(“%c”,ch); -> 9
char ch;
x = 20; int char
ch = ‘9’;
printf(“%d %d %f %c”,x,y,f1,ch); printf(“%d %d %f %c”,x,y,f1,ch);
}
39
What if I wanted to print both the text and value of variable using a single printf() ?
Let’s understand it with an example.
Code Output
#include <stdio.h> Sum of 5 + 15 = 20
#include <conio.h>
void main() {
int x, y = 15;
x = 5;
printf(“Sum of %d + %d = %d”,x,y,x+y);
}
40
scanf() is an input instruction used to receive input by user through keyboard.
scanf() is not a keyword but a predefined function.
It is part of the standard input/output library stdio.h and is commonly used for
interactive programs that require user input.
The scanf() function takes two main parameters: a format string and the addresses
of the variable where the input will be stored.
The format string specifies the expected data type and format of the input, and it starts
with '%' character followed by d, f or c for int, float or char respectively.
Address of the variable field specifies about the location where value should be stored
after receiving it from keyboard.
41
Let’s use scanf() to take input from user through keyboard.
Example 1
42
In the previous example, we declared an integer variable number_1 to store the
user's input.
Then, printf() function is used to display a message prompting/asking the user to
enter a number.
After that, scanf() is called with the format specifier %d to indicate that we expect
an integer input & address of the variable number_1 is passed using the &
operator.
Once the user enters a number and presses enter, scanf() reads the input and
assigns it to the variable number_1.
Finally, we used printf() again to display the entered number.
It's important to note that scanf() reads input until it encounters a whitespace
character (space, tab, or newline).
43
Let’s ask user for two numbers & print the sum.
Example 2
44
In C++, cout is used to send data/message to monitor.
cout is a predefined object in C++
The operator << is called insertion or put to operator & is used in combination with
cout to display data/messages on monitor.
Let’s understand it with an example using printf & cout:
Output
#include <iostream> Hello Physics
using namespace std; Hello Physics
void main() {
printf(“Hello Physics\n”);
cout << “Hello Physics”;
}
45
Let’s see another example using printf() & cout:
Output
#include <iostream> Value of var1: 25
using namespace std; Value of var1: 25
void main() {
int var1=25;
printf(“Value of var1: %d”,var1);
cout << “Value of var1: ” << var1;
}
46
In C++, cin is used to receive data from standard input device i.e. keyboard.
cin is a predefined object in C++
The operator >> is called extraction or get from operator & is used in combination
with cin to get data from input device.
Let’s understand it with an example using cin:
Output
#include <iostream> Enter a number:20
using namespace std; You Entered: 20
void main() {
int num1,num2;
printf(“Enter a number:”);
cin >> num1;
cout << “You Entered: ” << num1;
} 47
We need to include header file iostream, it contains declaration for the identifier
cout & the operator << as well as cin & the operator >>
endl
Inserting endl into the output stream causes the screen cursor to move to the
beginning of the next line just like we did using \n in C language.
endl is a manipulator & is declared in iostream.h
‘\n’ character also works in C++ as it works in C.
48
Output
#include <iostream> Enter a number: 8
using namespace std; Enter another number: 8
Sum: 16
void main() { Sub: 0
int num1,num2; Div: 1
cout << “Enter a number: ”; Mul: 64
cin >> num1; Rem: 0
cout << “Enter another number: ”;
cin >> num2;
cout << “Sum: ” << num1+num2;
cout << “Sub: ” << num2-num1;
cout << “Div: ” << num1/num2;
cout << “Mul: ” << num1*num2;
cout << “Rem: ” << num1%num2;
}
49
An instruction which is used to manipulate data using operators, is known as
Arithmetic Instruction.
There is no BODMAS rule to prioritize operators in C/C++ but we can remember
precedence/priority (from top to bottom) as listed below:
1. Unary Operators (+, -, ++, --, !, &, ~, sizeof(), *)
2. Arithmetic Operators (+, -, /, *, %)
High to Low
50
Arithmetic Operators
Precedence of *, /, % is higher than + & - but if operators with same
precedence/priority comes in a single line, we will solve them from left to right.
For example:
3 + 4 – 5 => 2
3 + 4 * 5 => 23
3 * 4 / 5 => 12/5 => 2 (Left to Right)
3 + 4 * 5 % 2 => 3 + 20 % 2 => 3 + 0 => 3 (Left to Right)
51
Relational Operators (<, >, <=, >=, ==, !=)
Precedence of >, <, >= & <= is higher than == & != but if operators with same
precedence/priority comes in a single line, we will solve them from left to right.
Relational operators always yields result either 0 or 1
Every non-zero value is True & zero is False.
True is 1 & False is 0.
For example:
15 > 20 => 0
15 == 15 => 1
20 != 30 => 1
3 > 4 < 5 => 0 < 5 => 1 (Left to Right)
52
Unary Operators (+, -, ++, --, !, *, &, ~, sizeof())
Unary operators are the operators that operates on a single operand to produce a
specific result.
Names of these unary operators are:
Unary Plus (+)
Unary Minus (-)
Increment operator (++)
Decrement operator (--)
Address of operator (&)
Dereferencing operator or asterisk (*)
Logical NOT (!) – will discuss in logical Operators topic
Bitwise NOT (~)
53
Unary Plus & Unary Minus
These operators are used to give sign to an expression or a number. For example:
+5 , -10, -22.4, +10.6 and so on
Increment & Decrement Operator
These operators are used to add or subtract 1 from given value or expression. For example:
a=5
++a or a++ will increase value of a by 1 i.e. a=6
--a or a-- will decrease value of a by 1 i.e. a=4
Increment & decrement operators can be classified as:
Pre-Increment or Pre-decrement i.e. ++a or --a
Post-Increment or Post-decrement i.e. a++ or a–
EXCEPTION: Post increment & post decrement has lowest precedence while pre-increment & pre-
decrement has the highest precedence.
54
Logical Operator (&&, ||, !)
Logical Operators are used as conjunctions with relational operators to evaluate an
expression.
These operators takes as input 0 or 1 to produce 0 or 1.
Names of these logical operators are:
Logical AND (&&)
Logical OR (||)
Logical NOT (!)
55
Logical AND, OR & NOT Operators
Following truth table illustrates the working of AND, OR & NOT operator
A B A && B A || B !A !B
0 0 0 0 1 1
0 1 0 1 1 0
1 0 0 1 0 1
1 1 1 1 0 0
56
Conditional or Ternary Operator (? : )
This operator takes three operands to produce an output or result.
It works both in C as well as C++.
Also known as short-hand of if-else.
Syntax is as follows:
Expression 1 ? Expression 2 : Expression 3
Expression 1 if true will trigger Expression 2 otherwise Expression 3 will be executed
Lets understand it with an example.
57
Conditional or Ternary Operator (? : )
59
Compound Assignment Operators (+=, -=, *=, /=, %=)
Lets say, a = 10
a += 2 is same as writing a = a + 2 (Result: a =12)
a -= 2 is same as writing a = a – 2 (Result: a = 8)
a *= 2 is same as writing a = a * 2 (Result: a = 20)
a /= 2 is same as writing a = a / 2 (Result: a = 5)
a %=2 is same as writing a = a % 2 (Result: a = 0)
60
A program is nothing but the execution of sequence of one or more instructions.
Quite often, it is desirable to:
Alter the sequence of the statements in the program depending upon the certain
circumstances or conditions
(OR)
Repeat a group of statements until certain specified conditions are met.
This involves a kind of decision making to see whether a particular condition has
occurred or not and direct the computer to execute certain statements accordingly.
Based on application, it is essential:
1.To alter the flow of a program
2.Test the logical conditions
3.Control the flow of execution
61
C/C++ language supports mainly three types of control structures / statements:
Decision making statements (Conditional Structures)
a) Simple if statement & if – else statement
b) Nested if-else statements
c) else – if ladder
d) switch Statement
Loop Control Statements (Repetitions & Loops)
a) for loop
b) while loop
c) do while loop
62
Conditional Structures / Decision Making Statements
As we know that each line in a program runs sequentially (one by one from top to
bottom) but using the control structures, we can alter this sequence by running a
block of statements when a certain condition is met.
For this purpose, C/C++ language provides us if & if else statements.
The syntax for using it is as follows:
if (condition){
if (condition){ Statement 1;
Statement 1; …..
Statement 2; }
Statement 3; else {
} Statement 1;
….
}
63
Examples
Write a C++ program to take a number from user & print if its even or odd.
64
A Simple Calculator using if-else ladder
65
Conditional Structures / Decision Making Statements switch(Expression){
case a:
Switch statement works similar to if else.
……..
Switch statements works best as compared to if else when ……..
there are conditions are many in numbers. break;
case b:
Syntax of switch is as shown on the right side. ……..
……..
break;
.
.
default:
…..
…..
}
66
Calculator example using switch
statement.
break keyword is used to terminate
the switch state if any of the case
executes.
67
68
Loop Control Structures (repetitions & loops)
If we want to execute a statement more than 1 time, we can use a programming
technique called loop control structures.
Also known as repetitions & loops.
There are three different ways to do this i.e., for loop, while loop, do while loop.
The syntax for each is as follows:
initialization; initialization;
for(initialize; condition; increment/decrement){ while(condition){ do {
Statement 1; Statement 1; Statement 1;
Statement 2; Statement 2; Statement 2;
Statement 3; ….. …..
} } }while(condition);
Syntax: for loop Syntax: while loop Syntax: do while loop
69
Loop Control Structures (repetitions & loops) – Flow Chart
For Loop
70
Examples of repetition & loops
Write a program to print “Hello World” using 10 times using for, while & do while.
71
Write a program to print all even numbers between 0-1000 using for & while loop.
72
Break: Used to jump out of a body (loop, conditions or switch)
Continue: Skips one iteration (in a loop) and continues with next iteration.
Od
d
73
We can write a single line as well as
multi-line comments.
Single line comments are denoted by
double forward slash //
Multi-line comments are enclosed in
/* */
The figure on right side illustrates the
usage of single and multi-line
comments in a C program.
74
Preprocessor directives are special instructions that are processed before the actual
compilation of your C/C++ code.
They begin with a '#' symbol and are used to perform various tasks such as including
header files, defining constants, and performing conditional compilation.
Some of the commonly used preprocessor directives are:
#include
#define
#undef
#error
#pragma
#if
#else
But we will only discuss about #include and #def, remaining are out of scope of
this course.
75
#define: The #define directive is used to
define constants or macros. It allows you to
give a name to a specific value or a piece of
code, which can be used throughout your
program.
#include: The #include directive is used to
include external header files in your C/C++
program. Header files contain declarations
of functions, structures, and other useful
information that your program needs to use.
The example on the right illustrates the usage
of both the directives.
76
Function is a reusable piece of code that performs a specific task.
(OR)
A function is a block of code which only runs when it is called.
Functions help break down a program into smaller, more manageable parts, making the
code more organized, readable, and easier to maintain.
There are two types of functions in C/C++ which are:
1. Predefined functions: These functions are already provided by the programming
language or libraries. They come with the language's standard library and can be
directly used in your program without the need for explicit declaration or definition.
For example printf() & scanf() in C language.
2. User defined functions: These functions are created by the user or programmer to
perform specific tasks. They allow you to modularize your code by breaking it into
smaller, reusable pieces. User-defined functions are defined by the programmer
according to their requirements.
77
Syntax to create a function is as follows:
RETURN_TYPE FUNCTION_NAME(){
---- body -----
}
78
Function definition
A function definition in C/C++ is where you
provide the implementation or the actual code that
makes up the function. It specifies what the function
does when it is called. In a function definition, you
define the function's name, return type (the type
of value the function returns, if any), parameters (if
any), and the body of the function, which contains
the set of statements that are executed when the
function is called.
In the example on the right, we define a
function named "sum" that takes two integer
parameters (a and b). The function calculates their
sum and returns the result as an integer value.
79
Function call
A function call is the act of invoking or executing a function within your code.
It is how you tell the program to run the code inside the function definition. When a
function is called, the program execution temporarily transfers to that function,
executes its code block, and then returns to the point where the function was called.
To call a function, you use the function's name followed by parentheses, and
you may provide any required arguments inside the parentheses. Below is the line to
call the function we created in previous slide:
sum(3, 5);
In this case, we call the "sum" function and pass two arguments (3 and 5). The
function will be executed, and the will return a value (8).
80
Function declaration or prototype
A function prototype, also known as a function declaration, is a way to declare the
existence of a function before its actual definition. It provides important information
about the function, such as its name, return type, and parameters, but without the actual
implementation details.
Here's an example of a function prototype:
int sum(int a, int b);
This prototype informs the compiler about the function named "sum" that takes
two integer parameters and returns an integer value. With this declaration, you can call
the function anywhere in your code, even before its actual definition, and the compiler
will understand what to expect.
Function prototypes are typically placed at the beginning of a program or in
header files (.h) that are included in multiple source files. They serve as a way to provide
a forward declaration of the functions you will be using.
81
Summary
To summarize, function definition is where you write the actual code for a
function, function call is how you invoke or execute a function, and function
prototypes are declarations that provide information about the function before its
definition.
Understanding these concepts is crucial for creating and using functions
effectively in C/C++ programming.
82
Function that takes nothing (no arguments) & returns nothing (no return value)
83
Function that takes something & returns nothing (no return value)
84
Function that takes something & returns something
85
Function that takes nothing & returns something
86