0% found this document useful (0 votes)
39 views28 pages

Answer Sheet

C++ worksheet

Uploaded by

zebrehe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views28 pages

Answer Sheet

C++ worksheet

Uploaded by

zebrehe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

1) Receive a number and determine whether it is odd or even.

Steps:

 Start
 Input number
 Check if the number is divisible by 2 (number % 2 == 0)
o Yes → Display "Even"
o No → Display "Odd"
 End

2) Obtain two numbers from the keyboard, and determine and display which (if
either) is the larger of the two numbers.

Steps:

 Start
 Input first number (num1)
 Input second number (num2)
 Check if num1 > num2
o Yes → Display num1 is larger
o No → Check if num2 > num1
 Yes → Display num2 is larger
 No → Display "Both are equal"
 End

3) Receive 3 numbers and display them in ascending order from smallest to


largest.

Steps:

 Start
 Input first number (num1)
 Input second number (num2)
 Input third number (num3)
 Compare all three numbers to arrange in ascending order (use sorting or comparisons)
 Display numbers in ascending order
 End
4) Add the numbers from 1 to 100 and display the sum.

Steps:

 Start
 Initialize sum to 0
 Loop through numbers from 1 to 100
o Add each number to sum
 Display sum
 End

5) Add the even numbers between 0 and any positive integer number given by
the user.

Steps:

 Start
 Input a positive integer (num)
 Initialize sum to 0
 Loop through numbers from 0 to num
o If the number is even, add it to sum
 Display the sum
 End

6) Find the average of two numbers given by the user.

Steps:

 Start
 Input first number (num1)
 Input second number (num2)
 Calculate average: (num1 + num2) / 2
 Display the average
 End

7) Find the average, maximum, minimum, and sum of three numbers given by
the user.

Steps:
 Start
 Input first number (num1)
 Input second number (num2)
 Input third number (num3)
 Calculate sum: num1 + num2 + num3
 Find maximum of the three numbers
 Find minimum of the three numbers
 Calculate average: (num1 + num2 + num3) / 3
 Display sum, average, maximum, and minimum
 End

8) Find the area of a circle where the radius is provided by the user.

Steps:

 Start
 Input radius (r)
 Calculate area: π * r^2 (use 3.14 for π)
 Display the area
 End

9) Swap the contents of two variables using a third variable.

Steps:

 Start
 Input first number (num1)
 Input second number (num2)
 Use a third variable (temp)
o Set temp = num1
o Set num1 = num2
o Set num2 = temp
 Display num1 and num2 after swapping
 End

10) Swap the content of two variables without using a third variable.

Steps:

 Start
 Input first number (num1)
 Input second number (num2)
 Swap the values using arithmetic:
o Set num1 = num1 + num2
o Set num2 = num1 - num2
o Set num1 = num1 - num2
 Display num1 and num2 after swapping
 End

11) Read an integer value from the keyboard and display a message indicating if
this number is odd or even.

Steps:

 Start
 Input number (num)
 Check if num % 2 == 0
o Yes → Display "Even"
o No → Display "Odd"
 End

12) Read 10 integers from the keyboard in the range 0 - 100, and count how
many of them are larger than 50, and display this result.

Steps:

 Start
 Initialize counter to 0
 Loop 10 times to input 10 integers
o If the number is greater than 50, increase the counter
 Display the counter value
 End

13) Take an integer from the user and display the factorial of that number.

Steps:

 Start
 Input integer (n)
 Initialize result to 1
 Loop from 1 to n
o Multiply result by the loop index (i)
 Display the result (factorial)
 End

Worksheet 2
1) Receive a number and determine whether it is odd or even.
#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;

if (num % 2 == 0) {
cout << num << " is even." << endl;
} else {
cout << num << " is odd." << endl;
}
return 0;
}
2. Obtain two numbers from the keyboard, and determine and display which (if either) is the
larger of the two numbers.
#include <iostream>
using namespace std;

int main() {
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;

if (num1 > num2) {


cout << num1 << " is larger." << endl;
} else if (num2 > num1) {
cout << num2 << " is larger." << endl;
} else {
cout << "Both numbers are equal." << endl;
}
return 0;
}
3. Receive 3 numbers and display them in ascending order from smallest to largest.
#include <iostream>
using namespace std;

