C Revision

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

Revision

1. Write a function to Calculate n!. Then write a program to


calculate a!+b!+c! using this function

// with looping (no recursion)

int fact(int number)

int f = 1;

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

f = f * i;

return f;

// (with recursion)

int factorial(int n)

if (n == 1)

return 1;

return n * factorial(n - 1); // 4*3*2*1

int main()

int a, b, c, sum;
cout << "enter a ,b and c\n";

cin >> a >> b >> c;

sum = fact(a) + fact(b) + fact(c);

cout << "the sum = " << sum << endl;

2. Write a program to read 3 arrays(a,b,c) each array has 10


elements, Calculate and print sum of every two
arrays[a+b,b+c,a+c] Using 3 functions read,add,print

void read(int* arr)

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

//cin >> arr[i];

cin >> *(arr + i);

void add(int* arr1, int* arr2, int* arr12)

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

arr12[i] = arr1[i] + arr2[i];

// another soution

//*(arr12 + i) = *(arr1 + i) + *(arr2 + i);

// another solution

/*

*arr12 = *arr1 + *arr2;

arr1++;
arr2++;

arr12++;*/

void print(int* arr)

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

cout << arr[i] << endl;

int main()

int a[10], b[10], c[10], ab[10], bc[10], ac[10];

cout << "Enter array a \n";

read(a);

cout << "Enter array b \n";

read(b);

cout << "Enter array c \n";

read(c);

add(a, b, ab);

add(b, c, bc);

add(a, c, ac);

cout << "a+b array\n";

print(ab);

cout << "b+c array\n";

print(bc);

cout << "a+c array\n";


print(ac);

3. Write a program to read id(int) , score(float), and


grade(char) of 30 students using array of structure. the
program will find and print id of these students who get
scores greater than or equal to 50.

struct student

int id;

float score;

char grade;

};

int main()

student st[30];

for(int i=0;i<=29;i++)

cout<<"enter the info of the student"<<i+1<<" id - score -grade \n";

cin>>st[i].id>>st[i].score>>st[i].grade;

cout<<"The students with Score higher than or equal 50 \n";

for(int i=0;i<=29;i++)

if(st[i].score>=50)

cout<<st[i].id<<endl;

}
}

4. Write a function to swap two numbers. Write a program to


read 3 numbers sort these numbers an ascending order
using the previous function. Print the numbers after sorting

#include <iostream>

using namespace std;

void myswap(int*, int*); // Function declaration

int main(void)

int a, b, c;

cout << "Enter 3 integer numbers: ";

cin >> a >> b >> c;

if (a<b)

myswap(&a, &b);

if (a<c)

myswap(&a, &c);

if (b<c)

myswap(&b, &c);

cout << "Numbers after swapping " << c << ","

<< b << "," << a << endl;

return 0;

void myswap(int *num1, int *num2)

int temp;

temp = *num1;
*num1 = *num2;

*num2 = temp;

5. Define a structure person which has data members id, Birth


date (year, month, day), salary, and gender. Then write a
program to read data of 10 persons, sort them according to
the age

#include <iostream>

using namespace std;

struct person

int id;

int year , month , day;

int salary;

char gender;

};

int main()

struct person per[10] , temp; //temp structure

int age[10];

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

cout << "Enter id, Birth date(year,month,day) , salary and gendar of

person " << i + 1 << " : ";

cin >> per[i].id >> per[i].year >> per[i].month >> per[i].day >> per
[i].salary >> per[i].gender;

age[i] = per[i].year * 365 + per[i].month * 30 + per[i].day;

for (int i = 0; i < 9; i++)

for (int k = i+1; k < 10; k++)

if (age[i] > age[k])

temp = per[k];

per[k] = per[i];

per[i] = temp;

cout << "The Sorted Persons :" << endl;

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

cout << " Person " << i + 1 << endl<< per[i].id << endl << per[i].year

<< endl << per[i].month << endl << per[i].day << endl << per

[i].salary

<< endl << per[i].gender;

return 0;

6. Write a program to read a positive number and then test the


number is prime or not using function.
#include<iostream>

using namespace std;

int prime(int x);

int main()

int a;

cout << "Enter a Number";

cin >> a;

if (prime(a) == 0)

cout << "the number is prime \n";

else

cout << "the number is not prime \n";

return 0;

int prime(int x)

int flag = 0;

for (int i = 2; i <= x / 2; i++)

if (x%i == 0)

flag = 1;

return flag;

7. write a function to calculate the n power m using( Loop,


recursion)
#include <iostream>

using namespace std;

int powerrec(int x, int z);

int powerlp(int n, int m);

int main()

int h, n, m, lop, rec;

cout << "plz enter value of n and m \n ";

cin >> n >> m;

lop = powerlp(n, m);

rec = powerrec(n, m);

