0% found this document useful (0 votes)
14 views

Computer Programming Ppt

sdffg

Uploaded by

shiferachala778
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Computer Programming Ppt

sdffg

Uploaded by

shiferachala778
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 73

Chapter One

Overview of Programming

1 01/27/2025
 What is Computer?

 A Computer is an electronic device that accepts data, performs computations, and makes logical decisions

according to instructions that have been given to it; then produces meaningful information in a form that is
useful to the user.
 In current world we live in, computers are almost used in all walks of life for different purposes.

 They have been deployed to solve different real life problems, from the simplest game playing up to the

complex nuclear energy production.


 In order to solve a given problem, computers must be given the correct instruction about how they can solve

it.
 The terms computer programs, software programs, or just programs are the instructions that tells the

computer what to do.

2 01/27/2025
 Computer programming (often shortened to programming or coding) is the process of writing, testing,

debugging/troubleshooting, and maintaining the source code of computer programs.


 Writing computer programs means writing instructions, that will make the computer follow and run a

program based on those instructions.


 Computer programs (also know as source code) is often written by professionals known as Computer

Programmers (simply programmers).


 Source code is written in one of programming languages.

 A programming language is an artificial language that can be used to control the behavior of a machine,

particularly a computer.
 In general, programming languages allow humans to communicate instructions to machines.

 A main purpose of programming languages is to provide instructions to a computer.

3 01/27/2025
C++ Program
 Before starting the abcd of C++ language, you need to learn how to write, compile and run the first C++ program.

 To write the first C++ program, open the C++ console and write the following code:

#include <iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout << "Welcome to C++ Programming.";
getch();
}
4 01/27/2025
 #include<iostream.h>

 includes the standard input output library functions.

 It provides cin and cout methods for reading from input and writing to output respectively.

 #include <conio.h>

 includes the console input output library functions. The getch() function is defined in conio.h file.

 void main()

 The main() function is the entry point of every program in C++ language.

 The void keyword specifies that it returns no value.

 cout << "Welcome to C++ Programming."

 is used to print the data "Welcome to C++ Programming." on the console.

 getch()

 The getch() function asks for a single character. Until you press any key, it blocks the
5 01/27/2025
screen.
6 01/27/2025
 How to compile and run the C++ program

 There are 2 ways to compile and run the C++ program, by menu and by shortcut.

 By menu

 Now click on the compile menu then compile sub menu to compile the c++ program.

 Then click on the run menu then run sub menu to run the c++ program.

 By shortcut

 Or, press ctrl+f9 keys compile and run the program directly.

 You will see the following output on user screen.

Welcome to C++ Programming

 You can view the user screen any time by pressing the alt+f5 keys.

7  Now press Esc to return to the turbo c++ console. 01/27/2025


C++ Basic Input/Output

 C++ I/O operation is using the stream concept.

 Stream is the sequence of bytes or flow of data.

 It makes the performance fast.

 If bytes flow from main memory to device like printer, display screen, or a network connection,

etc, this is called as output operation.


 If bytes flow from device like printer, display screen, or a network connection, etc to main

memory, this is called as input operation.

8 01/27/2025
 I/O Library Header Files

 Let us see the common header files used in C++ programming are:

Header File Function and Description

<iostream> It is used to define the cout, cin and cerr objects, which
correspond to standard output stream, standard input
stream and standard error stream, respectively.

<iomanip> It is used to declare services useful for performing


formatted I/O, such as setprecision and setw.

<fstream> It is used to declare services for user-controlled file


processing.

9 01/27/2025
Standard output stream (cout)
 The cout is a predefined object of ostream class.

 It is connected with the standard output device, which is usually a display screen.

 The cout is used in conjunction with stream insertion operator (<<) to display the output on a console
 Let's see the simple example of standard output stream (cout):

#include <iostream>
using namespace std;
int main( )
{
char ary[] = "Welcome to C++ tutorial";
cout << "Value of ary is: " << ary << endl;
return 0;
} Value of ary is:Welcome to C++ tutorial

Output:
10 01/27/2025
Standard input stream (cin)
 The cin is a predefined object of istream class.

 It is connected with the standard input device, which is usually a keyboard.

 The cin is used in conjunction with stream extraction operator (>>) to read the input from a console.
 Let's see the simple example of standard input stream (cin):

