Lecture 5 CSC1261
Lecture 5 CSC1261
16/09/2024 – 20/12/2024
Richard Mugisha
Course Plan (Provisional)
• Week 1: No Lecture due EPT
• Week 2: No Lecture due to EPT
• Week 3: Lecture #0 + Lecture #1
• Week 4: Lecture #2
• Week 5: Lab #1
• Week 6: Lecture #3 + Lecture #4
• Week 7: Lecture #5 + Lecture #6
• Week 8: Lab #2
• Week 9: Lecture #7
• Week 10: Lecture #8 + Lecture #9
• Week 11: Lab #3
• Week 12: Lecture #10 (Course Summary/Repetition)
• Week 13: Self Study
• Week 14: Self Study
Richard Mugisha
LOOPING
Chapter 5
Introduction
• We use loops when you want to
execute statement several times until a
condition is reached.
• Generally, loops consist of two parts:
❑ One or more control expressions which control the
execution of the loop.
❑ Body , which is the statement or a set of statement
which is executed over and over
3 types of loops
– For loop
– While loop
– Do while loop
For Loop
• The basic format of the for statement is,
main()
{
int count;
for(count = 1; count <= 10; count=count+1)
printf("%d ", count);
}
Sample Program Output: 1 2 3 4 5 6 7 8 9 10
For Loop
Example
// An example of using a for loop to print out
characters
#include <stdio.h>
main()
{
char letter;
for( letter = 'A'; letter <= 'E'; letter = letter + 1 )
printf("%c", letter);
}
• Sample Program Output: A B C D E
For Loop
Sum of the first n numbers
#include <stdio.h>
main()
{
int i,n,sum=0;
printf("ENTER THE LIMIT\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf("\n THE SUM OF FIRST %d NUMBERS = %d", n, sum);
}
For Loop
Multiplication Table
#include<stdio.h>
main()
{
int i, table, counter=1;
int loop = 0;
while(loop <= 10)
{
printf ("%d\n",loop);
++loop;
}
}
While loop
Multiplication table from 1 to 10
#include<stdio.h>
main(){
int i,j;i=1;
while(i<=10){
j=1;
while(j<=10){
printf("%d x %d = %d\n",i,j,i*j);
j++;
}
printf("\n\n");i++;
}
}
Do While Loop
• When developing programs, it sometimes become
desirable to have the test made at the end of the loop
rather than at the beginning.
• This looping statement is known as the do statement.
– N.B: Remember that, unlike the for and while loops, the do statement
guarantees that the body of the loop will be executed at least once.
Do While Loop
/* Program that displays number from 1 to 9 using Do
while */
#include<stdio.h>
main(){
int i;
i=1;
Do
{
printf("\n i is:%d",i);
i=i+1;
}
while(i<10);
}
Exercise
• Make a program to print out multiplication table of 7 using do
while.
return 0;
}
Pascal’s Triangle
#include <stdio.h>
int main()
{
int rows, coef = 1, space, i, j;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=0; i<rows; i++)
{
for(space=1; space <= rows-i; space++)
printf(" ");
for(j=0; j <= i; j++)
{
if (j==0 || i==0)
coef = 1;
else
coef = coef*(i-j+1)/j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
For(initialization; condition;
incrementation) body;
CSC1261 Computer Programming in C
16/09/2024 – 20/12/2024
Richard Mugisha