cout << "loop : " << lop << "\t" << "recursion : " << rec;

cin >> h;

return 0;

int powerrec(int n, int m) // Ex: 2^3 = 2*2*2

if (m == 1)

return n;

else

return (n * powerrec(n, m - 1)); // 2 * 2 * 2 --> 8

int powerlp(int x, int z) // 2^3

int p = 1;

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

p = p * x; // p = 2 * 2 * 2
}

return p;

8. Write a function to print the first 20 terms of the Fibonacci


series 0, 1, 1,2, 3, 5, 8, ..... using (Loops, Array, Recursion)

#include <iostream>

using namespace std;

//using loop

void fib();

int main() {

fib();

return 0;

// 0,1,1,2,3,5,8,...

void fib() {

int i, a = 0, b = 1, c;

cout << a << "," << b << ","

for (i = 3; i <= 10; i++) {

c = a + b;

cout << c << ",";

a = b;

b = c;

//using array

void fib();
int main() {

fib();

return 0;

void fib() {

int a[20], k;

a[0] = 0;

a[1] = 1;

cout << a[0] << "," << a[1] << ","

for (k = 2; k <= 19; k++) {

a[k] = a[k - 1] + a[k - 2];

cout << a[k] << ",";

//using recursion

int fib(int);

int main() {

int i;

for (i = 0; i <= 19; i++)

cout << fib(i) << ",";

return 0;

int fib(int n)

if (n == 0)
return 0;

else if (n == 1)

return 1;

else

return fib(n - 1) + fib(n - 2);

9. Define a structure has id (int ), dept (int), salary (float) . then write
five functions Read function to read id, dept, salary of 10 employees
using array of structure. Function to find the id of employee that
have the highest salary. Function to find the average salary of all
employees. Function to print counts of the employees who takes
salary greater than average & who takes salary less than average

#include <iostream>

using namespace std;

struct employees

int id;

int dept;

float salary;

};

struct employees emp[10];

void read()

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

cout << "Enter id, dept, salary of employee number " << i + 1 << " : ";

cin >> emp[i].id >> emp[i].dept >> emp[i].salary;

}
}

void highest()

int highs = 0, highid = 0;

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

if (emp[i].salary > highs)

highs = emp[i].salary;

highid = i;

cout << "The highest salary employee id is : " << emp[highid].id;

cout << endl;

float avg()

float sum = 0;

float avg = 0;

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

sum += emp[i].salary;

avg = sum / 10.0;

cout << "The average salary is : " << avg;

cout << endl;

return avg;

void counter()
{

float counterhigher = 0, counterlower = 0;

float average = avg();

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

if (emp[i].salary > average)

counterhigher++;

else

counterlower++;

cout << "The number of employees takes higher than average are : " <<

counterhigher

<< " and lower than average are : " << counterlower;

int main()

read();

highest();

avg();

counter();

return 0;

}
10.

Did your program compile? If so, what does it print? If not, what error message do you get?

Solu: not run, compilation error

11.

Did your program compile? If it does, what does the program output? If not, what error message
does it produce? Will run and get A
12. Write a program to add two matrices which are entered by user
and print the result and matrix. (Note: each matrix has dimensions
3x5)

Solution:
#include <iostream>
using namespace std;

int main()
{

int arr1[3][5];
int arr2[3][5];
cout << "plz enter the first matrix: ";
for (int i = 0; i < 3; i++)
{
cout << "enter the 5 elements for row no " << i << " : \n";
for (int j = 0; j < 5; j++)
{
cout << "element in the column no " << j << " : \n";
cin >> arr1[i][j];
}
}

cout << "\nthe first matrix is:\n";


for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 5; j++)
{
cout << arr1[i][j]<< "\t";
}
cout << "\n";
}

cout << "plz enter the second matrix: ";


for (int i = 0; i < 3; i++)
{
cout << "enter the 5 elements for row no " << i << " : \n";
for (int j = 0; j < 5; j++)
{
cout << "element in the column no " << j << " : \n";
cin >> arr2[i][j];
}
}

cout << "\nthe second matrix is:\n";


for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 5; j++)
{
cout << arr2[i][j] << "\t";
}
cout << "\n";
}

cout << "\nthe final matrix after summition: \n";


for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 5; j++)
{
arr1[i][j] = arr1[i][j]+arr2[i][j];
cout << arr1[i][j] << "\t";
}
cout << "\n";
}
}

13. Write a program to add numbers from A to B using function,


note: user will enter values of A and B.
#include<iostream>
using namespace std;
int Sum(int initial,int final)
{
int s=0;
for(int i=initial;i<=final;i=i+1)
{
s=s+i;
}
return s;
}