int main() {
int num1, num2, num3;
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;

if (num1 > num2) swap(num1, num2);


if (num1 > num3) swap(num1, num3);
if (num2 > num3) swap(num2, num3);

cout << "Numbers in ascending order: " << num1 << ", " << num2 << ", " << num3 << endl;
return 0;
}
4. Add the numbers from 1 to 100 and display the sum.
#include <iostream>
using namespace std;
int main() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
cout << "The sum of numbers from 1 to 100 is: " << sum << endl;
return 0;
}
5. Add the even numbers between 0 and any positive integer number given by the user.
#include <iostream>
using namespace std;

int main() {
int limit, sum = 0;
cout << "Enter a positive integer: ";
cin >> limit;

for (int i = 0; i <= limit; i += 2) {


sum += i;
}

cout << "The sum of even numbers from 0 to " << limit << " is: " << sum << endl;
return 0;
}
6. Find the average of two numbers given by the user.
#include <iostream>
using namespace std;
int main() {
double num1, num2, average;
cout << "Enter two numbers: ";
cin >> num1 >> num2;

average = (num1 + num2) / 2;


cout << "The average is: " << average << endl;
return 0;
}
7. Find the average, maximum, minimum, and sum of three numbers given by the user.
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
int num1, num2, num3, maxVal, minVal, sum;
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;

sum = num1 + num2 + num3;


maxVal = max({num1, num2, num3});
minVal = min({num1, num2, num3});
double average = sum / 3.0;

cout << "Average: " << average << endl;


cout << "Max: " << maxVal << endl;
cout << "Min: " << minVal << endl;
cout << "Sum: " << sum << endl;

return 0;
}
8. Find the area of a circle where the radius is provided by the user.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double radius, area;
cout << "Enter the radius of the circle: ";
cin >> radius;
area = M_PI * radius * radius;
cout << "The area of the circle is: " << area << endl;
return 0;
}
9. Swap the contents of two variables using a third variable.
#include <iostream>
using namespace std;
int main() {
int a, b, temp;
cout << "Enter two numbers: ";
cin >> a >> b;
// Swap using a third variable
temp = a;
a = b;
b = temp;

cout << "After swapping: a = " << a << ", b = " << b << endl;
return 0;
}
10. Swap the contents of two variables without using a third variable.
#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;

// Swap without a third variable


a = a + b;
b = a - b;
a = a - b;
cout << "After swapping: a = " << a << ", b = " << b << endl;
return 0;
}
11. Read an integer value from the keyboard and display a message indicating if this number is
odd or even.
#include <iostream>
using namespace std;

int main() {
int number;
cout << "Enter an integer: ";
cin >> number;

if (number % 2 == 0) {
cout << "The number is even." << endl;
} else {
cout << "The number is odd." << endl;
}

return 0;
}
12. Read 10 integers from the keyboard in the range 0 - 100, and count how many of them are
larger than 50, and display this result.
#include <iostream>
using namespace std;
int main() {
int num, count = 0;
cout << "Enter 10 integers (0-100):" << endl;

for (int i = 0; i < 10; i++) {


cin >> num;
if (num > 50) {
count++;
}
}

cout << "There are " << count << " numbers larger than 50." << endl;

return 0;
}

13. Take an integer from the user and display the factorial of that number.

#include <iostream>
using namespace std;
int main() {
int num;
unsigned long long factorial = 1;
cout << "Enter an integer: ";
cin >> num;
if (num < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
} else {
for (int i = 1; i <= num; ++i) {
factorial *= i;
}
cout << "The factorial of " << num << " is: " << factorial << endl;
}
return 0;
}
Worksheet 3
1. Write for, do-while, and while statements to compute the following sums
and products.
a. Sum of 1 + 2 + 3 + … + 100

Using for loop:

#include <iostream>
using namespace std;

int main() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
cout << "Sum (1 + 2 + ... + 100) using for loop: " << sum << endl;
return 0;
}
Using while loop:
#include <iostream>
using namespace std;

int main() {
int sum = 0, i = 1;
while (i <= 100) {
sum += i;
i++;
}
cout << "Sum (1 + 2 + ... + 100) using while loop: " << sum << endl;
return 0;
}
Using do-while loop:
#include <iostream>
using namespace std;

int main() {
int sum = 0, i = 1;
do {
sum += i;
i++;
} while (i <= 100);
cout << "Sum (1 + 2 + ... + 100) using do-while loop: " << sum << endl;
return 0;
}
b. Sum of 5 + 10 + 15 + … + 50
Using for loop:
#include <iostream>
using namespace std;

int main() {
int sum = 0;
for (int i = 5; i <= 50; i += 5) {
sum += i;
}
cout << "Sum (5 + 10 + 15 + ... + 50) using for loop: " << sum << endl;
return 0;
}
Using while loop:
#include <iostream>
using namespace std;

