SlideShare uma empresa Scribd logo
1 de 45
Baixar para ler offline
PROGRAMMING FOR PROBLEM
SOLVING
SEMESTER: 1st
PREPARED BY:
CHAPTER 3 TOPIC 4
• Loops
• While loop
• Do...while loop
• Switch Statement
2
WHILE LOOP
• A while loop in C programming
repeatedly executes a target
statement as long as a given
condition is true.
3
WHILE LOOP
• Syntax :
While (Test Expression)
{
// statements inside the body of the loop
}
4
WHILE LOOP
How While loop works :
• The while loop evaluates the test expression inside the parenthesis ().
• If the test expression is true, statements inside the body of while loop are
executed. Then, the test expression is evaluated again.
• The process goes on until the test expression is evaluated to false.
• If the test expression is false, the loop terminates (ends).
5
WHILE LOOP
// Print numbers from 1 to 5
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%dn", i);
++i;
}
return 0;
}
Here, we have initialized i to 1.
• When i is 1, the test expression i <= 5 is
true. Hence, the body of the while loop is
executed. This prints 1 on the screen
and the value of i is increased to 2.
• Now, i is 2, the test expression i <= 5 is
again true. The body of the while loop is
executed again. This prints 2 on the
screen and the value of is increased
to 3.
• This process goes on until i becomes 6.
When i is 6, the test expression i<=5 will
be false and the loop terminates.
6
Output :
1
2
3
4
5
DO...WHILE LOOP
• The do..while loop is similar to
the while loop with one important
difference.
• The body of do...while loop is
executed at least once. Only then,
the test expression is evaluated.
7
DO...WHILE LOOP
• Syntax :
do
{
// statements inside the body of the loop
} while (Test Expression);
8
DO...WHILE LOOP
How Do...While loop works :
• The body of do...while loop is executed once. Only then, the test expression
is evaluated.
• If the test expression is true, the body of the loop is executed again and the
test expression is evaluated.
• This process goes on until the test expression becomes false.
• If the test expression is false, the loop ends.
9
DO...WHILE LOOP
// Print numbers from 1 to 5
#include <stdio.h>
int main()
{
int i = 1;
do
{
printf("%dn", i);
++i;
} while(i <= 5) ;
return 0;
}
Here, we have initialized i to 1.
• As we know that do…while loop is
executed at least one time, it will be
printed when i=1 and then i
increments to 2.
• Now, i is 2, the test expression i <=
5 is true. The body of the do…while
loop is executed again. This prints 2
on the screen and the value of i is
increased to 3.
• This process goes on until i becomes
6. When i is 6, the test
expression i<=5 will be false and the
loop terminates.
10
Output :
1
2
3
4
5
SWITCH STATEMENTS
• The switch statement allows us to
execute one code block among many
alternatives.
• You can do the same thing with
the if...else..if ladder. However, the
syntax of the switch statement is
much easier to read and write.
11
SWITCH STATEMENTS
• Syntax :
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
. . .
default:
// default statements
}
12
SWITCH STATEMENTS
How switch case works :
• The expression is evaluated once and compared with the values of
each case label.
• If there is a match, the corresponding statements after the matching label are
executed. For example, if the value of the expression is equal to constant2,
statements after case constant2: are executed until break is encountered.
• If there is no match, the default statements are executed.
• If we do not use break, all statements after the matching label are executed.
• By the way, the default clause inside the switch statement is optional.
13
14
• In the given program we have
initialized a variable x with value 2.
• A switch construct is used to compare
the value stored in variable x and
execute the block of statements
associated with the matched case.
• In this program, since the value stored
in variable x is two, a switch will
execute the case whose case-label is 2.
After executing the case, the control
will fall out of the switch and program
will be terminated with the successful
result by printing the value on the
output screen.
// Following is a simple C program to
demonstrate syntax of switch.
#include <stdio.h>
int main()
{
int x = 2;
switch (x)
{
case 1:
printf("Choice is 1");
break;
case 2:
printf("Choice is 2");
break;
case 3:
printf("Choice is 3");
break;
default:
printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}
PROGRAMMING FOR PROBLEM
SOLVING
UNIT – 3 CONTROL STRUCTURE
SEMESTER: 1st
PREPARED BY: Prof. Brijesh Hansaliya
FOR LOOP
• Loop Concept
Loop is a repetition for series of actions and
activities.
In programming sometimes we need to repeat
block or statement for some period.
Loop is helping to repeat particular block or set
of statements for particular time period.
When to stop looping?
In chart , action is executed over and over again.
It never stop – This is called an Infinite Loop
Solution – Put a condition to tell the loop either
to continue or stop
2
An actions
and activities
or series of
actions and
activities
CONTINUE…
Main part of loop : Body and Condition
Body : Statement or Block of statements that will
be repeated.
Condition : It is used to control iteration either to
continue or stop the iteration.
3
Body Of Loop
Condi
tion
True
False
PRE-TEST LOOP
Condition is tested First before start executing
the body.
Body of the loop will executed if the condition is
true.
If condition becomes false loop will terminate.
After executing body again condition is tested.
4
Body Of Loop
Condi
tion
False
Pre-test Loop (FOR LOOP)
True
Stop
FOR LOOP
The for loop in C language is used to repeat the
statements or a block of the program several times.
The syntax of for loop in c language is given below:
for( Initialization ; Condition ; Increment or Decrement )
{
Statement block to be executed ;
}
Loop Execution :
Step 1: First initialization happens and the counter
variable gets initialized. Execute only One time.
Step 2: In the second step the condition is checked, if
the condition is true then the C statements inside the
body of for loop gets executed, if the condition is false
then the for loop gets terminated.
Step 3: After successful execution of statements inside
the body of loop, the counter variable is incremented or
decremented, depending on the operation (++ or –-).
5
Initialization
Condition
Statement
Incr / Decr
True
False
Stop
FOR Loop
Flow Chart
WHILE LOOP
for (
)
FOR LOOP
COMPARING FOR AND WHILE
6
Initialize
While (Expression)
{
} /* While */
action
action
update counter
Initialize;
Condition;
Increment or
Decrement;
{
} /* For */
action
action
action
Continue…
Continue…
FOR LOOP EXAMPLE 1
// Print numbers from 1 to 10
#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
O / P :
1 2 3 4 5 6 7 8 9 10
7
1. i is initialized to 1.
2. The test expression i < 11 is evaluated.
Since 1 less than 11 is true, the body
of for loop is executed. This will print
the 1 (value of i) on the screen.
3. The update statement ++i is executed.
Now, the value of i will be 2. Again, the test
expression is evaluated to true, and the
body of for loop is executed. This will
print 2 (value of i) on the screen.
4. Again, the update statement ++i is
executed and the test expression i < 11 is
evaluated. This process goes on
until i becomes 11.
5. When i becomes 11, i < 11 will be false,
and the for loop terminates.
FOR LOOP EXAMPLE 2
#include <stdio.h>
int main()
{ int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
O/P :
Enter a positive integer: 5
Sum = 15
8
The value entered by the user is stored in the
variable num. Suppose, the user entered 5.
The count is initialized to 1 and the test expression is
evaluated. Since the test expression count<=num (1
less than or equal to 5) is true, the body of for loop is
executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and
the count will equal to 2. Again, the test expression is
evaluated. Since 2 is also less than 5, the test
expression is evaluated to true and the body of for loop
is executed. Now, the sum will equal 3.
This process goes on and the sum is calculated until
the count reaches 6.
When the count is 6, the test expression is evaluated to
false, and the loop terminates.
Then, the value of sum is printed on the screen.
VARIOUS FORMS OF FOR LOOP IN C
Suppose we are using variable num as the counter in all the following examples –
1) Here instead of num++, I’m using num=num+1 which is same as num++.
for (num=10; num<20; num=num+1)
2) Initialization part can be skipped from loop as shown below, the counter variable is declared
before the loop.
int num=10;
for ( ; num<20;num++)
Note: Even though we can skip initialization part but semicolon (;) before condition is must,
without which you will get compilation error.
3) Like initialization, you can also skip the increment part as we did below. In this case
semicolon (;) is must after condition logic. In this case the increment or decrement part is done
inside the loop.
for (num=10; num<20; )
{ //Statements
num++;
}
9
CONTINUE….
4) This is also possible. The counter variable is initialized before the loop and incremented
inside the loop.
int num=10;
for (;num<20;)
{
//Statements
num++;
}
5) As mentioned above, the counter variable can be decremented as well. In the below example
the variable gets decremented each time the loop runs until the condition num>10 returns false.
for(num=20; num>10; num--)
10
NESTED LOOPS IN C
• C supports nesting of loops. Nesting of loops is the feature that allows the
looping of statements inside another loop.
• Any number of loops can be defined inside another loop, i.e., there is no
restriction for defining any number of loops. The nesting level can be defined at
n times.
Syntax for Nested Looping :
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
11
NESTED FOR LOOP
The nested for loop means for loop which is
defined inside the another 'for' loop.
for (initialization; condition; increment or
decrement)
{
for(initialization; condition; increment or
decrement)
{
// inner loop statements.
}
// outer loop statements.
}
12
Nested For loop Flow Chart :
NESTED FOR LOOP EXAMPLE
#include <stdio.h>
int main(void)
{ int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<=i;j++)
{
printf(" *");
}
printf("n");
}
return 0;
}
O/P : *
* *
* * *
* * * *
* * * * *
13
First, the 'i' variable is initialized to 1 and then program control
passes to the i<5.
The program control checks whether the condition 'i<5' is true or not.
If the condition is true, then the program control passes to the inner
loop.
The inner loop will get executed until the condition is true.
After the execution of the inner loop, the control moves back to the
update of the outer loop, i.e., i++.
After incrementing the value of the loop counter, the condition is
checked again, i.e., i<5.
If the condition is true, then the inner loop will be executed again.
This process will continue until the condition of the outer loop is true.
SUBJECT NAME
LECTURE COMPANION
SEMESTER:
PREPARED BY:
2
Control Structure
Branching Looping
Conditional Unconditional
 Simple if
 if…else
 Nested if…else
 if…else…if ladder
