MTN-103 Lab Assignment 3
Please use the concept of loops and decision-making control structures
to work out the following C++ programs.
1. Write a C++ program to check if an integer is a prime or a composite
number.
Solution:
// prime number is only divisible by 1 and itself
// composite number can have factors other than 1 and the number itself
#include <iostream>
using namespace std;
int main()
{
int number;
int i;
cout << "Enter the number" << endl;
cin >> number;
// loop from 1 to number
for(i=1;i<=number;i++)
{
if(i == 1) // skip when i = 1 as all numbers are divisible by 1
continue;
if(number%i == 0) // if number is divisible by i, break
break;
}
// if the number is only divisible by self
if(i == number)
cout << number << " is a prime number." << endl;
else
cout << number << " is a not prime number." << endl;
return 0;
}
2. Write a C++ program to check whether the entered character is a
vowel or consonant.
Solution:
// Note C++ is case sensitive
#include <iostream>
using namespace std;
int main()
{
char ch;
cout << "Enter the character: ";
cin >> ch;
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
cout << ch << " is a vowel." << endl;
break;
default:
cout << ch << " is a consonant." << endl;
}
return 0;
}
3. Write a C++ program that takes a positive integer from the user and
displays the value of the sum of n natural numbers in the series:
1+2+3+....+n.
Solution:
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter the value of n" << endl;
cin >> n;
int sum = 0;
for(int i = 1; i <= n; i++)
{
sum +=i;
}
cout << "sum of " << n << " natural numbers = " << sum << endl ;
return 0;
}
4. The factorial of a positive integer n equals to 1*2*3*...n. Write a C++
program to calculate 5! .
Solution:
#include <iostream>
using namespace std;
int main()
{
int n = 5;
int factorial = 1.0;
for(int i = 1; i <= n; i++)
{
factorial *= i; // factorial = factorial * i;
}
cout << "Factorial of " << n << " = " << factorial;
return 0;
}
5. Write a C++ program using nested loops to output the following 5-
lines pyramid pattern with stars.
[Hint: the number of star in a line is given by: 2*line number - 1]
*
***
*****
*******
*********
Solution:
// There are 5 lines in the pyramid. each line has (2*line number - 1) stars.
// We need a total of 3 loops - one outer loop to track the line;
//2 inner loops for spaces and stars to be printed on each line
#include <iostream>
using namespace std;
int main()
{
int line = 5;
int space = 5;
int star = 0;
int i,j,k;
// for loop for number of lines
for(i = 1; i<=5; i++)
{
space--;
star = (2*i) - 1;
j=0;
// nested while loop for no of spaces in each line
while(j < space)
{
cout << " ";
j++;
}
k = 0;
// nested while loop for no of stars in each line
while(k < star)
{
cout << "*";
k++;
}
cout << endl;
}
return 0;
}