#include <iostream>
using namespace std;
int main( )
{
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl; Enter your age:22
} Your age is: 22
11 Output: 01/27/2025
Standard end line (endl)
 The endl is a predefined object of ostream class.
 It is used to insert a new line characters and flushes the stream.
 Let's see the simple example of standard end line (endl):

#include <iostream>
using namespace std;
Output:
int main( ) {
cout << "C++ Tutorial";
cout << "programming"<<endl; C++ Tutorial programming
End of line
cout << "End of line"<<endl;
return 0;
}
12 01/27/2025
C++ Variable
 A variable is a name of memory location.

 It is used to store data.

 Its value can be changed and it can be reused many times.

 It is a way to represent memory location through symbol so that it can be easily identified.

 Let's see the syntax to declare a variable:

type variable_list;
 The example of declaring variable is given below: between JDK, JRE, and JVM
 int x;
 float y;
 char z;

13 Here, x, y, z are variables and int, float, char are data types. 01/27/2025
 We can also provide values while declaring the variables as given below:

 int x=5,b=10; //declaring 2 variable of integer type


 float f=30.8;
 char c='A';

Rules for defining variables


 A variable can have alphabets, digits and underscore.
 A variable name can start with alphabet and underscore only.
 It can't start with digit.
 No white space is allowed within variable name.
 A variable name must not be any reserved word or keyword e.g. char, float etc.

 Valid variable names:  Invalid variable names:


 int a;  int 4;
 int _ab;  int x y;
 int a30;  int double;

14 01/27/2025
C++ Data Types
 A data type specifies the type of data that a variable can store such as integer, floating, character etc.

15 01/27/2025
 There are 4 types of data types in C++ language.

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data enum


Type
User Defined Data structure
Type

16 01/27/2025
 Basic Data Types

 The basic data types are integer-based and floating-point based.

 C++ language supports both signed and unsigned literals.

 The memory size of basic data types may change according to 32- or 64-bit operating system.o Java Pro

 Let's see the basic data types. It size is given according to 32 bit OS.

17 01/27/2025
Data Types Memory Size Range

char 1 byte -128 to 127


signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 127
short 2 byte -32,768 to 32,767
signed short 2 byte -32,768 to 32,767
unsigned short 2 byte 0 to 32,767
int 2 byte -32,768 to 32,767
signed int 2 byte -32,768 to 32,767
unsigned int 2 byte 0 to 32,767
short int 2 byte -32,768 to 32,767
signed short int 2 byte -32,768 to 32,767
unsigned short int 2 byte 0 to 32,767
long int 4 byte
signed long int 4 byte
unsigned long int 4 byte
float 4 byte
double 8 byte
18 01/27/2025
long double 10 byte
C++ Keywords
 A keyword is a reserved word.
 You cannot use it as a variable name, constant name etc.
 A list of 32 Keywords in C++ Language which are also available in C language are given below.

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

 A list of 30 Keywords in C++ Language which are not available in C language are given below.

asm dynamic_cast namespace reinterpret_cast bool

explicit new static_cast false catch

operator template friend private class

this inline public throw const_cast

delete mutable protected true try


19 typeid typename using virtual wchar_t 01/27/2025
C++ Operators
 An operator is simply a symbol that is used to perform operations.

 There can be many types of operations like arithmetic, logical, bitwise etc.

 There are following types of operators to perform different types of operations in C++ language.

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operator
 Unary operator
 Ternary or Conditional Operator
 Increment and Decrement Operator

20 01/27/2025
21 01/27/2025
Increment and Decrement Operators

 For increasing and decreasing the values of integral objects by unity, we may make use of:

 increment operator ++ and decrement operator – – respectively.

 These operators may be placed before or after the variable name.

 When the operators ++ and – – are placed before the variable name, these are called pre-

increment and pre-decrement operators respectively.


 When the operators are placed after the names then these are called post-increment and post-

decrement operators.
 In case of pre-increment the present value of variable is first increased by unity and the

incremental value is then used in the application.

22 01/27/2025
 And in case of post-increment, the present value of variable is used in the application and then the value of
variable is incremented.
 Same is the case of operator --.

The pre and post versions of ++ and -- are also elaborated in table below.
 Also take care that there should not be any space between ++ or between -- because this may result in error.

23 01/27/2025
The following program illustrates the increment and decrement operators.