int main() {
int sum = 0, i = 5;
while (i <= 50) {
sum += i;
i += 5;
}
cout << "Sum (5 + 10 + 15 + ... + 50) using while loop: " << sum << endl;
return 0;
}
Using do-while loop:
#include <iostream>
using namespace std;

int main() {
int sum = 0, i = 5;
do {
sum += i;
i += 5;
} while (i <= 50);
cout << "Sum (5 + 10 + 15 + ... + 50) using do-while loop: " << sum << endl;
return 0;
}
c. Sum of 1 + 1/2 + 1/3 + 1/4 + … + 1/15
Using for loop:
#include <iostream>
using namespace std;

int main() {
double sum = 0;
for (int i = 1; i <= 15; i++) {
sum += 1.0 / i;
}
cout << "Sum (1 + 1/2 + 1/3 + ... + 1/15) using for loop: " << sum << endl;
return 0;
}
Using while loop:
#include <iostream>
using namespace std;

int main() {
double sum = 0;
int i = 1;
while (i <= 15) {
sum += 1.0 / i;
i++;
}
cout << "Sum (1 + 1/2 + 1/3 + ... + 1/15) using while loop: " << sum << endl;
return 0;
}
Using do-while loop:
#include <iostream>
using namespace std;

int main() {
double sum = 0;
int i = 1;
do {
sum += 1.0 / i;
i++;
} while (i <= 15);
cout << "Sum (1 + 1/2 + 1/3 + ... + 1/15) using do-while loop: " << sum << endl;
return 0;
}

d. Product of 1 * 2 * 3 * … * 20
Using for loop:
#include <iostream>
using namespace std;

int main() {
long long product = 1;
for (int i = 1; i <= 20; i++) {
product *= i;
}
cout << "Product (1 * 2 * 3 * ... * 20) using for loop: " << product << endl;
return 0;
}
Using while loop:
#include <iostream>
using namespace std;
int main() {
long long product = 1, i = 1;
while (i <= 20) {
product *= i;
i++;
}
cout << "Product (1 * 2 * 3 * ... * 20) using while loop: " << product << endl;
return 0;
}
Using do-while loop:
#include <iostream>
using namespace std;

int main() {
long long product = 1, i = 1;
do {
product *= i;
i++;
} while (i <= 20);
cout << "Product (1 * 2 * 3 * ... * 20) using do-while loop: " << product << endl;
return 0;
}
2. Print the numbers 10 through 49 in the following manner:
#include <iostream>
using namespace std;

int main() {
for (int i = 10; i <= 49; i++) {
cout << i << " ";
if (i % 10 == 9) {
cout << endl;
}
}
return 0;
}
3. Display all the prime numbers between 1 and 100.
#include <iostream>
using namespace std;

bool isPrime(int num) {


if (num <= 1) return false;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) return false;
}
return true;
}

int main() {
for (int num = 2; num <= 100; num++) {
if (isPrime(num)) {
cout << num << " ";
}
}
cout << endl;
return 0;
}
4. Count the number of digits in an integer number.
#include <iostream>
using namespace std;

int main() {
int number, count = 0;
cout << "Enter an integer: ";
cin >> number;
while (number != 0) {
number /= 10;
count++;
}
cout << "The number has " << count << " digits." << endl;
return 0;
}
5. Compute the letter grade of a student after accepting the mid and final marks.
#include <iostream>
using namespace std;
char calculateGrade(int mid, int finalExam) {
int total = mid + finalExam;
if (mid < 0 || mid > 40 || finalExam < 0 || finalExam > 60) {
cout << "Error: Marks should be in the range (mid: 0-40, final: 0-60)." << endl;
return 'E'; // Error grade
}
if (total >= 90) return 'A';
if (total >= 80) return 'B';
if (total >= 70) return 'C';
if (total >= 60) return 'D';
return 'F';
}

int main() {
int mid, finalExam;
char continueChoice;

do {
cout << "Enter midterm mark (0-40): ";
cin >> mid;
cout << "Enter final exam mark (0-60): ";
cin >> finalExam;

char grade = calculateGrade(mid, finalExam);


if (grade != 'E') {
cout << "The grade is: " << grade << endl;
}

cout << "Do you want to continue (y/n)? ";


cin >> continueChoice;

} while (continueChoice == 'y' || continueChoice == 'Y');

return 0;
}
6. Compute the factorial of a positive number using a for loop.
#include <iostream>
using namespace std;

