You are on page 1of 4

LAB 12 TASKS

1. The square of an integer n is normally calculated by multiplying n by itself, that is,


n2 = n * n. Another way to calculate n2 is by adding the first n odd integers. For example,

1 + 3 + 5 = 9 = 32
1 + 3 + 5 + 7 = 16 = 42
1 + 3 + 5 + 7 + 9 = 25 = 52

Write a program segment that uses this method to calculate and print the square of a
number. The program should prompt the user to enter an integer, then use this method to
calculate and then print the square of the integer entered. Use a do-while loop.
Code:
#include <iostream>
using namespace std;
int main() {
int a;
do {
cout << "Enter an integer: ";
cin >> a;
if (a != 0)
{
int b = 0;
int c = 1;
for (int i = 1; i <= a; ++i)
{
b += c;
c += 2;
}
cout << "The square of " << a << " is: " << b << endl;
}
} while (a != 0);
return 0;
}
Output:
2. Write a C++ program that takes a distance value in feet and converts it into inches.
Continue converting the input values until the user enters zero (The distance value should
be greater than zero).
Code:
#include<iostream>
using namespace std;
int main()
{
float a;
do
{
cout << "Enter the distance in feet: ";
cin >> a;
cout << "The distance i inches is: " << a * 12 << endl;
}
while (a != 0);
return 0;
}
Output:

3. Create a simple four function calculator. Use do-while Loop to display a menu to the user
and wait for the user to make a valid choice. After that take two numbers as input and
depending on the choice selected by the user, perform the appropriate mathematical
operation. Continue the process till the user wants to perform no more operations.
Code:
#include <iostream>
using namespace std;
int main()
{
float a, b,c;
do
{
cout << "1. Add" << endl;
cout << "2. Subtract" << endl;
cout << "3. Multiply" << endl;
cout << "4. Divided" << endl;
cout << "Enter your Choice: ";
cin >> a;
cout << endl;
if (a == 1)
{
cout << " Add" << endl;
cout << "Enter the number: ";
cin >> c;
cout << "Enter the number: ";
cin >> b;
cout << "Result: " << c + b << endl << endl;
}
if (a == 2)
{
cout << " Subtract" << endl;
cout << "Enter the number: ";
cin >> c;
cout << "Enter the number: ";
cin >> b;
cout << "Result: " << c - b << endl << endl;
}
if (a == 3)
{
cout << " Multiply" << endl;
cout << "Enter the number: ";
cin >> c;
cout << "Enter the number: ";
cin >> b;
cout << "Result: " << c * b << endl << endl;
}
if (a == 4)
{
cout << " Divided" << endl;
cout << "Enter the number: ";
cin >> c;
cout << "Enter the number: ";
cin >> b;
if (b == 0)
{
cout << "0 can not be divided" << endl;
}
else
{
cout << "Result: " << c / b << endl << endl;
}
}
}
while (a < 5);
return 0;
}
Output:

You might also like