int main()
{int a, b;
cout<<"enter value of a and b";
cin>>a>>b;
int res=Sum(a,b);
cout<<"res="<<res;

return 0;
}
14. Consider the following C++ code. What is preventing it from compiling?
struct Employee {
int id;
float wage;
}

A string for name


A return value
A missing semicolon after last bracket
An instance variable

15. Given the following C++ structs, how would you set the value of the id in the Union
struct to 35?
struct Union {
int id;};
struct Employee {
Union aflcio;
long emp_id;
float rate;
};

Employee joe; joe.id = 35;


Employee joe; joe.aflcio = 35;
Employee joe; aflcio = 35;
Employee joe; joe.aflcio.id = 35;

16. What is the output of the following code:


a. #include <iostream> Solution:
using namespace std;
int main(void) { come
string s = "Welcome to C++"; codone
string t= "done"; wone
s=s.substr(3,4);
cout<<s<<endl;
s=s.replace(2,5,t);
cout<<s<<endl;
t= t.replace(0,1,"w");
cout << t;
return 0;
}

17. What is the output of the following code:

#include <iostream>
using namespace std;
int main() {
char *ptr,*ptr2,*ptr3;
char Str[] = "Have a nice day";
ptr = Str;
ptr += 7;
cout << ptr<<endl;
ptr2 = ptr+1;
cout << ptr2;
return 0;
}

Answer:
nice day
ice day
18. Write a program to read the string from the user and print its length, then
compare it with text “SoftwareTestingHelp”, then add .com to the text
“SoftwareTestingHelp”, finally print length of text as shown in the following
scenario:

Input the string: test sentence

String entered is: test sentence

Length of the string str is: 13

Two strings are not equal

New str1 after adding .com: SoftwareTestingHelp.com

str new length: 23

#include <iostream>

#include <string>

using namespace std;

int main() {

string str;

string target = "SoftwareTestingHelp";

// Input the string

cout << "Input the string: ";

getline(cin, str);

// Print the entered string


cout << "String entered is: " << str << endl;

// Calculate and print the length of the string

cout << "Length of the string str is: " << str.length() << endl;

// Compare with target string

if (str == target) {

cout << "Two strings are equal" << endl;

else {

cout << "Two strings are not equal" << endl;

// Append ".com" to target string and print the new string and its length

string str1 = target + ".com";

cout << "New str1 after adding .com: " << str1 << endl;

cout << "str1 new length: " << str1.length() << endl;

return 0;

19. Write a C++ program that will prompt the user to input n
integer values. The program will display the smallest and greatest of
those values.

int findMax(int arr[], int max, int size)


{
for (int i = 1; i < size; i++)
{
if (max < arr[i]) max = arr[i];
}
return max;
}
int findMin(int arr[], int min, int size)
{
for (int i = 1; i < size; i++)
{
if (min > arr[i]) min = arr[i];
}
return min;
}
int main()
{
int n;
cout << "enter n: ";
cin >> n;
int *arr;
arr = new int[n];

for (int i = 0; i < n; i++)


{
cin >> arr[i];
}
int max = findMax(arr, arr[0], n);
int min = findMin(arr, arr[0], n);

cout << "the max is: " << max;


cout << "the min is: " << min;
}

20.Write a program to call a function that print the reverse order of n numbers
using pointer.
#include <iostream>
#include <conio.h>

using namespace std;

void reverse(int *p,int size)


{
for(int i=size;i>=0;i--)
{
cout<<*(p+i)<<endl;
}
}
int main (){
int * array;
int n;
cout<<"please enter number of numbers";
cin>>n;
array= new int[n];
cout<<"Enter the array numbers";
for(int i=0;i<n;i++)
{
cin>>*(array+i);
}
reverse(array,n);

21. Tracing the following code and choose the right answer.
1. int a;
int* p;
a = 2;
p = &a;
a = a + 1;
cout << *p;
a) 2 b) 3 c) Won't run

2. int a;
int* p;
a = 2;
p = a;
a = a + 2;
cout << *p;
a) 2 b) 4 c) Won't run

3. int a;
int b;
int* p;
p = &a;
*p = 4;
p = &b;
*p = 3;
cout << a << “ “ << b;

a) 4 3 b) 3 3 c) Won't run

4. int a;
int b;
int* p;
int* q;
a = 3;
p = &a;
q = p;
*q = *q + 5;
cout << *p;
a) 8 b) 3 c) Won't run

5. int a;
int* p;
a = 4;
p = &a;
cout << (*p) / a;
a) 1 b) 4 c) Won't run

6. ref(int* p)
{(*p) = (*p) * 2;}
int main()
{
int a = 5;
ref(&a);
cout << a;
}

a) 5 b) 10 c) Won't work

7. int a;
int b;
int* p;
int* q;
a = 3;
p = &a;
q = p;
b = 4;
*q = b;
cout << *p << a;

