Loops in C.

Slides:



Advertisements
Similar presentations
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Advertisements

ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
 Decision making statements Decision making statements if statement if...else statement Nested if...else statement (if...elseif....else Statement) 
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Chapter 4 Program Control Statements
Chapter 5 Control Structures: Loops 5.1 The while Loop The while loop is probably the most frequently used loop construct. The while loop is a conditional.
Do-while loop Syntax do statement while (loop repetition condition)
Repetitive Structures BBS514 Structured Programming (Yapısal Programlama)1.
1 Flowchart notation and loops Implementation of loops in C –while loops –do-while loops –for loops Auxiliary Statements used inside the loops –break –continue.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Chapter 7: Repetition Structure (Loop) Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
LOOPS IN ‘C’ PROGRAMMING. V ERY O FTEN, Y OU W ILL W ANT TO D O S OMETHING M ORE T HAN O NCE HA.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
The following statements are for y = -1; if ( x ) if ( x>0 ) y = 1; else y = 0; A. y= -1 x0 B. y= 0 x0 C. y= 1 x
Week 3.  TO PRINT NUMBERS FROM 1 TO 20  TO PRINT EVEN NUMBERS FROM 1 TO 20 2.
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied. Suppose you want to execute some code/s 10 times.
Computer Programming -1-
Control Structures (Repetition structure) Jump Statements
Chapter 4 – C Program Control
‘C’ Programming Khalid Jamal.
CSE 220 – C Programming Loops.
Fundamentals of PL/SQL part 2 (Basics)
Chapter 6: Loops.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
EKT120 COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Lecture 7: Repeating a Known Number of Times
C Program Controls + Flow Structure
Chapter 4 - Program Control
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Week 4 – Repetition Structures / Loops
Quick Test What do you mean by pre-test and post-test loops in C?
Lecture 13 & 14.
Chapter 2.2 Control Structures (Iteration)
Iteration statement while do-while
Programming Fundamentals
Control Structures Lecture 7.
INC 161 , CPE 100 Computer Programming
Looping.
Arrays, For loop While loop Do while loop
Loop Control Structure.
- Additional C Statements
Outline Altering flow of control Boolean expressions
Chapter 6 Decision Making and Looping
Chapter 4 - Program Control
3 Control Statements:.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Program Control Topics While loop For loop Switch statement
Chapter 2.2 Control Structures (Iteration)
Week 6 CPS125.
UMBC CMSC 104 – Section 01, Fall 2016
Computer programming Lecture 3.
More Loops Topics Counter-Controlled (Definite) Repetition
Repetition Statements (Loops) - 2
Chapter 4 - Program Control
More Loops Topics Counter-Controlled (Definite) Repetition
CSC215 Lecture Control Flow.
More Loops Topics Counter-Controlled (Definite) Repetition
LOOP Basics.
Presentation transcript:

Loops in C

Loops You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages

Loops flowchart

Loop Type & Description while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. do...while loop It is more like a while statement, except that it tests the condition at the end of the loop body. nested loops You can use one or more loops inside any other while, for, or do..while loop.

while loop in C A while loop in C programming repeatedly executes a target statement as long as a given condition is true. /*condition initialization*/ while(condition) { statement(s); //condition update } /*condition initialization*/ while(condition) statement; //condition update

While Example: print numbers between an interval, for example [10,20) #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) printf("value of a: %d\n", a); a++; } return 0;

Display the count of the characters of a sentence ended with an enter #include <stdio.h> int main() { printf("Enter a sentences with a dot at the end>>"); int counter=0; char ch=getche(); while(ch!='\r') ch=getche(); counter++; } printf("\nThe count of the characters is: %d",counter); return 0;

Compute #include <stdio.h> int main() { int x,y; printf("Enter x and y to compute pow(x,y)>>"); scanf("%d,%d",&x,&y); int pow=1; while(y>0) pow*=x; y--; } printf(“pow(%d,%d)=%d”,x,y,pow); return 0;

The Infinite Loop #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* while loop execution */ while( a < 20 ) printf("value of a: %d\n", a); } return 0; #include <stdio.h> int main () { while( 1) ; } return 0;

for loop in C A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. for ( init; condition; increment ) { statement(s); } for ( init; condition; increment ) statement;

for loop in C (cont.) The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop. After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.

Example: Factorial of a Number int n, i; unsigned long long factorial = 1; printf("Enter an integer: "); scanf("%d",&n); // show error if the user enters a negative integer if (n < 0) printf("Error! Factorial of a negative number doesn't exist."); else { for(i=1; i<=n; ++i) factorial *= i; // factorial = factorial*i; } printf("Factorial of %d = %llu", n, factorial);

Factorial with a reverse loop #include <stdio.h> int main() { int x; int fact=1; scanf(“%d”,&x); for (;x>1;x--) fact*=x; } printf(“%d! = %d“,x,fact); return 0;

Comma in for example: A program which computes : #include <stdio.h> int main() { float sum,x; int counter,num; printf("Enter a number >>"); scanf("%d",&num); for (sum=0,counter=1,x=1; counter<=num; counter++, x*=2) sum+=1/x; printf("\ncount = %d, sum = %f",counter,sum); } return 0;

Infinite for int i= 0; for(;;) { printf("%d“,i++); }

do...while loop in C Unlike for and while loop s, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop. do { statement(s); } while( condition ); do statement; while( condition );

do…while Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false.

do…while example #include <stdio.h> int main () { /* local variable definition */ int a = 10; /* do loop execution */ do printf("value of a: %d\n", a++); }while( a < 20 ); return 0; }

nested loops in C C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept. while(condition) { statement(s); } for ( init; condition; increment ) { statement(s); }

Using nested for to create the below output #include <stdio.h> void main() { char ch; int i; for (ch='A';ch<='G';ch++) for (i=1;i<=7;i++) printf("%c%i ",ch,i); } printf("\n"); A1 A2 A3 A4 A5 A6 A7 B1 B2 B3 B4 B5 B6 B7 C1 C2 C3 C4 C5 C6 C7 D1 D2 D3 D4 D5 D6 D7 E1 E2 E3 E4 E5 E6 E7 F1 F2 F3 F4 F5 F6 F7 G1 G2 G3 G4 G5 G6 G7

Multiplication table for the interval [1,5], using nested while #include <stdio.h> void main() { int i=1,j; while(i<=5) j=1; while(j<=5) printf(“%d*%d=%2d ",i,j,i*j); j++; } printf("\n"); i++;

Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

Control Statement & Description break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. goto statement Transfers control to the labeled statement.

Flowchart of break statement

Calculates sum until user enters negative number int i; double number, sum = 0.0; for(i=1;; ++i) { printf("Enter a n%d: ",i); scanf("%lf",&number); // If user enters negative number, loop is terminated if(number < 0.0) break; } sum += number; // sum = sum + number; printf("Sum = %.2lf",sum);

Example: Program to Check Prime Number int n, i, flag = 0; printf("Enter a positive integer: "); scanf("%d",&n); for(i=2; i<=sqrt(n); ++i) { // condition for nonprime number if(!n%i) flag=1; break; } if (!flag) printf("%d is a prime number.",n); else printf("%d is not a prime number.",n);

Flowchart of continue Statement

Example: print even numbers between [1,10] using continue int i; for (i=1;i<=10;i++) { if (i%2) continue; printf("%d\n",i); }

goto statement

Example goto: creating a loop using goto #include <stdio.h> int main() { int x=0; loop: x++; if (x<20) printf("%d\n",x); goto loop; } return 0;