Introduction to Loops, Lecture notes of Programming Languages

A basic introduction to loops in Language C

Typology: Lecture notes

2021/2022

Uploaded on 10/23/2023

muneeb-shahid-1
muneeb-shahid-1 🇵🇰

1 document

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
LEC 10 & 11
LOOPS
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Introduction to Loops and more Lecture notes Programming Languages in PDF only on Docsity!

LEC 10 & 11

LOOPS

  • (^) A Loop executes the sequence of statements many times until the stated condition becomes false. A loop consists of two parts, a body of a loop and a control statement.
  • (^) C programming has three types of loops:
  • (^) for loop
  • (^) while loop
  • (^) do...while loop

Syntax :

variable initialization; while(condition) { statements; variable increment or decrement; }

  • (^) Example: Program to print first 10 natural numbers #include<stdio.h> void main( ) { int x; x = 1; while(x <= 10) { printf("%d\t", x); /* below statement means, do x = x+1, increment x by 1*/ x++; } }

#include<stdio.h> void main () { int j = 1; while (j+=2,j<=10) { printf("%d ",j); } printf("%d",j); }

#include<stdio.h> void main () { while () { printf("hello Javatpoint"); } } Output compile time error: while loop can't be empty

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.
  • (^) The syntax of the do...while loop is: do { // statements inside the body of the loop } while (testExpression);

#include<stdio.h> #include<conio.h> int main() { int num=1; //initializing the variable //do-while loop do { printf("%d\n",2*num); num++; //incrementing operation } while(num<=10); return 0; }

#include<stdio.h> void main() { int a, i; a = 5; i = 1; do { printf("%d\t", a*i); i++; } while(i <= 10); }