a) 4 3 b) 3 4 c) 4 4

8. int a;
int* p;
a = 3;
p = &a;
cout << p;
a) 3 3 b) A memory address c) Won’t run

22. Choose the right answer

1. string* x, y;

a) x is a pointer to a string, y is a string


b) y is a pointer to a string, x is a string
c) both x and y are pointers to string types
d) y is a pointer to a string
ans a)

2. Which of the following is illegal?

a) int *ip;
b) string s, *sp = 0;
c) int i; double* dp = &i;
d) int *pi = 0;

ans: c)

3. What will happen in the following C++ code snippet?


int a = 100, b = 200;
int *p = &a, *q = &b;
p = q;

a) b is assigned to a
b) p now points to b
c) a is assigned to b
d) q now points to a

ans: b
Exam Solution:

Solution:
C++ Good

Wood

Solution : 7

#include <iostream>

using namespace std;


int main() {

int arr[] = {10, 20, 30, 40};

int* ptr = arr;

cout << *ptr << " "; // Line 1

ptr++;

cout << *ptr << " "; // Line 2

ptr += 2;

cout << *ptr << endl; // Line 3

return 0;

Solution :

Line 1: 10

Line 2: 20

Line 3: 40

#include <iostream>

using namespace std;

struct Student {

string name;

int age;

};

int main() {

Student s1 = {"Alice", 20};

Student* ptr = &s1;

cout << ptr->name << " "; // Line 1


cout << ptr->age << endl; // Line 2

return 0;

Solution:

Line 1: Alice

Line 2: 20
#include <iostream>

using namespace std;

int main() {

int a = 5;

int* ptr = &a;

if (*ptr > 3) {

cout << "Value is greater than 3" << endl;

} else {

cout << "Value is less than or equal to 3" << endl;

return 0;

Solution:

Value is greater than 3

#include <iostream>

using namespace std;

struct Book {

string title;

int pages;

};

int main() {

Book library[2] = {{"C++ Guide", 300}, {"Data Structures", 450}};

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


cout << library[i].title << " has " << library[i].pages << " pages." << endl;

return 0;

Solution:

C++ Guide has 300 pages.

Data Structures has 450 pages.

e. A structure in C++ can contain members of different data types. True

f. You cannot create a pointer that points to a structure in C++. False

g. An array in C++ must have all elements of the same data type. True

h. The while loop and do-while loop always execute the loop body at least once. False

i. The if statement must always be followed by an else block in C++. False

j. In C++, the + operator can be used to concatenate std::string objects. True


#include <iostream>

using namespace std;

// Function to add two arrays

void add(int* A, int* B, int* C, int N) {

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

C[i] = A[i] + B[i];

int main() {

int N;

// Input the size of the arrays

cout << "Enter the number of elements (N): ";

cin >> N;

// Dynamically allocate memory for arrays A, B, and C

int* A = new int[N];

int* B = new int[N];

int* C = new int[N];

// Input elements for array A

cout << "Enter elements of array A:" << endl;


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

cout << "A[" << i << "]: ";

cin >> A[i];

// Input elements for array B

cout << "Enter elements of array B:" << endl;

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

cout << "B[" << i << "]: ";

cin >> B[i];

// Call the add function

add(A, B, C, N);

// Display the contents of the new array C

cout << "The sum of arrays A and B is:" << endl;

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

cout << "C[" << i << "] = " << C[i] << endl;

// Free the dynamically allocated memory

delete[] A;

delete[] B;

delete[] C;

return 0;

}
#include <iostream>

using namespace std;

// Function to check if a number is prime

bool isPrime(int num) {

if (num <= 1) {

return false;

for (int i = 2; i * i <= num; i++) {

if (num % i == 0) {

return false;

return true;

int main() {

int n;

// Reading a positive number

cout << "Enter a positive number: ";

cin >> n;
// Check if the number is prime

if (isPrime(n)) {

cout << n << " is a prime number." << endl;

} else {

cout << n << " is not a prime number." << endl;

return 0;

1. Write a function to swap two integer numbers. Them write the


program to read 3 numbers, sort these numbers using the
previous function. Do not use loops or global variables in your
code.

#include <iostream>

using namespace std;

// Function to swap two integers

void swap(int& a, int& b) {

int temp = a;

a = b;

b = temp;

// Function to sort three numbers using the swap function


void sortThree(int& a, int& b, int& c) {

if (a > b) {

swap(a, b);

if (a > c) {

swap(a, c);

if (b > c) {

swap(b, c);

int main() {

int x, y, z;

// Reading three numbers

cout << "Enter three integers: ";

cin >> x >> y >> z;

// Sorting the numbers

sortThree(x, y, z);

// Display the sorted numbers

cout << "Sorted order: " << x << " " << y << " " << z << endl;

return 0;

You might also like