CS201P ASSIGNMENT 1 SOLUTION FALL 2023 | CS201P ASSIGNMENT 1 SOLUTION 2023 | CS201P ASSIGNMENT 1 2023 | INTRODUCTION TO PROGRAMMING (PRACTICAL) | VuTech
Visit Website For More Solutions
www.vutechofficial.blogspot.com
KINDLY, DON’T COPY PASTE
Question No. 1
Write a C++ program that performs the following tasks:
1- Store the first two alphabets of your Student ID in a variable and identify whether your study program is Bachelors or Masters using the following criteria.
Example:
- If ID is bc523456789 the output will be “Program Name: Bachelors”
- If ID is mc523456789 the output will be “Program Name: Masters”
- Otherwise the output will be “Program Name : Unknown”
2- Reverse only the digits of the Student ID using a loop and display the last two digits of the reversed ID.
For Example, the reverse of 523456789 is 987654325, the last digits (25) should be displayed.
3- Using the reversed ID, identify if the last digit is prime or not (use functions to implement this functionality).
For example, using the reversed ID 987654325, the last digit is 5 which is a prime number.
(Hint: A prime number is a whole number greater than 1 that cannot be exactly divided by any whole number other than itself and 1.)
Solution:
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
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(){
string studentID = "MC123456789";
string programName = studentID.substr(0,2);
if(programName == "BC"){
programName = "Bachelors";
}
else
if(programName == "MC"){
programName = "Masters";
}
else
{
programName = "Unknown";
}
string reversedID = "";
for(int i = studentID.length() - 1; i >= 2; i--){
reversedID += studentID[i];
}
string lastTwoDigits = reversedID.substr(reversedID.length() - 2);
int lastDigit;
stringstream ss(lastTwoDigits.substr(1));
ss>> lastDigit;
bool isPrimeNumber = isPrime(lastDigit);
cout<<"Student ID: "<< studentID<<endl;
cout<<"Program Name: "<< programName<<endl;
cout<<"Reversed ID: "<< studentID.substr(0,2)<<reversedID <<endl;
if(isPrimeNumber){
cout<<lastDigit<<" is a prime number." << endl;
}
else
{
cout<<lastDigit << " is not a prime number." << endl;
}
return 0;
}