C++ Lab 5

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

LAB MANUAL # 5

Course: Computer Programming (CP-107)


Session: 22CP

Loop Mechanism (for, while and do-while)

This lab has been designed to practice looping statements e.g., for loop, while loop and do-
while loop. Clear concept about this programming construct has already been provided in the
class. Supporting material can be found in section 3.3 of Problem solving with C++. Lab
handouts are also provided along with the lab manual as reference material.
Objectives:
In this lab, you will practice:
• Designing and using for loop statement.
• Designing and using while loop statement.
• Designing and using do while loop statement.
• Selecting appropriate loop type for given problem.

Lab Tasks: 15/


Question # 1: 2/
Write a program using for loop to calculate the sum and square of the first 10 odd numbers.
Question # 2: 2/
Write a program that prompts the user to enter a number and then print the table of that
number using for loop.
Question # 3: 2/
Write a program to check whether the number entered by the user is prime or not.
Question # 4: 3/
Write a program to generate a Fibonacci series up till 200. Here are the first few terms of the
series:
1 1 2 3 5 8 13 21 34 55
Each term is found by adding the two previous ones:
1 + 1 𝑖𝑠 2, 1 + 2 𝑖𝑠 3, 2 + 3 𝑖𝑠 5, 3 + 5 𝑖𝑠 8, and so on. Do this using while and do-while loop
Question # 5: 3/
An approximate value of pi can be calculated using the series given below:
𝑝𝑖 = 4 [ 1 – 1/3 + 1/5 – 1/7 + 1/9 . . . + ((– 1)𝑛)/(2𝑛 + 1) ]
LAB MANUAL # 5
Course: Computer Programming (CP-107)
Session: 22CP

Write a C++ program to calculate the approximate value of pi using this series. The program
takes an input n that determines the number of terms in the approximation of the value of pi
and outputs the approximation.
Question # 6: 3/
Observe output of the following codes and rewrite them to fix the problem (if any).
a. int main()
{
for(int i=0;i<10;i++)
cout<<i<<endl;
cout<<i+5;
return 0;
}

b. int main()
{
int i=0;
while(i<10);
{
cout<<i<<endl;
i++;
}
return 0;
}

c. int main()
{
for(int j=0;j<10;j--)
cout<<j<<endl;
return 0;
}

***************

You might also like