Q2: When will the ‘while’ loop be preferred over the for loop? Mention the scenario and write the
programme to demonstrate this.
#include <iostream>
#include <vector>
int main()
{
std::vector<int> arr;
int choise = 0;
while (choise != 3) // we use while loop to print menu because we dont need counter
{
choise = 0;
std::cout << "1.Add value\n2.Print values\n3.Exit\nEnter your choise : ";
std::cin >> choise;
switch (choise)
{
case 1:
{
int tmp = 0;
std::cout << "Enter value : ";
std::cin >> tmp;
arr.push_back(tmp);
}
break;
case 2:
{
std::cout << "Values : ";
for (int i = 0; i < arr.size(); i++) // we use for loop to go throught array because we need counter i
{
std::cout << arr[i] << '\t';
}
std::cout << std::endl;
}
break;
case 3:
break;
default:
break;
}
}
return 0;
}
Comments
Leave a comment