Week 6 PDF
Week 6 PDF
Muhammad Kamran
Lecturer Civil Engineering Department
Sarhad University of Information and Technology
MOTIVATION
• Suppose that you need to print a string (e.g., "Welcome to C++!") a hundred
times. It would be tedious to have to write the following statement a hundred
times:
• To use a sequence of values. E.g. a user may want to display integers from 1
to 10.
“for” LOOP
• “for” loop executes one or more statements for a specified number of times.
Initialize variable
Condition true
Test the variable statement Increment variable
false
“for” LOOP
• Syntax
for ( initialization ; condition ; increment/decrement )
{
Statement1;
Statement2;
}
TRACE FOR LOOP
Declare i
int i;
for( i=0; i<2; i++)
{
cout<<“Welcome to C++\n”;
}
TRACE FOR LOOP
Variable initialized
i is now 0
int i;
for( i=0; i<2; i++)
{
cout<<“Welcome to C++\n”;
}
TRACE FOR LOOP
(i < 2) is true
since i is 0
int i;
for( i=0; i<2; i++)
{
cout<<“Welcome to C++\n”;
}
TRACE FOR LOOP
since i is 1
int i;
for( i=0; i<2; i++)
{
cout<<“Welcome to C++\n”;
}
TRACE FOR LOOP
since i is 2 now
int i;
for( i=0; i<2; i++)
{
cout<<“Welcome to C++\n”;
}
TRACE FOR LOOP
• Write a program to print multiplication table of a number entered by the user using for loop ??
• Write a program that inputs a number from the user , Divide into the digits and check the largest
digit in the number and smallest digit in the number using for loop ??
• Write a program that inputs a number. It then displays the sum of all odd numbers and the sum of
all even numbers separately from 1 to the number entered by the user using for loop ??
• Write a program that inputs an integer from the user and prints if it’s a prime number or composite
number. A number is prime if it has factors 1 and itself, otherwise it’s a composite number using for
loop ??