int main() {
int number;
long long factorial = 1;
cout << "Enter a positive integer: ";
cin >> number;

if (number < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
} else {
for (int i = 1; i <= number; ++i) {
factorial *= i;
}
cout << "The factorial of " << number << " is: " << factorial << endl;
}
return 0;
}

7. Write a C++ code that computes the sum of the following series.
Sum = 1! + 2! + 3! + 4! + …n!
The program should accept the number from the user.
#include <iostream>
using namespace std;

// Function to calculate factorial of a number


long long factorial(int num) {
long long fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}

int main() {
int n;
long long sum = 0;

// Accept the number n from the user


cout << "Enter a number n: ";
cin >> n;

// Calculate the sum of factorials from 1! to n!


for (int i = 1; i <= n; i++) {
sum += factorial(i);
}

// Display the result


cout << "The sum of the series 1! + 2! + 3! + ... + " << n << "! is: " << sum << endl;

return 0;
}

8. Using the ASCII table numbers, write a program to print the following
output, using a
nested for loop. (Hint: the outer loop should loop from 1 to 5, and the inner
loop’s
start variable should be 65, the value of ASCII “A”).
A
AB
ABC
ABCD
ABCDE
#include <iostream>
using namespace std;

int main() {
// Outer loop to control the number of rows (1 to 5)
for (int i = 1; i <= 5; i++) {
// Inner loop to print characters from 'A' onwards
for (int j = 65; j < 65 + i; j++) {
cout << (char)j; // Print the character corresponding to ASCII value 'j'
}
cout << endl; // Move to the next line after each row
}
return 0;
}

9. Write a C++ program that displays the following output using their ASCII
values.
a
bc
def
gehi
jklmn
opqrst
#include <iostream>
using namespace std;

int main() {
// Variable to keep track of the starting ASCII value
int start = 97; // ASCII value of 'a'

// Outer loop to control the number of rows (6 rows)


for (int i = 1; i <= 6; i++) {
// Inner loop to print characters for the current row
for (int j = 0; j < i; j++) {
cout << (char)start; // Print the character corresponding to the ASCII value 'start'
start++; // Move to the next character
}
cout << endl; // Move to the next line after printing each row
}

return 0;
}

10. Write a C++ program that will print the following shapes.
A.
*
**
***
****
*****

B.
*****
****
***
**
*
C.
*
***
*****
*******
*********
D.
*
***
*****
***
#include <iostream>
using namespace std;

