Programming Fundamentals Lab 06 (Simple Loops and Switch)
Programming Fundamentals Lab 06 (Simple Loops and Switch)
Course Instructor:
Lab Instructors:
1. While Loop
General form of while loop is
Initialization
While (loop condition)
{
Statement(s)
Updating
}
Where expression acts as a decision maker. The statements from the body of the loop. Body of loop is
executed as long as the expression evaluates to true.
2. For Loop
General form of for loop is
{
Statement(s)
}
Initialization, loop condition and updating (called loop control statements) control the execution of body
of the for loop.
The control statement that allows us to make a decision from the number of choices is called a switch, or
more correctly a switchcase-default, since these three keywords go together to make up the control
statement. They most often appear as follows:
For Loop
#include<iostream>
using namespace std;
int main(void)
{
int count;
// Display the numbers 1 through 10
for(count = 1; count <= 10; count++)
cout<< count;
cout<<endl;
}
Output example:
1 2 3 4 5 6 7 8 9 10
Sample Program 2:
While loop
#include<iostream>
using namespace std;
int main ()
{
/* local variable definition */
int a = 0;
int main()
{
Int i = 2;
switch(i)
{
case 1:
cout<<”One”;
break;
case 2:
cout<<”Two”;
break;
case 3:
cout<<”Three”;
break;
default:
cout<<”Four”;
break;
}
return 0;
}
Task 1
Calculate the sum of number from one to ten using for and while loop.
Task 2
Write for statements that print the following sequences of values
a) 1, 2, 3, 4, 5, 6, 7
b) 3, 8, 13, 18, 23
c) 20, 14, 8, 2, –4, –10
Task 3
Write a program that calculates and print the average of even numbers from 2 -30, using
all loops.
Task 4
Write a program that takes initial and ending values and print all even and odd numbers
between the range in a tabular form.
Sample Output
Even Odd
13
14 15
16 17
18 19
20 21
22 23
24
Task 5
Write a program for calculator using switch Control structure which takes a mathematical
expression with two operands and one operator between them, e.g. 3+4, 4*7, 32/4 and
20-13.
Note: You are supposed to enter the expression without spaces.
Sample Outpur 1.
Sample Outpur 2.
Sample Outpur 3.