#include <iostream>
using namespace std;
int main() OutPut

{ A = 36 n =
int a = 6, p = 4,r=3,n =5,A,B,C,K ; 6
A = 6*++n ; K = 30 a = 5
cout << “A = “<<A <<“\t n = “ <<n <<endl;
B = 12 r =
K = 5*a– – ;
cout<<“K = “<<K<<“\t a = “ <<a << endl;
5
B =r++*r++ ; C= 12 p=
cout<< “B = “<<B<<“\t r = “<< r << endl; 2
C = p– –*p– –;
cout<<“C= “<< C<<“\t p= “ << p << endl;
24
return 0; 01/27/2025
}
Precedence of Operators in C++
 The precedence of operator species that which operator will be evaluated first and next.

 The associativity specifies the operators direction to be evaluated, it may be left to right or right to left.

 Let's understand the precedence by the example given below: ++ vs Java

 int data= 5+10*10;


 The "data" variable will contain 105 because * (multiplicative operator) is evaluated before + (additive

operator).
 The precedence and associativity of C++ operators is given below:

25 01/27/2025
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right


Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Right to left
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == !=/td> Right to left
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Right to left
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


26 01/27/2025
C++ Identifiers
 C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or other user-

defined data types created by the programmer.


 They are the basic requirement of any language.

 Every language has its own rules for naming the identifiers.

Some naming rules are common in both C and C++. They are as follows:

 Only alphabetic characters, digits, and underscores are allowed.

 The identifier name cannot start with a digit, i.e., the first letter should be alphabetical.

 After the first letter, we can use letters, digits, or underscores.

 In C++, uppercase and lowercase letters are distinct.

 Therefore, we can say that C++ identifiers are case-sensitive.


27 01/27/2025
 A declared keyword cannot be used as a variable name.
 For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname’.

 Both the identifiers will be different as the letter 'N' in the first case in uppercase while lowercase in second.

 Therefore, it proves that identifiers are case-sensitive.

 Valid Identifiers

 The following are the examples of valid identifiers are:

 Result Identifiers are used to name a variable, a function, a


class, a structure, a union.
 Test2

 _sum Variables are used to give a name to a memory


location that holds a value. Hence, a variable is also an
 power identifier. The names of variables are different which
cannot be a keyword.

 Invalid Identifiers

 The following are the examples of invalid identifiers:


 Sum-1 // containing special character '-'.

 2data // the first letter is a digit.


28 01/27/2025
 break // use of a keyword.
 Let's look at a simple example to understand the concept of identifiers.

#include <iostream>
using namespace std;
int main() OutPut

{
int a;
int A;
cout<<"Enter the values of 'a' and 'A'";
cin>>a;
cin>>A;
cout<<"\nThe values that you have entered are : "<<a<<" , "<<A;
return 0;
}
 In the above code, we declare two variables 'a' and 'A’.

 Both the letters are same but they will behave as different identifiers.

29 01/27/2025
 As we know that the identifiers are the case-sensitive so both the identifiers will have different memory locations.
 Differences between Identifiers and Keywords

Identifiers Keywords

Identifiers are the names defined by the programmer to Keywords are the reserved words whose meaning is
the basic elements of a program. known by the compiler.

It is used to identify the name of the variable. It is used to specify the type of entity.
It can consist of letters, digits, and underscore. It contains only letters.
It can use both lowercase and uppercase letters. It uses only lowercase letters.

No special character can be used except the underscore. It cannot contain any special character.

The starting letter of identifiers can be lowercase, It can be started only with the lowercase letter.
uppercase or underscore.
It can be classified as internal and external identifiers. It cannot be further classified.

Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.
30 01/27/2025
C++ Expression
 C++ expression consists of operators, constants, and variables which are arranged according to the rules

of the language.
 It can also contain function calls which return values.

 An expression can consist of one or more operands, zero or more operators to compute a value.

 Every expression produces some value which is assigned to the variable with the help of an assignment

operator.
Examples of C++ expression:
 (a+b) -c
 (x/y) -z
 4a2 - 5b +c
 (a+b) * (x+y)

31 01/27/2025
 An expression can be of following types:

32 01/27/2025
Constant expressions
 A constant expression is an expression that consists of only constant values.

 It is an expression whose value is determined at the compile-time but evaluated at the run-time.

 It can be composed of integer, character, floating-point, etc.

 Let's see a simple program containing constant expression:

