Answer to Question #297793 in C++ for Shiva

Question #297793

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-15T01:48:38-0500

In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.

#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 know how many times we will run
    {
        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 know how many time we will run
            {
                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