Looping Statements Activity #1
Looping Statements Activity #1
Looping Statements Activity #1
Write a program in C++ that prompts the user to input an integer and then outputs both the
individual digits of the number and the sum of the digits.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int inputNumber, sum, individualNumber;
cin >> inputNumber;
do {
individualNumber = inputNumber % 10; //Extract the last digit of the number
sum += individualNumber;
inputNumber = inputNumber / 10; //Remove the last digit
} while (inputNumber > 0);
cout << "The sum of the individual numbers is: " << sum << endl;
return 0;
}
2. Write a program in C++ that prompts the user to enter two integers. The program outputs
how many numbers are multiples of 3 and how many numbers are multiples of 5 between the
two integers (inclusive).
#include <iostream>
using namespace std;
int main() {
if (temp % 3 == 0)
multiple3count++;
if (temp % 5 == 0)
multiple5count++;
temp++;
}
cout << "Multiples of 3 between " << num1 << " and " << num2 << ": " << multiple3count << endl;
cout << "Multiples of 5 between " << num1 << " and " << num2 << ": " << multiple5count << endl;
return 0;
}
3. Write a program in C++ that prompts the user to input a positive integer. It should then
output a message indicating whether the number is a prime number.
#include <iostream>
using namespace std;
int main()
{
std::cout << "Please input a positive integer: ";
int number;
std::cin >> number;
if(number < 0)
{
std::cout << "Error: integer is negative\n";
return 1;
}
if(number < 2)
{
std::cout << "Integer is not a prime number\n";
return 0;
}
if(number == 2)
{
std::cout << "Integer is a prime number\n";
return 0;
}
if(number % 2 == 0)
{
std::cout << "Integer is not a prime number\n";
return 0;
}
#include<iostream>
using namespace std;
int main()
i = firstNum;
{
if (i % 2 == 0)
sum = sum + i;
else
i++;
i = 1;
cout << "\nNumber Square\n";
while (i <= 10)
cout << " " << i << "\t " << i * i << endl;
i++;
}
return 0;
5. Write a program in C++ that will loop by inputting any integer and displays whether the
integer is “POSITIVE” or “NEGATIVE”, and terminate the loop if the integer is equal to zero
using any looping construct.
#include <iostream>
using namespace std;
int main()
{
signed long num1 = 0;
cout << "\n\n Check whether a number is positive, negative or zero :\n";
cout << "-----------------------------------------------------------\n";
cout << " Input a number : ";
cin >> num1;
if(num1 > 0)
{
cout << " The entered number is positive.\n\n";
}
else if(num1 < 0)
{
cout << " The entered number is negative.\n\n";
}
else
{
std::cout << " The number is zero.\n\n";
}
return 0;
}