#include <iostream>
using namespace std; OutPut
int main()
{
int x; // variable declaration. Value of x is: 3
x=(3/2) + 2; // constant expression
cout<<"Value of x is : "<<x; // displaying the value of x.
return 0;
}
 In the above code, we have first declared the 'x' variable of integer type.

33 01/27/2025
 After declaration, we assign the simple constant expression to the 'x' variable.
Integral Expressions
 An integer expression is an expression that produces the integer value as output after performing all the

explicit and implicit conversions.

Following are the examples of integral expression:


 (x * y) -5

 x + int(9.0)

 where x and y are the integers.

34 01/27/2025
 Let's see a simple example of integral expression:

#include <iostream>
using namespace std;
outpu
int main()
t
{
int x; // variable declaration. Enter the value of x and
int y; // variable declaration y
8
int z; // variable declaration 9
cout<<"Enter the values of x and y"; Value of z is: 17
cin>>x>>y;
z=x+y;
cout<<"\n"<<"Value of z is :"<<z; // displaying the value of z.
return 0;
}
 In the above code, we have declared three variables, i.e., x, y, and z.

 After declaration, we take the user input for the values of 'x' and 'y’.
35 01/27/2025
 Then, we add the values of 'x' and 'y' and stores their result in 'z' variable.
 Let's see another example of integral expression.

#include <iostream>
using namespace std;
int main()
{
int x; // variable declaration
OutPut
int y=9; // variable initialization
x=y+int(10.0); // integral expression
cout<<"Value of x : "<<x; // displaying the value of x.
Value of x: 19
return 0;
}
 In the above code, we declare two variables, i.e., x and y.

 We store the value of expression (y+int(10.0)) in a 'x' variable.

36 01/27/2025
Float Expressions
 A float expression is an expression that produces floating-point value as output after performing all the

explicit and implicit conversions.


 The following are the examples of float expressions:

 x+y
 (x/10) + y
 34.5
 x+float(10)
OutPut
 Let's understand through an example.
#include <iostream>
using namespace std;
int main()
{ Value of z is: 14.5
float x=8.9; // variable initialization
float y=5.6; // variable initialization
float z; // variable declaration
z=x+y;
cout <<"value of z is :" << z<<endl; // displaying the value of z.
return 0;
}
37 01/27/2025
Relational Expressions
 A relational expression is an expression that produces a value of type bool, which can be either true or false.

 It is also known as a boolean expression.

 When arithmetic expressions are used on both sides of the relational operator, arithmetic expressions are

evaluated first, and then their results are compared.


 The following are the examples of the relational expression:

 a>b
 a-b >=x-y
 a+b>80

38 01/27/2025
 Let's understand through an example

#include <iostream>
using namespace std;
int main()
Output
{
int a=45; // variable declaration
int b=78; // variable declaration
bool y= a>b; // relational expression Value of y is:
0
cout<<"Value of y is :"<<y; // displaying the value of y.
return 0;
}
 In the above code, we have declared two variables, i.e., 'a' and 'b’.

 After declaration, we have applied the relational operator between the variables to check whether 'a' is greater than 'b'

or not.
39 01/27/2025
Logical Expressions
 A logical expression is an expression that combines two or more relational expressions and produces a bool type value.

 The logical operators are '&&' and '||' that combines two or more relational expressions.
 The following are some examples of logical expressions:
Output
 a>b && x>y
 a>10 || b==5
 Let's see a simple example of logical expression.
