Answer to Question #296999 in C++ for Harsh

Question #296999

Q2: When will the ‘while’ loop be preferred over the for loop? Mention the scenario and write the



programme to demonstrate this.

1
Expert's answer
2022-02-14T06:37:47-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog