SlideShare une entreprise Scribd logo
1  sur  47
Télécharger pour lire hors ligne
Loop
Session Objective
• To learn about different types of Control
Statements
Session Topics
• Repetition or Iteration structure - for statement,
continue statement, nested loop, while loop
C Control Structure Looping
n - tim es
w hile do-w hile for
n - tim es
Operators (contd…)
• A unary operator has one operand
– Post and Pre increment and decrement
• a++,b--,++a,--b
» a = a++;
• A binary operator has two operands
• a = b+c
• A ternary operator has three operands
• boolean-expr ? expression-1 : expression-2
The ternary operator
• boolean-expr ? expression-1 : expression-2
• This is like if-then-else for values rather than for
statements
• If the boolean-expr evaluates to true, the result is
expression-1, else it is expression-2
• Example: max = a > b ? a : b ; sets the variable max
6
• Example: max = a > b ? a : b ; sets the variable max
to the larger of a and b
• expression-1 and expression-2 need not be the same
type, but either result must be useable (not a “void”
function)
• The ternary operator is right associative!
– To avoid confusion, use parentheses if your expression has
more than one ternary operator
– AKA unary operators
– The increment operator ++ adds 1 to its
operand, and the decrement operator - -
subtracts 1.
– If either is used as a prefix operator, the
expression increments or decrements the
Increment and Decrement Operators
expression increments or decrements the
operand before its value is used.
– If either is used as a postfix operator, the
increment and decrement operation will
be performed after its value has been
used.
main( )
{
int a=5;
printf("a=%d”,a++);
}
main()
{
int a=5;
printf("a=%d",++a);
}
main()
{
int a=5;
printf("a=%d",a++);
main()
{
int a=5;
printf("a=%d“,a--);
}
main()
{
int a=5;
printf("a=%d”,--a);
}
main()
{
int a=5;
printf("a=%d a=%d",a,++a,a++);
printf("a=%d",a++);
printf("a=%d",++a);
printf("a=%d",a++);
}main( )
{
int a=5;
printf("a=%d",a--);
printf("a=%d“,--a);
printf("a=%d",a--);
}
printf("a=%d a=%d",a,++a,a++);
}
The while Statement
• Structure
while(expression)
statement;
or
while(expression)
{
statement_1;
statement_2;
The while Statement
Example
while (a < b)
{
printf("%dn",
a);
a = a + 1;statement_2;
}
a = a + 1;
}
* Operation: expression is evaluated and if TRUE then
statement (or statement_1 and statement_2) is executed.
The evaluation and executions sequence is repeated until
the expression evaluates to be FALSE. If the expression is
initially FALSE then statement is not executed at all.
Flowchart of a while Loop
• The syntax of a while
loop is as follows:
while(expression)while(expression)
statement
Understanding a while loop
b=1;
While(b<2)
{
blah
blah
When the computer reaches while
statement, it tests to see if the
Boolean expression is true. If true, it
jumps into the block of codeblah
b=b+1;
}
blah
blah
jumps into the block of code
immediately below the while
statement.
Understanding a while loop
b=1;
While(b<2)
{
blah
When the computer reaches last
line in the while loop’s block of
code, it jumps back up to the
blah
b=b+1;
}
blah
blah
while statement. It re-tests the
Boolean expression. If still true,
it enters the block of code
again.
Understanding a while loop
b=1;
While(b<2)
{
blah
blah
When the Boolean expression
becomes false , the computer skips
the while loop statement’s block of
code and continues with theblah
b=b+1;
}
blah
blah
code and continues with the
remainder of the program.
Looping: A Real Example
• Let's say that you would like to create a program that
prints a Fahrenheit-to-Celsius conversion table. This is
easily accomplished with a for loop or a while loop:
main()
{
int a;
a = 0;a = 0;
while (a <= 100)
{
printf(“%d degrees F = %d degrees Cn", a, (a - 32)
* 5 / 9);
a = a + 10;
}
}
Example:
int i = 0;
while(i < 5){
printf(“%d “,i);
i++;
0 1 2 3 4
i++;
}
Output:
main( )
{
int i = 1,sum=0;
while(i <=100 ){
sum=sum+i;
printf(“Sum=%d t &
i=%dn”,sum,i++);
}}
main( )
{
int i = 100,sum=0;
while(i >=1 ){
sum=sum+i;
printf(“Sum=%d t &
i=%dn”,sum,i--);
}}
main( )main( )
{
int i = 100,sum=0;
while(i >=1 ){
sum=sum+i;
printf(“Sum=%d t &
i=%dn”,sum,i=i-
5);
}}
main( )
{
int i = 1,sum=0;
while(i <=100 ){
sum=sum+i;
printf(“Sum=%d t &
i=%dn”,sum,i=i+5
);
}}
main( )
{
int i = 1,sum=0;
while(i <=100 ){
if(i%2==0)
{
sum=sum+i;
}
printf(“Sum=%d t &
main( )
{
int i = 1,sum=0;
while(i <=100 ){
if(i%2==1)
{
sum=sum+i;
}
printf(“Sum=%d t &printf(“Sum=%d t &
i=%dn”,sum,i++);
}
}
printf(“Sum=%d t &
i=%dn”,sum,i++);
}
}
Solve same problem using decrement(- -
)operator
main( )
{
int i = 1,sum=0;
while(i <=100 ){
if(i%2==0 &&
i%5==0)
{
sum=sum+i;
}
main( )
{
int i = 100,sum=0;
while(i >=1){
if(i%2==0 && i%5==0 &&
i%10==0)
{
sum=sum+i;
printf("Sum=%d t & i=%dn",sum,i);}
printf(“Sum=%d t &
i=%dn”,sum,i++);
}
}
printf("Sum=%d t & i=%dn",sum,i);
}//bracket for if
i=i-1;
}//bracket for while
}//bracket for main
Example:
Calculating a factorial 5!. The factorial n! is defined as n*(n-1)!
main() {
/* declaration */
int i, f, n;
/* initialization */
i = 1;
f = 1;
/* processing */
printf(“Please input a numbern”);
scanf(“%d”, &n);
while (i <= n) {
f *= i;
i++;
}
/* termination */
printf(“factorial %d! = %dn", n, f);
}
5
factorial 5! = 120
Control of Repetition
• Counter-controlled repetition
• Sentinel-controlled repetition• Sentinel-controlled repetition
Example:
Counter-controlled repetition
• Loop repeated until counter reaches a certain value.
• Definite repetition: number of repetitions is known
A student takes four courses in a quarter.A student takes four courses in a quarter.
Each course will be assigned a grade with the
score from 0 to 4.
Develop a C program to calculate the grade
point average (GPA) for the quarter.
The flowchart for
program gpa.c
#define NUM 4
main() {
int count;
double grade, total, gpa;
count = 0;
total = 0;
/* processing */
while(count < NUM) {
printf("Enter a grade: ");
scanf("%lf", &grade);
total += grade;
Enter a grade: 4
Enter a grade: 3.7
Enter a grade: 3.3
Execution and Output:
Macro
NUM ≡ 4
total += grade;
count++;
}
/* termination */
gpa = total/NUM;
printf("The GPA is: %fn",
gpa);
}
Enter a grade: 4
The GPA is:
3.750000
Sentinel-controlled repetition
• Loop repeated until the sentinel (signal) value is
entered.
• Indefinite repetition: number of repetitions is
unknown when the loop begins execution.
Example:
Develop a GPA calculation program that will process
grades with scores in the range of [0, 4] for an
arbitrary number of courses.
#define SENTINELNUM -1
#define HIGHESTMARK 4
main() {
int count;
double grade, total, gpa;
/* initialization */
count = 0;
total = 0;
printf("Enter a grade [0, %d] or %d to end: ",
HIGHESTMARK, SENTINELNUM);
scanf("%lf", &grade);
while((int)grade != SENTINELNUM) {
if(0 <= grade && grade <= HIGHESTMARK) {
total += grade;
count++;
}
else {
printf("Invalid grade %cn", 'a');
}
printf("Enter a grade [0, %d] or %d to end: ",
HIGHESTMARK, SENTINELNUM);
scanf("%lf", &grade);
}
/* termination */
if(count != 0) {
gpa = total/count;
printf("The GPA is: %fn",
gpa);
}
else
printf("No grade entered.n");
}
Execution and
Output:
Enter a grade [0, 4] or -1 to end: 4
Enter a grade [0, 4] or -1 to end: 3.7
Enter a grade [0, 4] or -1 to end: 3.3
Enter a grade [0, 4] or -1 to end: 4
Enter a grade [0, 4] or -1 to end: 10
Invalid grade
Enter a grade [0, 4] or -1 to end: 3.7
Enter a grade [0, 4] or -1 to end: -1
The GPA is: 3.740000
• do-while Loop
– The syntax of a do-while statement is as
follows:
do
statement
– The evaluation of the controlling
expression takes place after each
execution of the loop body.
– The loop body is executed repeatedly
until the return value of the controlling
expression is equal to 0.
while(expression);
The do-while Statement
• Structure
do
{
statement;
} while(expression);
do {
printf("%dn", a);
a = a + 1;
} while (a < b);
• Operation: Similar to the while control except that
statement is executed before the expression is evaluated.
This guarantees that statement is always executed at
least one time even if expression is FALSE.
Flowchart of a do-while loop
• The syntax of a do-while
statement is as follows:
do
statementstatement
while(expression);
Example:
int i = 0;
do {
printf(“%d ”, i);
i++;i++;
} while(i < 5);
Output:
0 1 2 3 4
– What is the output of the following example?
Example:
int i = 10;
do {
printf(“%d ”, i);
i++;
} while(i < 5);
Output:
10
The for Statement
• Structure: for(expr1; expr2; expr3)
{
statement;
}
• Operation: The for loop in C is simply a shorthand way of
expressing a while statement:
expr1;expr1;
while(expr2)
{
statement;
expr3
}
• The comma operator lets you separate several different
statements in the initialization and increment sections of the
for loop (but not in the test section).
C Errors to Avoid
• Putting = when you mean == in an if or while statement
• Forgetting to increment the counter inside the while loop - If
you forget to increment the counter, you get an infinite loop
(the loop never ends).
• Accidentally putting a ; at the end of a for loop or if
statement so that the statement has no effect - For
example:
for (x=1; x<10; x++);
printf("%dn",x);
only prints out one value because the semicolon after the
for statement acts as the one line the for loop executes.
• For Loop
– The syntax of a for statement is as follows:
for(expression1; expression2; expression3)
statement
– The expression expression1 is evaluated as a void
expression before the first evaluation of the controlling
expression.expression.
– The expression expression2 is the controlling expression
that is evaluated before each execution of the loop
body.
– The expression expression3 is evaluated as a void
expression after each execution of the loop body.
– Both expression1 and expression3 can be omitted. An
omitted expression2 is replaced by a nonzero constant.
–The for-loop is semantically equivalent
to the following while-loop:
expression1;
while(expression2)
{
statement
expression3;
}
Flowchart of a for Loop
The syntax of a for loop is as follows:
for(expression1; expression2; expression3)
statement
Example:
int i;
for(i = 0; i < 5; i++)
{
printf(“%d ”, i);
}
0 1 2 3 4
Output:
Example:
Calculating a factorial 5!. The factorial n! is defined as n*(n-1)!
main() {
int i, f, n;
printf(“Please input a numbern”);
scanf(“%d”, &n);
for(i=1, f=1; i<=n; i++)
{
f = f*i;f = f*i;
}
printf(“factorial %d! = %dn", n, f);
}
Execution and Output:
5
factorial 5! = 120
int i;
for(i=0; i<5; i++)
{
Jump Statements
• Break Statements
– The break statement provides an early exit from the for, while,
do-while, and for each loops as well as switch statement.
– A break causes the innermost enclosing loop or switch to be
exited immediately.
Example:
{
if(i == 3)
{
break;
}
printf("%d", i);
}
Output :0 1 2
int i;
• Continue Statements
– The continue statement causes the next iteration
of the enclosing for, while and do-while loop
to begin.
– A continue statement should only appear in a loop
body.
int i;
for(i=0; i<5; i++)
{
if(i == 3)
{
continue;
}
printf("%d", i);
}
Output : 0 1 2 4
Nested Loop
Nested loop = loop inside loop
Program flow
The inner loops must beThe inner loops must be
finished before the outer loop resumes iteration.
Write a program to print a multiplication table.
1 2 3 4 5 6 7 8 9 10
------------------------------------------
1| 1
2| 2 4
3| 3 6 9
4| 4 8 12 16
5| 5 10 15 20 255| 5 10 15 20 25
6| 6 12 18 24 30 36
7| 7 14 21 28 35 42 49
8| 8 16 24 32 40 48 56 64
9| 9 18 27 36 45 54 63 72 81
10| 10 20 30 40 50 60 70 80 90 100
------------------------------------------
Example: A program to print a multiplication table.
main()
{
int i, j;
printf("1 2 3 4 5 6 7 8 9 10n");
printf("-------------------------------------n");
for(i=1; i<= 10; i++)
{ /* outer loop */
printf("%d ", i);printf("%d ", i);
for(j=1; j<=i; j++)
{ /* inner loop */
printf("%d ", i*j);
}
printf("n");
}
printf("------------------------------------n");
}
Solve all problem using while,do – while and for
• WAP to find sum of ten numbers.
• WAP to display all numbers between 1 to 1000 that are perfectly
divisible by 10.
• WAP to display all numbers between 2000 to 100 that are perfectly
divisible by 13 and 15 and 17 and 19.
• WAP to find sum of all numbers between 500 to 1500 that are perfectly
divisible by 3 and 5 and 15 and 45.
• WAP to find sum of all numbers between 10000 to 1000 that are• WAP to find sum of all numbers between 10000 to 1000 that are
perfectly divisible by 3 and 7 and 9 and 42.
• WAP to find factorial of given number
– N! = N * (N-1)!
• WAP to check whether a given number is prime or not.
– A number is prime if it is divisible by 1 and the number itself only
• WAP to generate all prime numbers between 100 to 1.
• WAP to generate multiplication table of any given number
• WAP to generate multiplication table of number 1 to 5.
• WAP to check whether a given program in Armstrong or
not.
– 153 is a Armstrong number because 13+53+33=153
• WAP to check whether a number is strong or not.
– 145 is a strong number because 1! + 4! +5 ! = 145
• WAP to check whether a number is perfect or not.
– 28 is a perfect number because 1+2+4+7+14 = 28
• WAP to find GCD (HCF) of given two numbers.
• WAP to find LCM of given numbers.

Contenu connexe

Tendances

Chapter 5 exercises Balagurusamy Programming ANSI in c
Chapter 5 exercises Balagurusamy Programming ANSI  in cChapter 5 exercises Balagurusamy Programming ANSI  in c
Chapter 5 exercises Balagurusamy Programming ANSI in cBUBT
 
C programs
C programsC programs
C programsMinu S
 
Chapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CChapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CBUBT
 
Chapter 2 : Balagurusamy_ Programming ANsI in C
Chapter 2 :  Balagurusamy_ Programming ANsI in CChapter 2 :  Balagurusamy_ Programming ANsI in C
Chapter 2 : Balagurusamy_ Programming ANsI in CBUBT
 
Program flowchart
Program flowchartProgram flowchart
Program flowchartSowri Rajan
 
Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C BUBT
 
LET US C (5th EDITION) CHAPTER 2 ANSWERS
LET US C (5th EDITION) CHAPTER 2 ANSWERSLET US C (5th EDITION) CHAPTER 2 ANSWERS
LET US C (5th EDITION) CHAPTER 2 ANSWERSKavyaSharma65
 
Decisions in C or If condition
Decisions in C or If conditionDecisions in C or If condition
Decisions in C or If conditionyarkhosh
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given numberMainak Sasmal
 
LET US C (5th EDITION) CHAPTER 1 ANSWERS
LET US C (5th EDITION) CHAPTER 1 ANSWERSLET US C (5th EDITION) CHAPTER 1 ANSWERS
LET US C (5th EDITION) CHAPTER 1 ANSWERSKavyaSharma65
 
programs of c www.eakanchha.com
 programs of c www.eakanchha.com programs of c www.eakanchha.com
programs of c www.eakanchha.comAkanchha Agrawal
 
6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumping6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumpingMomenMostafa
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solutionAzhar Javed
 
Let us C (by yashvant Kanetkar) chapter 3 Solution
Let us C   (by yashvant Kanetkar) chapter 3 SolutionLet us C   (by yashvant Kanetkar) chapter 3 Solution
Let us C (by yashvant Kanetkar) chapter 3 SolutionHazrat Bilal
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solutionKuntal Bhowmick
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given numberMainak Sasmal
 

Tendances (20)

Chapter 5 exercises Balagurusamy Programming ANSI in c
Chapter 5 exercises Balagurusamy Programming ANSI  in cChapter 5 exercises Balagurusamy Programming ANSI  in c
Chapter 5 exercises Balagurusamy Programming ANSI in c
 
C programs
C programsC programs
C programs
 
Chapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in CChapter 4 : Balagurusamy Programming ANSI in C
Chapter 4 : Balagurusamy Programming ANSI in C
 
Chapter 2 : Balagurusamy_ Programming ANsI in C
Chapter 2 :  Balagurusamy_ Programming ANsI in CChapter 2 :  Balagurusamy_ Programming ANsI in C
Chapter 2 : Balagurusamy_ Programming ANsI in C
 
Program flowchart
Program flowchartProgram flowchart
Program flowchart
 
Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C
 
LET US C (5th EDITION) CHAPTER 2 ANSWERS
LET US C (5th EDITION) CHAPTER 2 ANSWERSLET US C (5th EDITION) CHAPTER 2 ANSWERS
LET US C (5th EDITION) CHAPTER 2 ANSWERS
 
Decisions in C or If condition
Decisions in C or If conditionDecisions in C or If condition
Decisions in C or If condition
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
LET US C (5th EDITION) CHAPTER 1 ANSWERS
LET US C (5th EDITION) CHAPTER 1 ANSWERSLET US C (5th EDITION) CHAPTER 1 ANSWERS
LET US C (5th EDITION) CHAPTER 1 ANSWERS
 
programs of c www.eakanchha.com
 programs of c www.eakanchha.com programs of c www.eakanchha.com
programs of c www.eakanchha.com
 
6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumping6 c control statements branching &amp; jumping
6 c control statements branching &amp; jumping
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solution
 
C lab-programs
C lab-programsC lab-programs
C lab-programs
 
Let us C (by yashvant Kanetkar) chapter 3 Solution
Let us C   (by yashvant Kanetkar) chapter 3 SolutionLet us C   (by yashvant Kanetkar) chapter 3 Solution
Let us C (by yashvant Kanetkar) chapter 3 Solution
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solution
 
C important questions
C important questionsC important questions
C important questions
 
Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
 
C Programming
C ProgrammingC Programming
C Programming
 

Similaire à Looping

COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops Hemantha Kulathilake
 
Control structure of c
Control structure of cControl structure of c
Control structure of cKomal Kotak
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02Suhail Akraam
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about CYi-Hsiu Hsu
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in Csana shaikh
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)yap_raiza
 
C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptxDEEPAK948083
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02CIMAP
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.comGreen Ecosystem
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptxeaglesniper008
 
Loop control structure
Loop control structureLoop control structure
Loop control structureKaran Pandey
 

Similaire à Looping (20)

COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
 
SPL 8 | Loop Statements in C
SPL 8 | Loop Statements in CSPL 8 | Loop Statements in C
SPL 8 | Loop Statements in C
 
Introduction to c part -1
Introduction to c   part -1Introduction to c   part -1
Introduction to c part -1
 
Loops in c
Loops in cLoops in c
Loops in c
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about C
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
What is c
What is cWhat is c
What is c
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
 
Control statments in c
Control statments in cControl statments in c
Control statments in c
 
C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptx
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
 
Session 3
Session 3Session 3
Session 3
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
 
computer programming Control Statements.pptx
computer programming Control Statements.pptxcomputer programming Control Statements.pptx
computer programming Control Statements.pptx
 
Loop control structure
Loop control structureLoop control structure
Loop control structure
 

Plus de Kathmandu University (8)

Storage class
Storage classStorage class
Storage class
 
Pointers [compatibility mode]
Pointers [compatibility mode]Pointers [compatibility mode]
Pointers [compatibility mode]
 
L7 pointers
L7 pointersL7 pointers
L7 pointers
 
structure
structurestructure
structure
 
Array
ArrayArray
Array
 
Function
Function Function
Function
 
control statement
control statement control statement
control statement
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 

Dernier

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.pptxDr. Sarita Anand
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
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)Jisc
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
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.pptxDenish Jangid
 
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.pdfNirmal Dwivedi
 
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 17Celine George
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
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.docxRamakrishna Reddy Bijjam
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 

Dernier (20)

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
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 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)
Jamworks pilot and AI at Jisc (20/03/2024)
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).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
 
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
 
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
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
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
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 

Looping

  • 2. Session Objective • To learn about different types of Control Statements
  • 3. Session Topics • Repetition or Iteration structure - for statement, continue statement, nested loop, while loop
  • 4. C Control Structure Looping n - tim es w hile do-w hile for n - tim es
  • 5. Operators (contd…) • A unary operator has one operand – Post and Pre increment and decrement • a++,b--,++a,--b » a = a++; • A binary operator has two operands • a = b+c • A ternary operator has three operands • boolean-expr ? expression-1 : expression-2
  • 6. The ternary operator • boolean-expr ? expression-1 : expression-2 • This is like if-then-else for values rather than for statements • If the boolean-expr evaluates to true, the result is expression-1, else it is expression-2 • Example: max = a > b ? a : b ; sets the variable max 6 • Example: max = a > b ? a : b ; sets the variable max to the larger of a and b • expression-1 and expression-2 need not be the same type, but either result must be useable (not a “void” function) • The ternary operator is right associative! – To avoid confusion, use parentheses if your expression has more than one ternary operator
  • 7. – AKA unary operators – The increment operator ++ adds 1 to its operand, and the decrement operator - - subtracts 1. – If either is used as a prefix operator, the expression increments or decrements the Increment and Decrement Operators expression increments or decrements the operand before its value is used. – If either is used as a postfix operator, the increment and decrement operation will be performed after its value has been used.
  • 8. main( ) { int a=5; printf("a=%d”,a++); } main() { int a=5; printf("a=%d",++a); } main() { int a=5; printf("a=%d",a++); main() { int a=5; printf("a=%d“,a--); } main() { int a=5; printf("a=%d”,--a); } main() { int a=5; printf("a=%d a=%d",a,++a,a++); printf("a=%d",a++); printf("a=%d",++a); printf("a=%d",a++); }main( ) { int a=5; printf("a=%d",a--); printf("a=%d“,--a); printf("a=%d",a--); } printf("a=%d a=%d",a,++a,a++); }
  • 9. The while Statement • Structure while(expression) statement; or while(expression) { statement_1; statement_2; The while Statement Example while (a < b) { printf("%dn", a); a = a + 1;statement_2; } a = a + 1; } * Operation: expression is evaluated and if TRUE then statement (or statement_1 and statement_2) is executed. The evaluation and executions sequence is repeated until the expression evaluates to be FALSE. If the expression is initially FALSE then statement is not executed at all.
  • 10. Flowchart of a while Loop • The syntax of a while loop is as follows: while(expression)while(expression) statement
  • 11. Understanding a while loop b=1; While(b<2) { blah blah When the computer reaches while statement, it tests to see if the Boolean expression is true. If true, it jumps into the block of codeblah b=b+1; } blah blah jumps into the block of code immediately below the while statement.
  • 12. Understanding a while loop b=1; While(b<2) { blah When the computer reaches last line in the while loop’s block of code, it jumps back up to the blah b=b+1; } blah blah while statement. It re-tests the Boolean expression. If still true, it enters the block of code again.
  • 13. Understanding a while loop b=1; While(b<2) { blah blah When the Boolean expression becomes false , the computer skips the while loop statement’s block of code and continues with theblah b=b+1; } blah blah code and continues with the remainder of the program.
  • 14. Looping: A Real Example • Let's say that you would like to create a program that prints a Fahrenheit-to-Celsius conversion table. This is easily accomplished with a for loop or a while loop: main() { int a; a = 0;a = 0; while (a <= 100) { printf(“%d degrees F = %d degrees Cn", a, (a - 32) * 5 / 9); a = a + 10; } }
  • 15. Example: int i = 0; while(i < 5){ printf(“%d “,i); i++; 0 1 2 3 4 i++; } Output:
  • 16. main( ) { int i = 1,sum=0; while(i <=100 ){ sum=sum+i; printf(“Sum=%d t & i=%dn”,sum,i++); }} main( ) { int i = 100,sum=0; while(i >=1 ){ sum=sum+i; printf(“Sum=%d t & i=%dn”,sum,i--); }} main( )main( ) { int i = 100,sum=0; while(i >=1 ){ sum=sum+i; printf(“Sum=%d t & i=%dn”,sum,i=i- 5); }} main( ) { int i = 1,sum=0; while(i <=100 ){ sum=sum+i; printf(“Sum=%d t & i=%dn”,sum,i=i+5 ); }}
  • 17. main( ) { int i = 1,sum=0; while(i <=100 ){ if(i%2==0) { sum=sum+i; } printf(“Sum=%d t & main( ) { int i = 1,sum=0; while(i <=100 ){ if(i%2==1) { sum=sum+i; } printf(“Sum=%d t &printf(“Sum=%d t & i=%dn”,sum,i++); } } printf(“Sum=%d t & i=%dn”,sum,i++); } } Solve same problem using decrement(- - )operator
  • 18. main( ) { int i = 1,sum=0; while(i <=100 ){ if(i%2==0 && i%5==0) { sum=sum+i; } main( ) { int i = 100,sum=0; while(i >=1){ if(i%2==0 && i%5==0 && i%10==0) { sum=sum+i; printf("Sum=%d t & i=%dn",sum,i);} printf(“Sum=%d t & i=%dn”,sum,i++); } } printf("Sum=%d t & i=%dn",sum,i); }//bracket for if i=i-1; }//bracket for while }//bracket for main
  • 19. Example: Calculating a factorial 5!. The factorial n! is defined as n*(n-1)! main() { /* declaration */ int i, f, n; /* initialization */ i = 1; f = 1; /* processing */ printf(“Please input a numbern”); scanf(“%d”, &n); while (i <= n) { f *= i; i++; } /* termination */ printf(“factorial %d! = %dn", n, f); } 5 factorial 5! = 120
  • 20.
  • 21. Control of Repetition • Counter-controlled repetition • Sentinel-controlled repetition• Sentinel-controlled repetition
  • 22. Example: Counter-controlled repetition • Loop repeated until counter reaches a certain value. • Definite repetition: number of repetitions is known A student takes four courses in a quarter.A student takes four courses in a quarter. Each course will be assigned a grade with the score from 0 to 4. Develop a C program to calculate the grade point average (GPA) for the quarter.
  • 24. #define NUM 4 main() { int count; double grade, total, gpa; count = 0; total = 0; /* processing */ while(count < NUM) { printf("Enter a grade: "); scanf("%lf", &grade); total += grade; Enter a grade: 4 Enter a grade: 3.7 Enter a grade: 3.3 Execution and Output: Macro NUM ≡ 4 total += grade; count++; } /* termination */ gpa = total/NUM; printf("The GPA is: %fn", gpa); } Enter a grade: 4 The GPA is: 3.750000
  • 25. Sentinel-controlled repetition • Loop repeated until the sentinel (signal) value is entered. • Indefinite repetition: number of repetitions is unknown when the loop begins execution. Example: Develop a GPA calculation program that will process grades with scores in the range of [0, 4] for an arbitrary number of courses.
  • 26.
  • 27. #define SENTINELNUM -1 #define HIGHESTMARK 4 main() { int count; double grade, total, gpa; /* initialization */ count = 0; total = 0; printf("Enter a grade [0, %d] or %d to end: ", HIGHESTMARK, SENTINELNUM); scanf("%lf", &grade); while((int)grade != SENTINELNUM) { if(0 <= grade && grade <= HIGHESTMARK) { total += grade; count++; } else { printf("Invalid grade %cn", 'a'); } printf("Enter a grade [0, %d] or %d to end: ", HIGHESTMARK, SENTINELNUM); scanf("%lf", &grade); }
  • 28. /* termination */ if(count != 0) { gpa = total/count; printf("The GPA is: %fn", gpa); } else printf("No grade entered.n"); } Execution and Output: Enter a grade [0, 4] or -1 to end: 4 Enter a grade [0, 4] or -1 to end: 3.7 Enter a grade [0, 4] or -1 to end: 3.3 Enter a grade [0, 4] or -1 to end: 4 Enter a grade [0, 4] or -1 to end: 10 Invalid grade Enter a grade [0, 4] or -1 to end: 3.7 Enter a grade [0, 4] or -1 to end: -1 The GPA is: 3.740000
  • 29. • do-while Loop – The syntax of a do-while statement is as follows: do statement – The evaluation of the controlling expression takes place after each execution of the loop body. – The loop body is executed repeatedly until the return value of the controlling expression is equal to 0. while(expression);
  • 30. The do-while Statement • Structure do { statement; } while(expression); do { printf("%dn", a); a = a + 1; } while (a < b); • Operation: Similar to the while control except that statement is executed before the expression is evaluated. This guarantees that statement is always executed at least one time even if expression is FALSE.
  • 31. Flowchart of a do-while loop • The syntax of a do-while statement is as follows: do statementstatement while(expression);
  • 32. Example: int i = 0; do { printf(“%d ”, i); i++;i++; } while(i < 5); Output: 0 1 2 3 4
  • 33. – What is the output of the following example? Example: int i = 10; do { printf(“%d ”, i); i++; } while(i < 5); Output: 10
  • 34. The for Statement • Structure: for(expr1; expr2; expr3) { statement; } • Operation: The for loop in C is simply a shorthand way of expressing a while statement: expr1;expr1; while(expr2) { statement; expr3 } • The comma operator lets you separate several different statements in the initialization and increment sections of the for loop (but not in the test section).
  • 35. C Errors to Avoid • Putting = when you mean == in an if or while statement • Forgetting to increment the counter inside the while loop - If you forget to increment the counter, you get an infinite loop (the loop never ends). • Accidentally putting a ; at the end of a for loop or if statement so that the statement has no effect - For example: for (x=1; x<10; x++); printf("%dn",x); only prints out one value because the semicolon after the for statement acts as the one line the for loop executes.
  • 36. • For Loop – The syntax of a for statement is as follows: for(expression1; expression2; expression3) statement – The expression expression1 is evaluated as a void expression before the first evaluation of the controlling expression.expression. – The expression expression2 is the controlling expression that is evaluated before each execution of the loop body. – The expression expression3 is evaluated as a void expression after each execution of the loop body. – Both expression1 and expression3 can be omitted. An omitted expression2 is replaced by a nonzero constant.
  • 37. –The for-loop is semantically equivalent to the following while-loop: expression1; while(expression2) { statement expression3; }
  • 38. Flowchart of a for Loop The syntax of a for loop is as follows: for(expression1; expression2; expression3) statement
  • 39. Example: int i; for(i = 0; i < 5; i++) { printf(“%d ”, i); } 0 1 2 3 4 Output:
  • 40. Example: Calculating a factorial 5!. The factorial n! is defined as n*(n-1)! main() { int i, f, n; printf(“Please input a numbern”); scanf(“%d”, &n); for(i=1, f=1; i<=n; i++) { f = f*i;f = f*i; } printf(“factorial %d! = %dn", n, f); } Execution and Output: 5 factorial 5! = 120
  • 41. int i; for(i=0; i<5; i++) { Jump Statements • Break Statements – The break statement provides an early exit from the for, while, do-while, and for each loops as well as switch statement. – A break causes the innermost enclosing loop or switch to be exited immediately. Example: { if(i == 3) { break; } printf("%d", i); } Output :0 1 2
  • 42. int i; • Continue Statements – The continue statement causes the next iteration of the enclosing for, while and do-while loop to begin. – A continue statement should only appear in a loop body. int i; for(i=0; i<5; i++) { if(i == 3) { continue; } printf("%d", i); } Output : 0 1 2 4
  • 43. Nested Loop Nested loop = loop inside loop Program flow The inner loops must beThe inner loops must be finished before the outer loop resumes iteration.
  • 44. Write a program to print a multiplication table. 1 2 3 4 5 6 7 8 9 10 ------------------------------------------ 1| 1 2| 2 4 3| 3 6 9 4| 4 8 12 16 5| 5 10 15 20 255| 5 10 15 20 25 6| 6 12 18 24 30 36 7| 7 14 21 28 35 42 49 8| 8 16 24 32 40 48 56 64 9| 9 18 27 36 45 54 63 72 81 10| 10 20 30 40 50 60 70 80 90 100 ------------------------------------------
  • 45. Example: A program to print a multiplication table. main() { int i, j; printf("1 2 3 4 5 6 7 8 9 10n"); printf("-------------------------------------n"); for(i=1; i<= 10; i++) { /* outer loop */ printf("%d ", i);printf("%d ", i); for(j=1; j<=i; j++) { /* inner loop */ printf("%d ", i*j); } printf("n"); } printf("------------------------------------n"); }
  • 46. Solve all problem using while,do – while and for • WAP to find sum of ten numbers. • WAP to display all numbers between 1 to 1000 that are perfectly divisible by 10. • WAP to display all numbers between 2000 to 100 that are perfectly divisible by 13 and 15 and 17 and 19. • WAP to find sum of all numbers between 500 to 1500 that are perfectly divisible by 3 and 5 and 15 and 45. • WAP to find sum of all numbers between 10000 to 1000 that are• WAP to find sum of all numbers between 10000 to 1000 that are perfectly divisible by 3 and 7 and 9 and 42. • WAP to find factorial of given number – N! = N * (N-1)! • WAP to check whether a given number is prime or not. – A number is prime if it is divisible by 1 and the number itself only • WAP to generate all prime numbers between 100 to 1.
  • 47. • WAP to generate multiplication table of any given number • WAP to generate multiplication table of number 1 to 5. • WAP to check whether a given program in Armstrong or not. – 153 is a Armstrong number because 13+53+33=153 • WAP to check whether a number is strong or not. – 145 is a strong number because 1! + 4! +5 ! = 145 • WAP to check whether a number is perfect or not. – 28 is a perfect number because 1+2+4+7+14 = 28 • WAP to find GCD (HCF) of given two numbers. • WAP to find LCM of given numbers.