#include <iostream>
using namespace std; 0
int main()
{
int a=2;
int b=7;
int c=4;
cout<<((a>b)||(a>c));
40 return 0; 01/27/2025
Special Assignment Expressions
Special assignment expressions are the expressions which can be further classified depending upon the value
assigned to the variable.

Chained Assignment
 Chained assignment expression is an expression in which the same value is assigned to more than one

variable by using single statement.


 For example:

 a=b=20
 or
 (a=b) = 20

41 01/27/2025
 Let's understand through an example.
Output
#include <iostream>
using namespace std;
int main()
{
Values of 'a' and 'b' are :80,80
int a; // variable declaration
int b; // variable declaration
a=b=80; // chained assignment
cout <<"Values of 'a' and 'b' are : " <<a<<","<<b<< endl;
Note: Using chained assignment expression, the value cannot be assigned to
return 0;
the variable at the time of declaration. For example, int a=b=c=90 is an
} invalid statement.
 In the above code, we have declared two variables, i.e., 'a' and 'b’.

 Then, we have assigned the same value to both the variables using chained assignment expression.
42 01/27/2025
Embedded Assignment Expression
 An embedded assignment expression is an assignment expression in which assignment expression is enclosed within

another assignment expression.


 Let's understand through an example. Outp
ut
#include <iostream>
using namespace std;
int main()
{ Values of 'a’ is 100
int a; // variable declaration
int b; // variable declaration
a=10+(b=90); // embedded assignment expression
cout <<"Values of 'a' is " <<a<<endl;
return 0;
}
 In the above code, we have declared two variables, i.e., 'a' and 'b’. 01/27/2025
43
 Compound Assignment
 A compound assignment expression is an expression which is a combination of an assignment operator and

binary operator.
 For example,
 a+=10; Outp
 In the above statement, 'a' is a variable and '+=' is a compound statement. ut
 Let's understand through an example.

#include <iostream>
using namespace std;
Values of a is:20
int main()
{
int a=10; // variable declaration
a+=10; // compound assignment
cout << "Value of a is :" <<a<<endl; // displaying the value of a.
return 0;
}
 In the above code, we have declared a variable 'a' and assigns 10 value to this variable.
44 01/27/2025
 Then, we applied compound assignment operator (+=) to 'a' variable, i.e., a+=10 which is equal to (a=a+10).
C++ Comments
 The C++ comments are statements that are not executed by the compiler.

 The comments in C++ programming can be used to provide explanation of the code, variable, method or class.

 By the help of comments, you can hide the program code also.

 There are two types of comments in C++.

 Single Line comment

 Multi Line comment

45 01/27/2025
C++ Single Line Comment
 The single line comment starts with // (double slash).

 Let's see an example of single line comment in C++.


Output
#include <iostream>
using namespace std;
int main()
{ 11
int x = 11; // x is a variable
cout<<x<<"\n";
return 0;
}

46 01/27/2025
C++ Multi Line Comment
 The C++ multi line comment is used to comment multiple lines of code.

 It is surrounded by slash and asterisk (/∗ ..... ∗/).

 Let's see an example of multi line comment in C++. Output


#include <iostream>
using namespace std;
int main() 35
{
/* declare and
print variable in C++. */
int x = 35;
cout<<x<<"\n";
return 0;

47 } 01/27/2025
CONDITIONAL EXPRESSIONS

 In C++ three conditional expressions are provided. These are

 (i) if, (ii) if .... else and (iii) switch .


 The if condition gives the option of single choice, i.e. if the conditional expression is true the statement

following the condition is carried out.


 If the condition is false the following statement is discarded and program goes to next statement.

 In if .... else there are two choices.

 One choice is with if and the second choice is with else.

 If the conditional expression is true the statement following if is carried out otherwise the statement

following else is carried out.

48 01/27/2025
 In switch condition more than two choices are generally provided.

 There is no limit to the number of choices.

 Each switch condition may have its own choice condition.

 Similar results may also be obtained by using a chain of if .... else statements.

49 01/27/2025
C++ IF Statement

 The C++ if statement tests the condition.

 It is executed if condition is true.

if(condition)
{
//code to be executed
}
 The first line of code is the condition.

 If the expression in the parentheses is true, the

statement following the expression would be


carried out, otherwise the statement would be
ignored and the program would proceed further.
50 01/27/2025
C++ If Example

#include <iostream>
using namespace std;
int main () Output

{
int num = 10;
if (num % 2 == 0)
{ It is even number

cout<<"It is even number";


}
return 0;
}
51 01/27/2025
#include <iostream>
using namespace std;
int main()
{int n , m ,p;
outpu
cout<<“Enter three integers.”;

cin>>m>>n>>p;
t
if(n == m) // If n is equal to m Display the following.

cout<<“n and m are equal”<<endl;

if(m !=n) // If m is not equal to n, display the following Enter three integers.30 30
cout << “n and m are not equal. ”<<endl; 40
if (m >=p) // If m is greater than or equal to p. n and m are equal
cout <<“m is greater than p”<<endl; p is greater than m.
if ( p>=m)

cout<< “p is greater than m.”<<endl;

return 0;
}
52 01/27/2025
C++ IF-else Statement

 The C++ if-else statement also tests the

condition.
 It executes if block if condition is true

otherwise else block is executed.


if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
53 01/27/2025
C++ If-else Example

#include <iostream>
using namespace std;
int main () { outpu
int num = 11; t
if (num % 2 == 0)
{
cout<<"It is even number";
} It is odd number
else
{
cout<<"It is odd number";
}
return 0;
}
54 01/27/2025
#include<iostream> outp
using namespace std; ut
int main()
{
Write your marks: 46
int Marks; You are not eligible for
cout<<“Write your marks: ”; admission.
cin>>Marks;
if (Marks>= 50) // conditional statement
cout << “You are eligible admission.”<< endl;
else
cout << “You are not eligible for admission.” <<endl;
return 0;
}
55 01/27/2025
C++ IF-else-if ladder Statement

 The C++ if-else-if ladder statement


executes one condition from multiple
statements.
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//
code to be executed if all the conditions are false
56 01/27/2025
}
#include <iostream> else if (num >= 60 && num < 70)
using namespace std; {
int main () { cout<<"C Grade";
int num; }
cout<<"Enter a number to check grade:"; else if (num >= 70 && num < 80)
cin>>num; {
if (num <0 || num >100) cout<<"B Grade";
{ }
cout<<"wrong number"; else if (num >= 80 && num < 90)
} outp {
ut
else if(num >= 0 && num < 50){ cout<<"A Grade";
cout<<"Fail"; }
} else if (num >= 90 && num <= 100)
else if (num >= 50 && num < 60) {
{ cout<<"A+ Grade";
cout<<"D Grade"; }
} Enter
Enter aa number
number to
to check
check grade:-2
grade:66}
57 01/27/2025
Wrong
C Gradenumber
C++ switch
 During execution of the program, the switch expression is
