Write a program in C++ that ask the user number of iteration for the loop and print "Light is On" in 1st iteration and the "Light is Off" for the second iteration and the work accordingly. You are allowed to use a single loop with one if-else statement only.
Sample For Program:
Sample Input:
Enter number of iterations: 5
Output:
Light is On
Light is Off
Light is On
Light is Off
Light is On
#include <iostream> //Preprogressive Directive
using namespace std; // Global Identifier
int main() // Main Function
{
// Variable Declaration
int number;
cout<<"Please enter a number of iterations: ";
cin>>number;
for (int i = 1; i<=number; i++)
{
if (i%2==1)
{
cout<<"Light is On"<<endl;
}
else
{
cout<<"Light is Off"<<endl;
}
}
return 0;
}
c++ programming exercise with solution |