You are on page 1of 4

IT 103- COMPUTER PROGRAMMING 2

TOPIC: LOOPING CONSTRUCT

Direction: Make a program that will solve the given problems below using C++
programming language. You may use any type of looping statement – while, do while or
for. Choose at least two programs to be presented during our online class on Wednesday,
May 19, 2021.

1. A program declares an int variable named evenNum and initializes it to 2. Write the C ++
code to display the even integers 2, 4, 6, 8, and 10 on separate lines on the computer
screen.
2. Write the C ++ code to display the integers 15, 12, 9, 6, 3, and 0 on separate lines on the
computer screen.
3. A program that prints all even numbers from 50 to 1.
Answer:
#include <stdio.h>

Int main() {
Int i;
Printf(“Even numbers from 50 to 1 :\n”);
For (i = 50; i >= 1; i --)
{
If(i%2 == 0)
{
Printf(“%d “, i);
}
}
Return 0;
}
4. A program that prints numbers in reverse order from 100 to 50 with an interval of
5.
Answer:

#include <stdio.h>

int main() {
int i;
printf("Even numbers 100 to 50:\n");
for (i = 100; i >= 50; i--)
{
if(i%5 == 0)
{
printf("%d ", i);
}
}
return 0;
}
5. A program to calculate the sum of all numbers from 1 to 20. The output should be
the total of all numbers from 1 to 20
(1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20).
Answer:
#include
using namespace std;
int main(){
int n, sum=0;
cout<<"Enter the value of n(positive integer): "; //Storing the input integer value i sa
atong variable n
cin>>n; /* If negative number imo ibutang sa value sa n then modisplay syag   * error
message nga ang value of n is invalid     */
if(n<=0)
{
cout<<"Invalid value of n";
}
else
{ // using for loop to calculate the sum
for(int i = 1; i <= n; i++)
{
sum = sum+i;
}
cout<<"Total of all numbers from 1 to n is: "<<sum;
}
return 0;
}

Try to run this source code and discuss the output.

#include <iostream>

using namespace std;

int main ( )

int number =44;

int guess;

cout<<” Guess a number between 1 and 100.\n”;

do

cout<<”Enter your guess:”;

cin>> guess;

if (guess > number)


cout<<” Too high!”;

else if (guess < number)

cout<<”Too low!”;

while (guess != number)

cout<< “You win. The answer is”<<number;

return 0;

Answer:

This program that will emulate a common guessing game.


The game should randomly set a number which the user will have to guess and will get "higher"
or "lower" hints as it goes. Only integers will be used for the target number.
The target number should be 1 to 100, The game will end with a note of the win when the
correct number is guessed.

Prepared by:

MELIZA J. CHATTO
Instructor

You might also like