evaluated.
 The C++ switch statement executes one statement from multiple
 The expression should evaluate to an integer value.
conditions.
 Its value is compared with the values mentioned in different
 It is like if-else-if ladder statement in C++.

 For a large number of choices the if-else chain becomes unwieldy


cases mentioned under switch expression.
and confusing.  If the value matches a value of a particular case, the
 A better method is the switch expression which is illustrated statements in that case are carried out.
below.  If no case-value matches with the value of switch
switch(expression){ expression the program comes to the last statement which is
case value1: a default statement.
//code to be executed;  Provision of default statement is optional.
break;  It is useful in case of user interactive programs where the
case value2: user may enter a wrong value by mistake.
//code to be executed;  The statements contained in default case can remind the
break;
user that the data was wrong and prompt the user to enter
...... correct data.
default:  After each case the statement break; is provided to get out
// of the switch at the end of a case which matched the key.
code to be executed if all cases are not matched;
 If this is not provided, then all the statements following the

break;
match would also be carried out which is not desirable.
58 01/27/2025
}
 The following points must be taken care of while using switch statement.

 The (expression) must evaluate to an integral value.

 Characters may also be used in the switch expression because characters also have

integer value as per ASCII code.


 The choices are enclosed between a pair of curly brackets.

 Each case value is followed by colon ( : ).

 All the statements following a match are carried out. After the colon there may be one

or more than one statements.


 In case of multiple statements there is no need to put them between curly braces.

 The break statement should be given at end of every case, otherwise, all the cases

following a match would be carried out.


 The following figure illustrates the execution of switch statement.

59 01/27/2025
60 01/27/2025
C++ Switch Example
outp
ut
#include <iostream>
using namespace std;
int main ()
{
int num; grade:10
Enter a number to check grade:55
cout<<"Enter a number to check grade:"; It is 10,
Not 10 20 or 30
cin>>num;
switch (num)
{
case 10: cout<<"It is 10";
break;
case 20: cout<<"It is 20";
break;
case 30: cout<<"It is 30";
break;
default: cout<<"Not 10, 20 or 30";
break;
61 } 01/27/2025
}
THE for LOOP
 The C++ for loop is used to iterate a part of the program several times.

 If the number of iteration is fixed, it is recommended to use for loop than while or do-while loops.

 The for loop is coded as given below.

for (initial value of variable ; conditional expression ; mode of increment /decrement)