int main() {

// Shape A

cout << "Shape A:" << endl;

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= i; j++) {

cout << "*";

cout << endl;

cout << endl;

// Shape B

cout << "Shape B:" << endl;

for (int i = 5; i >= 1; i--) {

for (int j = 1; j <= i; j++) {

cout << "*";

cout << endl;

cout << endl;

// Shape C

cout << "Shape C:" << endl;

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= (2 * i - 1); j++) {

cout << "*";

}
cout << endl;

cout << endl;

// Shape D

cout << "Shape D:" << endl;

for (int i = 1; i <= 5; i += 2) {

for (int j = 1; j <= i; j++) {

cout << "*";

cout << endl;

for (int i = 3; i >= 1; i -= 2) {

for (int j = 1; j <= i; j++) {

cout << "*";

cout << endl;

return 0;

11. Write a weather-calculator program that asks for a list of the previous 10
days’
temperatures, computes the average, and prints the results. You have to
compute the
total as the input occurs, then divide that total by 10 to find the average. Use
a while
loop for the 10 repetitions

#include <iostream>

using namespace std;


int main() {

double temperature, total = 0.0, average;

int day = 1;

// Ask the user to input temperatures for the last 10 days

while (day <= 10) {

cout << "Enter temperature for day " << day << ": ";

cin >> temperature;

// Add the entered temperature to the total

total += temperature;

day++; // Increment the day count

// Calculate the average temperature

average = total / 10;

// Display the results

cout << "\nTotal temperature for the last 10 days: " << total << endl;

cout << "Average temperature: " << average << endl;

return 0;

12. Write a C++ program using for loop that can compute the following
summation:
#include <iostream.h>

int main()

double sum=0;

// Use a for loop to compute the su

for(int i=1;i<=30;i++)

sum=sum+((i/3.0)*2);

cout<<"The sum of the series is:"<<sum<<endl;

return 0;

Write a C++ program that accepts marks of five students and then displays
their
average. The program should not accept mark which is less than 0 and mark
greater
than 100.
#include <iostream>

using namespace std;

int main() {

double marks[5]; // Array to store the marks of five students

double total = 0.0;

double average;

// Loop to get marks for five students


for (int i = 0; i < 5; i++) {

do {

cout << "Enter marks for student " << (i + 1) << " (between 0 and 100): ";

cin >> marks[i];

// Check if the entered mark is valid

if (marks[i] < 0 || marks[i] > 100) {

cout << "Invalid mark. Please enter a mark between 0 and 100." << endl;

} while (marks[i] < 0 || marks[i] > 100); // Keep asking for the mark until it's valid

total += marks[i]; // Add the mark to the total

// Calculate the average

Develop a calculator program that computes and displays the result of a


single
requested operation.
E.g. if the input is
15 * 20, then the program should display 15 * 20 equals 300
If the operator is not legal, as in the following example
24 ~ 25 then the program displays ~ is unrecognized operator
As a final example, if the denominator for a division is 0, as in the following
input: 23 / 0 then the program should display the following:
23 / 0 can’t be computed: denominator is 0.

#include <iostream>
using namespace std;

int main() {

double num1, num2;

char op;

// Ask the user for input

cout << "Enter a calculation (e.g., 15 * 20): ";

cin >> num1 >> op >> num2;

// Perform the operation based on the operator

if (op == '+') {

cout << num1 << " " << op << " " << num2 << " equals " << num1 + num2 << endl;

} else if (op == '-') {

cout << num1 << " " << op << " " << num2 << " equals " << num1 - num2 << endl;

} else if (op == '*') {

cout << num1 << " " << op << " " << num2 << " equals " << num1 * num2 << endl;

} else if (op == '/') {

// Handle division by zero

if (num2 == 0) {

cout << num1 << " " << op << " " << num2 << " can’t be computed: denominator is 0." << endl;

} else {

cout << num1 << " " << op << " " << num2 << " equals " << num1 / num2 << endl;

} else {

// Handle invalid operator

cout << op << " is unrecognized operator" << endl;

}
return 0;

Use either a switch or an if-else statement and display whether a vowel or a


consonant character is entered by the user. The program should work for
both lower
case and upper case letters.
#include <iostream>

using namespace std;

int main() {

char ch;

// Ask the user to enter a character

cout << "Enter a character: ";

cin >> ch;

// Check if the character is a letter

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {

// Check if the character is a vowel

if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch


== 'u' || ch == 'U') {

cout << ch << " is a vowel." << endl;

// If it's not a vowel, it must be a consonant

else {

cout << ch << " is a consonant." << endl;

} else {

cout << "Please enter a valid alphabet character." << endl;


}

return 0;

Write a C++ code to display only even numbers found between 0 and 20.
#include <iostream>

using namespace std;

int main() {

// Loop through numbers from 0 to 20

for (int i = 0; i <= 20; i++) {

// Check if the number is even

if (i % 2 == 0) {

cout << i << " "; // Display the even number

cout << endl; // End the line after displaying all even numbers

return 0;

Write a C++ application that extracts a day, month and year and
determine whether
the date is valid. If the program is given a valid date, an appropriate
message is
displayed. If instead the program is given an invalid date, an
explanatory message is
given. Note: to recognize whether the date is valid, we must be able
to determine
whether the year is a leap year or not.
An example of the expected input/output behavior for a valid date
follows
Please enter a date (dd mm yyyy) : 30 4 2006
30/4/2006 is a valid date
Please enter a date (dd mm yyyy) : 1 13 2006
Invalid month: 13
Please enter a date (dd mm yyyy) : 29 2 1899
Invalid day of month 29
If the year is a leap year, then February will have total of 29 days.
Otherwise, it
will have 28 days. If the year is not a century year and is evenly
divisible by 4,
then the year is a leap year. If the year is a century year (years
whose last digits
are 00) and is evenly divisible by 400, then the year is a leap year.
#include <iostream>

using namespace std;

// Function to check if a year is a leap year

bool isLeapYear(int year) {

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {

return true; // Leap year

} else {

return false; // Not a leap year

// Function to check if the date is valid

bool isValidDate(int day, int month, int year) {

// Check if the month is valid

if (month < 1 || month > 12) {

cout << "Invalid month: " << month << endl;

return false;

// Check if the day is valid for each month

int daysInMonth;
switch (month) {

case 1: case 3: case 5: case 7: case 8: case 10: case 12:

daysInMonth = 31; // January, March, May, July, August, October, December

break;

case 4: case 6: case 9: case 11:

daysInMonth = 30; // April, June, September, November

break;

case 2:

if (isLeapYear(year)) {

daysInMonth = 29; // February in a leap year

You might also like