switch goto break continue
 while
 do…while
 simple for loop
 Nested for loop
if(condition)
{
Block Statements;
}
statement-X;
if(condition1)
{
if(condition2)
{
Block-1 statements;
}
else
{
Block-2 statements;
}
}
else
{
Block-3 statements;
}
Statement-X;
3
if(condition)
{
TRUE-Block
Statements;
}
else
{
FALSE-Block
Statements;
}
statement-X;
if(condition1)
{
Block-1 statements;
}
else if(condition2)
{
Block-2 statements;
}
else if(condition3)
{
Block-3 statements;
}
.
.
else if(condition N)
{
Block-N statements;
}
else
{
Default statement;
}
Statement-X;
If..else..if Ladder
Nested If..else
If..else Statement
Simple if Statement
Syntax : Simple if , else… if , nested if…else, if..else…if Ladder
4
Nested If..else
If..else Statement
Simple if Statement
Flowcharts : Simple if , else… if , nested if…else, if..else…if Ladder
Conditions
Block
Statements
Statement-X
TRUE
FALSE
Conditions
FALSE Block
Statements
Statement-X
TRUE
FALSE
TRUE Block
Statements
Condition-2
Block-1
Statements
Block-2
Statements
Condition-1
Block-3
Statements
Statement-X
FALSE TRUE
TRUE
FALSE
5
Nested If..else
If..else Statement
Simple if Statement
Let us Enter Value : 50
Let us Enter Value : 55
Let us Enter Values : 45, 56 and 89
Examples : Simple if , else… if , nested if…else, if..else…if Ladder
6
Flowchart
if…else…if ladder Example
Condition-2
Condition-1
Condition-N
Default
Statements
Block-N
Statements
Block-2
Statements
Block-1
Statements
Statement-X
FALSE
FALSE
FALSE
TRUE
TRUE
TRUE
Let us Enter Marks : 89
PROGRAMMING FOR PROBLEM
SOLVING
SEMESTER: 1st
PREPARED BY:
CHAPTER 3 TOPIC 1
• INTRODUCTION
• Control Statement
• Simple Statement
• Decision Making Statement
DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY
*Proprietary material of SILVER OAK UNIVERSITY
22-10-2020 2
INTRODUCTION
• In any programming language, there is a
need to perform different tasks based
on the condition.
• For example, consider example of true
and false if your answer is right you will
get 1 point and if answer is wrong you
will get 0.
• Behind process conditional logic
declared in any programming language
it’s called the Control Statement.
DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY
*Proprietary material of SILVER OAK UNIVERSITY
22-10-2020 3
SIMPLE STATEMENT
22-10-2020
DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY
*Proprietary material of SILVER OAK UNIVERSITY
4
Entry
Action 1
Action 2
Action 3
Exit
• Simple statements are used in C or C++ for
unconditional flow of control through out the
functions in a program. They support Three type of
simple statements.
1. Break
2. Continue
3. Goto
DECISION MAKING STATEMENT
22-10-2020
DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY
*Proprietary material of SILVER OAK UNIVERSITY
5
• Decision making structures require that
the programmer specifies one or more
conditions to be evaluated or tested by the
program.
• statements to be executed if the condition
is determined to be true, and optionally,
other statements to be executed if the
condition is determined to be false.
• They support two type of decision
statements.
1. IF….ELSE
2. SWITCH
Action 1 Action 1
Condition
to make
Decision
EXIT
ENTRY
TRUE FALSE
BREAK
22-10-2020
DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY
*Proprietary material of SILVER OAK UNIVERSITY
6
Condition
to break
from loop
Action 1
TRUE
FALSE
Loop body
start
• Break statements are used in the
situations when we are not sure
about the actual number of
iterations for the loop or we want to
terminate the loop based on some
condition.
Syntax :- break;
BREAK EXAMPLE
22-10-2020
DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY
*Proprietary material of SILVER OAK UNIVERSITY
7
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 )
{
printf("value of a: %dn", a);
a++;
if( a > 15)
{
/* terminate the loop using break statement */
break;
}
}
return 0;}
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
CONTINUE
• This loop control statement is just
like the break statement. The
continue statement is opposite to
that of break statement, instead of
terminating the loop, it forces to
execute the next iteration of the
loop.
22-10-2020
DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY
*Proprietary material of SILVER OAK UNIVERSITY
8
Syntax :-
continue;
Condition
to continue
next
iteration
Action 1
TRUE
FALSE
Loop body
start
Execute remaining
part of body loop
#include <stdio.h>
int main ()
{
/* local variable definition
*/
int a = 10;
/* do loop execution */
do {
if( a == 15)
{
22-10-2020
DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY
*Proprietary material of SILVER OAK UNIVERSITY
9
CONTINUE EXAMPLE
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %dn", a);
a++;
}
while( a < 20 );
return 0;}
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
GO TO STATEMENT
22-10-2020
DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY
*Proprietary material of SILVER OAK UNIVERSITY
10
start
Statement 1
Statement 2
Statement 3
Label 1
Label 2
Label 3
start
stop
• The goto statement in C/C++ also
referred to as unconditional jump
statement can be used to jump from
one point to another within a
function.
goto label;
..
.
label: statement;
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do {
if( a == 15)
{
22-10-2020
DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY
*Proprietary material of SILVER OAK UNIVERSITY
11
GO TO EXAMPLE
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %dn", a);
a++;
}while( a < 20 );
return 0;
}
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
22-10-2020
DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY
*Proprietary material of SILVER OAK UNIVERSITY
12
REFERENCE
For Theory
• https://www.geeksforgeeks.org/continue-statement-cpp/?ref=lbp
• https://en.wikibooks.org/wiki/C_Programming/Statements
• https://www.geeksforgeeks.org/break-statement-cc/?ref=lbp
• https://www.tutorialspoint.com/cprogramming/c_decision_making.htm
NPTEL
• https://youtu.be/BZwdn-t_unY
• https://youtu.be/CxkPH74fVBo

Mais conteúdo relacionado

Semelhante a Loop and while Loop

C++ control structure
C++ control structureC++ control structure
C++ control structure
bluejayjunior
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
Amy Nightingale
 

Semelhante a Loop and while Loop (20)

[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
 
C Programming - Decision making, Looping
C  Programming - Decision making, LoopingC  Programming - Decision making, Looping
C Programming - Decision making, Looping
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
Visula C# Programming Lecture 4
Visula C# Programming Lecture 4Visula C# Programming Lecture 4
Visula C# Programming Lecture 4
 
Mesics lecture 7 iteration and repetitive executions
Mesics lecture 7   iteration and repetitive executionsMesics lecture 7   iteration and repetitive executions
Mesics lecture 7 iteration and repetitive executions
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Loops In C++
Loops In C++Loops In C++
Loops In C++
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
 
Loops and iteration.docx
Loops and iteration.docxLoops and iteration.docx
Loops and iteration.docx
 
M C6java6
M C6java6M C6java6
M C6java6
 
Workbook_2_Problem_Solving_and_programming.pdf
Workbook_2_Problem_Solving_and_programming.pdfWorkbook_2_Problem_Solving_and_programming.pdf
Workbook_2_Problem_Solving_and_programming.pdf
 
UNIT 2 PPT.pdf
UNIT 2 PPT.pdfUNIT 2 PPT.pdf
UNIT 2 PPT.pdf
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
 
dizital pods session 5-loops.pptx
dizital pods session 5-loops.pptxdizital pods session 5-loops.pptx
dizital pods session 5-loops.pptx
 

Último

Último (20)

On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 

Loop and while Loop

  • 2. CHAPTER 3 TOPIC 4 • Loops • While loop • Do...while loop • Switch Statement 2
  • 3. WHILE LOOP • A while loop in C programming repeatedly executes a target statement as long as a given condition is true. 3
  • 4. WHILE LOOP • Syntax : While (Test Expression) { // statements inside the body of the loop } 4
  • 5. WHILE LOOP How While loop works : • The while loop evaluates the test expression inside the parenthesis (). • If the test expression is true, statements inside the body of while loop are executed. Then, the test expression is evaluated again. • The process goes on until the test expression is evaluated to false. • If the test expression is false, the loop terminates (ends). 5
  • 6. WHILE LOOP // Print numbers from 1 to 5 #include <stdio.h> int main() { int i = 1; while (i <= 5) { printf("%dn", i); ++i; } return 0; } Here, we have initialized i to 1. • When i is 1, the test expression i <= 5 is true. Hence, the body of the while loop is executed. This prints 1 on the screen and the value of i is increased to 2. • Now, i is 2, the test expression i <= 5 is again true. The body of the while loop is executed again. This prints 2 on the screen and the value of is increased to 3. • This process goes on until i becomes 6. When i is 6, the test expression i<=5 will be false and the loop terminates. 6 Output : 1 2 3 4 5
  • 7. DO...WHILE LOOP • The do..while loop is similar to the while loop with one important difference. • The body of do...while loop is executed at least once. Only then, the test expression is evaluated. 7
  • 8. DO...WHILE LOOP • Syntax : do { // statements inside the body of the loop } while (Test Expression); 8
  • 9. DO...WHILE LOOP How Do...While loop works : • The body of do...while loop is executed once. Only then, the test expression is evaluated. • If the test expression is true, the body of the loop is executed again and the test expression is evaluated. • This process goes on until the test expression becomes false. • If the test expression is false, the loop ends. 9
  • 10. DO...WHILE LOOP // Print numbers from 1 to 5 #include <stdio.h> int main() { int i = 1; do { printf("%dn", i); ++i; } while(i <= 5) ; return 0; } Here, we have initialized i to 1. • As we know that do…while loop is executed at least one time, it will be printed when i=1 and then i increments to 2. • Now, i is 2, the test expression i <= 5 is true. The body of the do…while loop is executed again. This prints 2 on the screen and the value of i is increased to 3. • This process goes on until i becomes 6. When i is 6, the test expression i<=5 will be false and the loop terminates. 10 Output : 1 2 3 4 5
  • 11. SWITCH STATEMENTS • The switch statement allows us to execute one code block among many alternatives. • You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is much easier to read and write. 11
  • 12. SWITCH STATEMENTS • Syntax : switch (expression) { case constant1: // statements break; case constant2: // statements break; . . . default: // default statements } 12
  • 13. SWITCH STATEMENTS How switch case works : • The expression is evaluated once and compared with the values of each case label. • If there is a match, the corresponding statements after the matching label are executed. For example, if the value of the expression is equal to constant2, statements after case constant2: are executed until break is encountered. • If there is no match, the default statements are executed. • If we do not use break, all statements after the matching label are executed. • By the way, the default clause inside the switch statement is optional. 13
  • 14. 14 • In the given program we have initialized a variable x with value 2. • A switch construct is used to compare the value stored in variable x and execute the block of statements associated with the matched case. • In this program, since the value stored in variable x is two, a switch will execute the case whose case-label is 2. After executing the case, the control will fall out of the switch and program will be terminated with the successful result by printing the value on the output screen. // Following is a simple C program to demonstrate syntax of switch. #include <stdio.h> int main() { int x = 2; switch (x) { case 1: printf("Choice is 1"); break; case 2: printf("Choice is 2"); break; case 3: printf("Choice is 3"); break; default: printf("Choice other than 1, 2 and 3"); break; } return 0; }
  • 15. PROGRAMMING FOR PROBLEM SOLVING UNIT – 3 CONTROL STRUCTURE SEMESTER: 1st PREPARED BY: Prof. Brijesh Hansaliya
  • 16. FOR LOOP • Loop Concept Loop is a repetition for series of actions and activities. In programming sometimes we need to repeat block or statement for some period. Loop is helping to repeat particular block or set of statements for particular time period. When to stop looping? In chart , action is executed over and over again. It never stop – This is called an Infinite Loop Solution – Put a condition to tell the loop either to continue or stop 2 An actions and activities or series of actions and activities
  • 17. CONTINUE… Main part of loop : Body and Condition Body : Statement or Block of statements that will be repeated. Condition : It is used to control iteration either to continue or stop the iteration. 3 Body Of Loop Condi tion True False
  • 18. PRE-TEST LOOP Condition is tested First before start executing the body. Body of the loop will executed if the condition is true. If condition becomes false loop will terminate. After executing body again condition is tested. 4 Body Of Loop Condi tion False Pre-test Loop (FOR LOOP) True Stop
  • 19. FOR LOOP The for loop in C language is used to repeat the statements or a block of the program several times. The syntax of for loop in c language is given below: for( Initialization ; Condition ; Increment or Decrement ) { Statement block to be executed ; } Loop Execution : Step 1: First initialization happens and the counter variable gets initialized. Execute only One time. Step 2: In the second step the condition is checked, if the condition is true then the C statements inside the body of for loop gets executed, if the condition is false then the for loop gets terminated. Step 3: After successful execution of statements inside the body of loop, the counter variable is incremented or decremented, depending on the operation (++ or –-). 5 Initialization Condition Statement Incr / Decr True False Stop FOR Loop Flow Chart
  • 20. WHILE LOOP for ( ) FOR LOOP COMPARING FOR AND WHILE 6 Initialize While (Expression) { } /* While */ action action update counter Initialize; Condition; Increment or Decrement; { } /* For */ action action action Continue… Continue…
  • 21. FOR LOOP EXAMPLE 1 // Print numbers from 1 to 10 #include <stdio.h> int main() { int i; for (i = 1; i < 11; ++i) { printf("%d ", i); } return 0; } O / P : 1 2 3 4 5 6 7 8 9 10 7 1. i is initialized to 1. 2. The test expression i < 11 is evaluated. Since 1 less than 11 is true, the body of for loop is executed. This will print the 1 (value of i) on the screen. 3. The update statement ++i is executed. Now, the value of i will be 2. Again, the test expression is evaluated to true, and the body of for loop is executed. This will print 2 (value of i) on the screen. 4. Again, the update statement ++i is executed and the test expression i < 11 is evaluated. This process goes on until i becomes 11. 5. When i becomes 11, i < 11 will be false, and the for loop terminates.
  • 22. FOR LOOP EXAMPLE 2 #include <stdio.h> int main() { int num, count, sum = 0; printf("Enter a positive integer: "); scanf("%d", &num); for(count = 1; count <= num; ++count) { sum += count; } printf("Sum = %d", sum); return 0; } O/P : Enter a positive integer: 5 Sum = 15 8 The value entered by the user is stored in the variable num. Suppose, the user entered 5. The count is initialized to 1 and the test expression is evaluated. Since the test expression count<=num (1 less than or equal to 5) is true, the body of for loop is executed and the value of sum will equal to 1. Then, the update statement ++count is executed and the count will equal to 2. Again, the test expression is evaluated. Since 2 is also less than 5, the test expression is evaluated to true and the body of for loop is executed. Now, the sum will equal 3. This process goes on and the sum is calculated until the count reaches 6. When the count is 6, the test expression is evaluated to false, and the loop terminates. Then, the value of sum is printed on the screen.
  • 23. VARIOUS FORMS OF FOR LOOP IN C Suppose we are using variable num as the counter in all the following examples – 1) Here instead of num++, I’m using num=num+1 which is same as num++. for (num=10; num<20; num=num+1) 2) Initialization part can be skipped from loop as shown below, the counter variable is declared before the loop. int num=10; for ( ; num<20;num++) Note: Even though we can skip initialization part but semicolon (;) before condition is must, without which you will get compilation error. 3) Like initialization, you can also skip the increment part as we did below. In this case semicolon (;) is must after condition logic. In this case the increment or decrement part is done inside the loop. for (num=10; num<20; ) { //Statements num++; } 9
  • 24. CONTINUE…. 4) This is also possible. The counter variable is initialized before the loop and incremented inside the loop. int num=10; for (;num<20;) { //Statements num++; } 5) As mentioned above, the counter variable can be decremented as well. In the below example the variable gets decremented each time the loop runs until the condition num>10 returns false. for(num=20; num>10; num--) 10
  • 25. NESTED LOOPS IN C • C supports nesting of loops. Nesting of loops is the feature that allows the looping of statements inside another loop. • Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. Syntax for Nested Looping : Outer_loop { Inner_loop { // inner loop statements. } // outer loop statements. } 11
  • 26. NESTED FOR LOOP The nested for loop means for loop which is defined inside the another 'for' loop. for (initialization; condition; increment or decrement) { for(initialization; condition; increment or decrement) { // inner loop statements. } // outer loop statements. } 12 Nested For loop Flow Chart :
  • 27. NESTED FOR LOOP EXAMPLE #include <stdio.h> int main(void) { int i,j; for(i=0;i<5;i++) { for(j=0;j<=i;j++) { printf(" *"); } printf("n"); } return 0; } O/P : * * * * * * * * * * * * * * * 13 First, the 'i' variable is initialized to 1 and then program control passes to the i<5. The program control checks whether the condition 'i<5' is true or not. If the condition is true, then the program control passes to the inner loop. The inner loop will get executed until the condition is true. After the execution of the inner loop, the control moves back to the update of the outer loop, i.e., i++. After incrementing the value of the loop counter, the condition is checked again, i.e., i<5. If the condition is true, then the inner loop will be executed again. This process will continue until the condition of the outer loop is true.
  • 29. 2 Control Structure Branching Looping Conditional Unconditional  Simple if  if…else  Nested if…else  if…else…if ladder switch goto break continue  while  do…while  simple for loop  Nested for loop
  • 30. if(condition) { Block Statements; } statement-X; if(condition1) { if(condition2) { Block-1 statements; } else { Block-2 statements; } } else { Block-3 statements; } Statement-X; 3 if(condition) { TRUE-Block Statements; } else { FALSE-Block Statements; } statement-X; if(condition1) { Block-1 statements; } else if(condition2) { Block-2 statements; } else if(condition3) { Block-3 statements; } . . else if(condition N) { Block-N statements; } else { Default statement; } Statement-X; If..else..if Ladder Nested If..else If..else Statement Simple if Statement Syntax : Simple if , else… if , nested if…else, if..else…if Ladder
  • 31. 4 Nested If..else If..else Statement Simple if Statement Flowcharts : Simple if , else… if , nested if…else, if..else…if Ladder Conditions Block Statements Statement-X TRUE FALSE Conditions FALSE Block Statements Statement-X TRUE FALSE TRUE Block Statements Condition-2 Block-1 Statements Block-2 Statements Condition-1 Block-3 Statements Statement-X FALSE TRUE TRUE FALSE
  • 32. 5 Nested If..else If..else Statement Simple if Statement Let us Enter Value : 50 Let us Enter Value : 55 Let us Enter Values : 45, 56 and 89 Examples : Simple if , else… if , nested if…else, if..else…if Ladder
  • 35. CHAPTER 3 TOPIC 1 • INTRODUCTION • Control Statement • Simple Statement • Decision Making Statement DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY *Proprietary material of SILVER OAK UNIVERSITY 22-10-2020 2
  • 36. INTRODUCTION • In any programming language, there is a need to perform different tasks based on the condition. • For example, consider example of true and false if your answer is right you will get 1 point and if answer is wrong you will get 0. • Behind process conditional logic declared in any programming language it’s called the Control Statement. DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY *Proprietary material of SILVER OAK UNIVERSITY 22-10-2020 3
  • 37. SIMPLE STATEMENT 22-10-2020 DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY *Proprietary material of SILVER OAK UNIVERSITY 4 Entry Action 1 Action 2 Action 3 Exit • Simple statements are used in C or C++ for unconditional flow of control through out the functions in a program. They support Three type of simple statements. 1. Break 2. Continue 3. Goto
  • 38. DECISION MAKING STATEMENT 22-10-2020 DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY *Proprietary material of SILVER OAK UNIVERSITY 5 • Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program. • statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. • They support two type of decision statements. 1. IF….ELSE 2. SWITCH Action 1 Action 1 Condition to make Decision EXIT ENTRY TRUE FALSE
  • 39. BREAK 22-10-2020 DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY *Proprietary material of SILVER OAK UNIVERSITY 6 Condition to break from loop Action 1 TRUE FALSE Loop body start • Break statements are used in the situations when we are not sure about the actual number of iterations for the loop or we want to terminate the loop based on some condition. Syntax :- break;
  • 40. BREAK EXAMPLE 22-10-2020 DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY *Proprietary material of SILVER OAK UNIVERSITY 7 #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) { printf("value of a: %dn", a); a++; if( a > 15) { /* terminate the loop using break statement */ break; } } return 0;} Output value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15
  • 41. CONTINUE • This loop control statement is just like the break statement. The continue statement is opposite to that of break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. 22-10-2020 DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY *Proprietary material of SILVER OAK UNIVERSITY 8 Syntax :- continue; Condition to continue next iteration Action 1 TRUE FALSE Loop body start Execute remaining part of body loop
  • 42. #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* do loop execution */ do { if( a == 15) { 22-10-2020 DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY *Proprietary material of SILVER OAK UNIVERSITY 9 CONTINUE EXAMPLE /* skip the iteration */ a = a + 1; continue; } printf("value of a: %dn", a); a++; } while( a < 20 ); return 0;} Output value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19
  • 43. GO TO STATEMENT 22-10-2020 DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY *Proprietary material of SILVER OAK UNIVERSITY 10 start Statement 1 Statement 2 Statement 3 Label 1 Label 2 Label 3 start stop • The goto statement in C/C++ also referred to as unconditional jump statement can be used to jump from one point to another within a function. goto label; .. . label: statement;
  • 44. #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* do loop execution */ LOOP:do { if( a == 15) { 22-10-2020 DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY *Proprietary material of SILVER OAK UNIVERSITY 11 GO TO EXAMPLE /* skip the iteration */ a = a + 1; goto LOOP; } printf("value of a: %dn", a); a++; }while( a < 20 ); return 0; } Output value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19
  • 45. 22-10-2020 DEPARTMENT OF COMPUTER ENGINEERING & INFORMATION TECHNOLOGY *Proprietary material of SILVER OAK UNIVERSITY 12 REFERENCE For Theory • https://www.geeksforgeeks.org/continue-statement-cpp/?ref=lbp • https://en.wikibooks.org/wiki/C_Programming/Statements • https://www.geeksforgeeks.org/break-statement-cc/?ref=lbp • https://www.tutorialspoint.com/cprogramming/c_decision_making.htm NPTEL • https://youtu.be/BZwdn-t_unY • https://youtu.be/CxkPH74fVBo