statement ;
 There are three expressions inside the brackets separated by two semicolons.

 In the first expression the variable controlling the loop is initialized, i.e. its initial value is

specified,
 in the second expression its final or limiting value is given, i.e. the value of the variable at which

the loop should terminate,


 in the third expression the mode of increment/decrement is specified.
62 01/27/2025
 The working of a for loop is illustrated in Fig below.
outpu
C++ For Loop Example t

#include <iostream>
using namespace std; 1
int main() 2
3
{ 4
5
for(int i=1;i<=10;i++) 6
{ 7
8
cout<<i <<"\n"; 9
10
}
}

63 01/27/2025
C++ Nested For Loop Example

output
Let's see a simple example of nested
for loop in C++.
11
12
#include <iostream> 13
using namespace std; 21
22
int main () 23
{ 31
for(int i=1;i<=3;i++) 32
{ 33
for(int j=1;j<=3;j++)
{
cout<<i<<" "<<j<<"\n";
}
}
64
} 01/27/2025
C++ While loop

 In C++, while loop is used to iterate a part


of the program several times.
 If the number of iteration is not fixed, it is
recommended to use while loop than for
loop.

while(condition)
{
//code to be executed
}

65 01/27/2025
C++ While Loop Example
 Let's see a simple example of while loop output

#include <iostream>
using namespace std;
1
int main() {
2
int i=1; 3
4
while(i<=10)
5
{ 6
7
cout<<i <<"\n";
8
i++; 9
10
}

66 01/27/2025
 Let's see a simple example of nested while loop in C++
C++ Nested While Loop Example
programming language.
 In C++, we can use while loop inside another while loop, it is
known as nested while loop.
 The nested while loop is executed fully when outer loop is #include <iostream>
executed once. using namespace std;
outpu int main ()
 The i loop is the outer loop and j loop is the inner loop. t
 The manner in which code may be written is illustrated below. {
int i=1;
while (int i < n) while(i<=3)
{
{ statements ; 11
12 int j = 1;
13 while (j <= 3)
while (int j < m)
21 {
{ statements ; 22 cout<<i<<" "<<j<<"\n";
23 j++;
statement ; 31 }
32
i++;
} 33
}
67 01/27/2025
} }
C++ Do-While Loop

 The C++ do-while loop is used to iterate a

part of the program several times.


 If the number of iteration is not fixed and you

must have to execute the loop at least once, it


is recommended to use do-while loop.
 The C++ do-while loop is executed at least

once because condition is checked after loop


body.

68 01/27/2025
 C++ do-while Loop Example
output
 Let's see a simple example of C++ do-while

loop

1
#include <iostream> 2
3
using namespace std; 4
5
int main() { 6
7
int i = 1; 8
9
do{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
69 01/27/2025
C++ Nested do-while Loop

 In C++, if you use do-while loop inside output

another do-while loop, it is known as nested


do-while loop.
 The nested do-while loop is executed fully for
each outer do-while loop. 11
12
 Let's see a simple example of nested do-while 13
loop in C++. 21
22
#include <iostream> 23
using namespace std;
int main() { 31
int i = 1; 32
do{
int j = 1; 33
do{
cout<<i<<j<<"\n";
j++;
} while (j <= 3) ;
i++;
70 } while (i <= 3) ; 01/27/2025
}
C++ Break Statement

C++ Break Statement Example


 The C++ break is used to break loop or switch  Let's see a simple example of C++ break statement
which is used inside the loop.
statement. It breaks the current flow of the program
at the given condition. In case of inner loop, it #include <iostream>
using namespace std;
breaks only inner loop. int main() {
for (int i = 1; i <= 10; i++)
1. jump-statement; {
if (i == 5)
2. break; { output
break;
}
cout<<i<<"\n";
}
return 0;
} 1
2
3
4

71 01/27/2025
C++ Continue Statement
 C++ Continue Statement Example

 The C++ continue statement is used to #include <iostream>


continue loop. output
using namespace std;
 It continues the current flow of the program
int main()
and skips the remaining code at specified {
condition. 1
for(int i=1;i<=10;i++){
 2
In case of inner loop, it continues only inner if(i==5){ 3
loop. 4
continue;
6
1. jump-statement; } 7
2. continue;
8
cout<<i<<"\n"; 9
10
}
return 0:
72 } 01/27/2025
The End!

73 01/27/2025

You might also like