You are on page 1of 75

Chapter 01

Arrays
Prepared By:
Dr. Murad Magableh
2013
One Dimensional

Q1: Write a program that declares two arrays of integers and fills them from the
user. Then exchanges their values and display the resulted two arrays.

Solution:

#include<iostream>
using namespace std;

void main()
{
int arr1[10], arr2[10];
cout << "Enter the first array values\n";
for (int i=0; i<10; i++)
cin >> arr1[i];
cout << "Enter the second array values\n";
for (int i=0; i<10; i++)
cin >> arr2[i];

int temp;
for (int i=0; i<10; i++)
{
temp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = temp;
}

cout << "The first array values now are:\n";


for (int i=0; i<10; i++)
cout << arr1[i] << " ";
cout << endl;

cout << "The second array values now are:\n";


for (int i=0; i<10; i++)
cout << arr2[i] << " ";
cout << endl;
}

2|Page
Q2: Write a program that takes 10 integers as input and prints the largest integer
and its location in the array.

Solution:

#include<iostream>
using namespace std;

void main()
{
int arr[10];
cout << "Enter the array values\n";
for (int i=0; i<10; i++)
cin >> arr[i];

int max = arr[0], loc = 0, i;


for (i=1; i<10; i++)
{
if (arr[i] > max)
{
max = arr[i];
loc = i;
}

cout << "The maximum value is: " << max


<< " and it is in location " << loc << endl;

3|Page
Q3: Write a program that defines a one dimensional array of integers of size 10 and
fill it from the user. Then find the negative values and store them in another array
and display new array.

Solution:

#include<iostream>
using namespace std;

void main()
{
int arr[10];
cout << "Enter the array values\n";
for (int i=0; i<10; i++)
cin >> arr[i];

int new_arr[10], index = 0;


for (int i=0; i<10; i++)
if (arr[i] < 0)
new_arr[index++] = arr[i];

cout << "The new array values are:\n";


for (int i=0; i<index; i++)
cout << new_arr[i] << " ";
cout << endl;
}

4|Page
Q4: Write a program that defines a one dimensional array of integers of size 11 and
fill the first 10 values from the user. Then calculate the summation of the 10 values
and store it in the 11th location.

Solution:

#include<iostream>
using namespace std;

void main()
{
int arr[11];
arr[10] = 0;
cout << "Enter the array values\n";
for (int i=0; i<10; i++)
{
cin >> arr[i];
arr[10] += arr[i];
}

cout << "The new array values are:\n";


for (int i=0; i<11; i++)
cout << arr[i] << " ";
cout << endl;
}

5|Page
Q5: Write a C++ program that reverses the order of a one-dimensional array of size
10 without using another array.

Solution:

#include<iostream>
using namespace std;

void main()
{
int x, j=9, a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

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


x = a[i];
a[i] = a[j];
a[j] = x;
j--;
}

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


cout << a[i] << " ";
cout << endl;
}

6|Page
Q6: Write a C++ program that declares two arrays of size 5. Read the first array from
the user and store the factorial of each element in this array in its corresponding
location in the second array.

Solution:

#include<iostream>
using namespace std;

void main()
{
double a[5], b[5];
int fact;
cout << "Enter the first array values\n";
for(int i=0; i<5; i++)
{
cin >> a[i];
fact = 1;
for(int j=1; j<=a[i]; j++)
fact *= j;
b[i] = fact;
}

cout << "The factorials array values are:\n";


for (int i=0; i<5; i++)
cout << b[i] << " ";
cout << endl;
}

7|Page
Two Dimensional

Q7: Write a program that adds up two [4x4] arrays and stores the sum in a third
array.

Solution:

#include<iostream>
using namespace std;

void main()
{
int a[4][4], b[4][4];
cout << "Enter the first array values\n";
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
cin >> a[i][j];

cout << "Enter the second array values\n";


for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
cin >> b[i][j];

int c[4][4];
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
c[i][j] = a[i][j] + b[i][j];

cout << "The array values are:\n";


for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
cout << c[i][j] << " ";
cout << endl;
}
cout << endl;
}

8|Page
Q8: Write a C++ program that declares a two dimensional array of size [4x4] and
generates the values of its elements using conditional statements as the following:

The main diagonal contains 0 in all its locations


The upper triangle contains 1 in all its locations
The lower triangle contains 2 in all its locations

Solution:

#include<iostream>
using namespace std;

void main(){
int a[4][4];
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
{
if(i<j) a[i][j] = 1;
else if (i==j) a[i][j] = 0;
else a[i][j] = 2;
}

cout << "The array values are:\n";


for(int i=0; i<4; i++)
{
for(int j=0; j<4; j++)
cout << a[i][j] << " ";
cout << endl;
}
cout << endl;
}

9|Page
Q9: Write a program that defines a two-dimensional array of integers of size 4*4.
The program will fill the array of values using the equation array_name[i][j]
= i+j+2 (i refers to the row index, j refers to the column index). Then, define a
one-dimensional array of size 4. The one-dimensional array should be filled with the
values along the main diagonal of the two-dimensional array.

For example:

If the two-dimensional array is:

V1 V2 V3 V4

V5 V6 V7 V8

V9 V10 V11 V12

V13 V14 V15 V16

The one-dimensional array will be:

V1 V6 V11 V16

Solution:

#include <iostream>
using namespace std;

void main(){
int a[4][4];
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
a[i][j] = i+j+2;
int b[4], index=0;
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
if(i==j)
{
b[index] = a[i][j];
index++;
}
}

10 | P a g e
Q10: Write a program that defines a two-dimensional array of integers of size 10*10.
The program will fill each location of the array by its index summation (array[i][j] =
i+j). Then print the summation of the elements on the array circumference as shown
below:

Solution:

#include <iostream>
using namespace std;

void main(){
int a[4][4];
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
a[i][j] = i+j;
int sum = 0;
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
if(i==0 || j==0 || i==9 || j==9)
sum += a[i][j];

cout << "The result is: " << sum << endl;
}

11 | P a g e
Q11: Write a program that stores the grades of 5 students in a two-dimensional
array. Each student has 3 marks. Each row will represent a student and the last cell in
the row will store the calculated average for the student's marks. Finally, display the
average of all student averages.

Solution:
#include <iostream>
using namespace std;

void main(){
float a[5][4], sum;
for(int i=0; i<5; i++)
{
sum = 0;
cout << "Enter the 3 marks for the
student number: " << i+1 << endl;
for(int j=0; j<3; j++)
{
cin >> a[i][j];
sum += a[i][j];
}
a[i][3] = sum/3;
}

cout << "The students marks and averages are:"


<< endl;
for(int i=0; i<5; i++)
{
for(int j=0; j<4; j++)
cout << a[i][j] << " ";
cout << endl;
}
cout << endl;

sum = 0;
for(int i=0; i<5; i++)
sum += a[i][3];

cout << "The AVG for all sudents is: "


<< (float)sum/5 << endl;
}

12 | P a g e
Chapter 02

Functions
Prepared By:
Dr. Murad Magableh
2013

13 | P a g e
Q1: Write a program to take a depth (in kilometers) inside the earth as input data;
compute and display the temperature at this depth in degrees Celsius and degrees
Fahrenheit, The relevant formulas are:

Celsius = 10 (depth) + 20
Fahrenheit = 1.8 (Celsius) + 32

Include two functions in your program:

1. Function celsius_at_depth should compute and return the Celsius temperature at a


depth measured in kilometers.
2. Function fahrenheit should convert a Celsius temperature to Fahrenheit.

Solution:

#include <iostream>
using namespace std;

float celsius_at_depth(float depth)


{
return ( 10 * depth + 20);
}

float fehrenheit(float celsius)


{
return ( 1.8 * celsius + 32);
}

void main()
{

float depth, celsius;


cout << "Enter the depth inside the earth:\n";
cin >> depth;
celsius = celsius_at_depth(depth);
cout << "The temperature at this depth in degree Celsius is: "
<< celsius << endl;
cout << "The temperature at this depth in degree Fehrenheit is: "
<< fehrenheit(celsius) << endl;
}

14 | P a g e
Q2: Write a program to find the following using functions:

1. Sphere surface area (4 r2)


2. Sphere volume (4/3 r3)

NOTE: Use functions to find powers of the radius

Solution:

#include <iostream>
using namespace std;

float power2(float radius)


{
return ( radius * radius);
}

float power3(float radius)


{
return ( radius * radius * radius);
}
float surface_area(float radius)
{
return ( 4 * 3.14 * power2(radius));
}

float volume(float radius)


{
return ( 4.0/3.0 * 3.14 * power3(radius));
}

void main()
{
float radius;
cout << "Enter the radius of the sphere: ";
cin >> radius;
cout << "The surface area is: " << surface_area(radius) << endl;
cout << "The volume is: " << volume(radius) << endl;

15 | P a g e
Q3: Write a program (using a function) that takes a positive number with a fractional part
and rounds it to two decimal places. For example, 32.4851 would round to 32.49, and
32.4431 would round to 32.44

Solution:

#include <iostream>
using namespace std;

float round(float number)


{
int num = number * 100;
if ( (number*100-num) >= 0.5) num++;
return num/100.0;
}

void main()
{
float number;
cout << "Enter a number: ";
cin >> number;
cout << "The round to two decimal places is: "
<< round(number) << endl;
}

16 | P a g e
Q4: Write a program (using a function) that takes a positive integer number and displays
PRIME if the number is prime and NOT PRIME otherwise.

NOTE: a prime number is an integer that has no integral factors but itself and 1

Solution:

#include <iostream>
using namespace std;

void isPrime(int x)
{
int flag = 0;
for(int i=1; i<=x; i++)
if(x%i==0) flag++;
if(flag<=2) cout << "Prime" << endl;
else cout << "Not Prime" << endl;
}

void main()
{
int number;
cout << "Enter a number: ";
cin >> number;
isPrime(number);
}

17 | P a g e
Q5: Write a function that takes a positive integer number and returns TRUE if the number
is prime and FALSE otherwise. Use the function in the main to display PRIME if the number
is prime and NOT PRIME otherwise.

NOTE: a prime number is an integer that has no integral factors but itself and 1

Solution:

#include <iostream>
using namespace std;

bool isPrime(int x)
{
int flag = 0;
for(int i=1; i<=x; i++)
if(x%i==0) flag++;
if(flag<=2) return true;

return false; // "else" is not necessary here. WHY???


}

void main()
{
int number;
cout << "Enter a number: ";
cin >> number;
if(isPrime(number)) cout << "Prime" << endl;
else cout << "Not Prime" << endl;
}

18 | P a g e
Q6: Write a function that displays the perfect numbers between 1 and 1000.

NOTE: A perfect number is a positive integer that is equal to the sum of its positive integral
factors, including 1 but excluding itself.

Solution:

#include <iostream>
using namespace std;

bool isPerfect(int x)
{
int flag = 0;
for(int j=1; j<x; j++)
if(x%j==0) flag += j;
if(flag == x) return true;
else return false; // You can omit the "else" keyword
}

void perfect_list()
{
int sum = 0, index = 1;
for(int i=1; i<=1000; i++)
if(isPerfect(i))
cout << "Perfect number no. " << index++ << " is: "
<< i << endl;
}

void main()
{
perfect_list();
}

19 | P a g e
Q7: Write a function that takes a salary of an employee and increases it by 100 (Just to
introduce the concept of Call-By-Reference).

Solution 01 (Call-By-Reference):

#include <iostream>
using namespace std;

void sal_inc(int &sal)


{
sal += 100;
}

void main()
{
int salary;
cout << "Enter a salary: " ;
cin >> salary;
sal_inc(salary);
cout << "The salary after the increment is: " << salary << endl;
}

Solution 01 (Call-By-Value):

#include <iostream>
using namespace std;

int sal_inc(int sal)


{
return sal + 100;
}

void main()
{
int salary;
cout << "Enter a salary: " ;
cin >> salary;
salary = sal_inc(salary);
cout << "The salary after the increment is: " << salary << endl;
}

20 | P a g e
Q8: Write a function that takes a one-dimensional array and its size, and then fill each
location in the array by the factorial of the location's index.

NOTE: The factorial of an integer number is the product of that integer and all the integers
below it.

Solution:

#include <iostream>
using namespace std;

int fact(int x)
{
int f = 1;
for(int j=1; j<=x; j++)
f *= j;
return f;
}

void fill_array(int a[], int size)


{
a[0] = 1; // The factorial of Zero is 1
for(int i=1; i<size; i++)
a[i] = fact(i);
}

void main()
{
int a[5] = {2, 4, 1, 9, -3};
cout << "The array before calling the function: " << endl;
for(int i=0; i<5; i++)
cout << a[i] << " ";

fill_array(a, 5);

cout << "\nThe array after calling the function: " << endl;
for(int i=0; i<5; i++)
cout << a[i] << " ";
}

21 | P a g e
Q9: Write a function that takes a one-dimensional array and its size, and then returns the
summation of prime numbers in the array.

Solution:

#include <iostream>
using namespace std;

bool isPrime(int x)
{
int flag = 0;
for(int i=1; i<=x; i++)
if(x%i==0) flag++;
if(flag<=2) return true;

return false; // "else" is not necessary here. WHY???


}

int array_sum(int a[], int size)


{
int sum = 0;
for(int i=0; i<size; i++)
if(isPrime(a[i])) sum += a[i];
return sum;
}

void main()
{
int arr[10] = {1, 2, 3, 17, 5, 4, 8, 11, 20, 30};
cout << "The summation of prime numbers in this array is: "
<< array_sum(arr, 10) << endl;
}

22 | P a g e
Chapter 03

Pointers
Prepared By:
Dr. Murad Magableh
2013

23 | P a g e
Q1: Write the output of the following code:

#include<iostream>
using namespace std;

void main()
{
int a = 8;
int b = 4;
int *p, *q;
p = &a;
q = &b;
cout << a << " " << b << " "
<< *p << " " << *q << endl;
*p+=12;
a++;
cout << a << " " << b << " "
<< *p << " " << *q << endl;
*p = 100;
*q = 200;
cout << a << " " << b << " "
<< *p << " " << *q << endl;
int * t;
t = q;
q = p;
p = t;
cout << a << " " << b << " "
<< *p << " " << *q << endl;
t = &a;
p = t;
q = t;
cout << a << " " << b << " "
<< *p << " " << *q << endl;
}

Solution:

8 4 8 4

21 4 21 4

100 200 100 200

100 200 200 100

100 200 100 100

24 | P a g e
Q2: Write the output of the following code:

#include<iostream>
using namespace std;
void main()
{
int a[5] = {2, 4, 6, 8, 10};
int *p;
p = a;
if(a==p) p++;
cout << *p << endl;
p+=3;
cout << *p << endl;
for(int i=100; i<105; i++)
{
cout << *p << " ";
--p;
}
cout << endl;
p = a;
for(int i=0; i<5; i++)
cout << p[i] << " ";
cout << endl;
for(int i=0; i<5; i++)
cout << a[i] << " ";
cout << endl;
for(int i=4; i>=0; i--)
cout << *(p+i) << " ";
cout << endl;
for(int i=1; i<5; i+=2)
cout << *(p+i) << " ";
cout << endl;
for(int i=0; i<5; i++)
cout << *p << " ";
cout << endl;
}

Solution:
4

10

10 8 6 4 2

2 4 6 8 10

2 4 6 8 10

10 8 6 4 2

4 8

2 2 2 2 2

25 | P a g e
Q3: Write a program that reads a size of a one-dimensional array from the user. The
size will be passed to a function that creates an array of this size. The function will
also fill the array elements with the square of each element's index. Finally, the
function will print the array.

Solution:

#include<iostream>
using namespace std;

void dynamic_array_size(int size)


{
int *arr = new int[size];
for(int i=0; i<size; i++)
arr[i] = i*i;
for(int i=0; i<size; i++)
cout << arr[i] << " ";
cout << endl;
}

void main()
{
int s;
cout << "Please insert the array size: ";
cin >> s;
dynamic_array_size(s);
}

26 | P a g e
Q4: Write a program that reads 10 integers from the user and stores them in a one-
dimensional array. Then, store the odd values in another array. The size of the new
array should be exactly the same as the number of the odd values (No empty
locations is allowed in the new array).

Solution:

#include<iostream>
using namespace std;

void main()
{
int a[10];
int count = 0;
cout << "Please enter 10 values:" << endl;
for(int i=0; i<10; i++)
{
cin >> a[i];
if(a[i]%2==1) count++;
}
int *new_arr = new int[count];
int index = 0;
for(int i=0; i<10; i++)
if(a[i]%2==1)
new_arr[index++] = a[i];

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


cout << new_arr[i] << " ";
cout << endl;
}

27 | P a g e
Q5: Write the output of the following code:

#include<iostream>
using namespace std;

void main()
{
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int *front, *rear;
front = a; // OR front = &a[0];
rear = &a[9];
while(front<=rear)
{
int t = *front;
*front = *rear;
*rear = t;
rear--;
front++;
}
for(int i=0; i<10; i++)
cout << a[i] << " ";
cout << endl;
}

Solution:
10 9 8 7 6 5 4 3 2 1

28 | P a g e
Chapter 04

Recursion
Prepared By:
Dr. Murad Magableh
2013

29 | P a g e
Q1: Write a recursive function that prints the numbers between 1 to n.

Solution:

#include<iostream>
using namespace std;

void print_numbers(int n)
{
if(n>1) print_numbers(n-1);
cout << n << " ";
}

void main()
{
int num;
cout << "Please insert the number (n): ";
cin >> num;
print_numbers(num);
cout << endl;
}

30 | P a g e
Q2: Write a recursive function that prints the numbers between 1 to n in a reverse
order.

Solution:

#include<iostream>
using namespace std;

void print_numbers(int n)
{
cout << n << " ";
if(n>1) print_numbers(n-1);
}

void main()
{
int num;
cout << "Please insert the number (n): ";
cin >> num;
print_numbers(num);
cout << endl;
}

31 | P a g e
Q3: What is the output of the following code:

#include<iostream>
using namespace std;

void print_numbers(int n)
{
cout << n << " ";
if(n>1) print_numbers(n-1);
cout << n << " ";
}

void main()
{
print_numbers(5);
cout << endl;
}

Solution:

5 4 3 2 1 1 2 3 4 5

32 | P a g e
Q4: Write a recursive function that prints the following shape:

Solution:

#include<iostream>
using namespace std;

void print_stars(int n)
{
if(n>1) print_stars(n-1);
for(int i=1; i<=n; i++)
cout << "*";
cout << endl;
}

void main()
{
print_stars(5);
cout << endl;
}

33 | P a g e
Q5: Write a recursive function that prints the following shape:

Solution:

#include<iostream>
using namespace std;

void print_stars(int n)
{
for(int i=1; i<=n; i++)
cout << "*";
cout << endl;
if(n>1) print_stars(n-1);
}

void main()
{
print_stars(5);
cout << endl;
}

34 | P a g e
Q6: What is the output of the following code:

#include<iostream>
using namespace std;

int global = 5;

void print_stars(int n)
{
for(int i=1; i<=(global-n); i++)
cout << "*";
cout << endl;
if(n>=1) print_stars(n-1);
for(int i=1; i<=(global-n); i++)
cout << "*";
cout << endl;
}

void main()
{
print_stars(4);
cout << endl;
}

Solution:

35 | P a g e
Q7: Write a recursive function that calculates and returns the factorial of a number
x.

Solution:

#include<iostream>
using namespace std;

int fact(int x)
{
if(x==1) return 1;
return x*fact(x-1);
}

void main()
{
cout << fact(5) << endl;
}

36 | P a g e
Q8: Write a recursive function that receives a one-dimensional array and reverses
the order of its elements.

Solution:

#include<iostream>
using namespace std;

void reverse_array(int a[], int front, int rear)


{
if(front<(rear-1)) reverse_array(a, front+1, rear-1);
int t = a[front];
a[front] = a[rear];
a[rear] = t;
}

void main()
{
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(int i=0; i<10; i++)
cout << arr[i] << " ";
cout << endl;

reverse_array(arr, 0, 9);

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


cout << arr[i] << " ";
cout << endl;
}

37 | P a g e
Q9: What is the output of the following code:

#include<iostream>
using namespace std;

void reverse_array(int a[], int front, int rear, int


size)
{
if(front<(rear-1)) reverse_array(a,front+1,rear-1,size);
int t = a[front];
a[front] = a[rear];
a[rear] = t;
for(int i=0; i<size; i++)
cout << a[i] << " ";
cout << endl;
}

void main()
{
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
reverse_array(arr, 0, 9, 10);
}

Solution:

1 2 3 4 6 5 7 8 9 10

1 2 3 7 6 5 4 8 9 10

1 2 8 7 6 5 4 3 9 10

1 9 8 7 6 5 4 3 2 10

10 9 8 7 6 5 4 3 2 1

38 | P a g e
Q10: Write the following function in a recursive way:

int power(int x, int y)


{
int result = x;
for(int i=1; i<y; i++)
result *= x;
return result;
}

Solution:

#include<iostream>
using namespace std;

int power(int x, int y)


{
if(y==1) return x;
return x*power(x, y-1);
}

void main()
{
cout << power(2, 3) << endl;
}

39 | P a g e
Chapter 05

Strings
Prepared By:
Dr. Murad Magableh
2013

40 | P a g e
Q1: Write a function that receives a string and returns its length without using the
strlen function.

Solution:

#include<iostream>
using namespace std;

int my_strlen(char *s)


{
int c = 0;
while(s[c] != '\0') c++;
return c;
}

void main()
{
char *s1 = "Philadelphia University";
cout << my_strlen(s1) << endl;
}

41 | P a g e
Q2: Write a function that does the same as the function strcat.

Solution:

#include<iostream>
#include<cstring>
using namespace std;

char* my_strcat(char *s1, char *s2)


{
int s2_index = 0;
int len = strlen(s1)+strlen(s2);

for(int i=strlen(s1); i<len; i++)


s1[i] = s2[s2_index++];
return s1;
}

void main()
{
char s1[100] = "Philadelphia";
char s2[100] = "University";
cout << my_strcat(s1, s2) << endl;
}

42 | P a g e
Q3: Write a function that does the same as the function strcpy.

Solution:

#include<iostream>
#include<cstring>
using namespace std;

char* my_strcpy(char *s1, char *s2)


{
int i;
for(i=0; i<strlen(s2); i++)
s1[i] = s2[i];
s1[i] = '\0';
return s1;
}

void main()
{
char s1[100] = "Philadelphia";
char s2[100] = "University";
cout << my_strcpy(s1, s2) << endl;
}

43 | P a g e
Q4: Write a function that does the same as the function strcmp.

Solution:

#include<iostream>
#include<cstring>
using namespace std;

int min(int x, int y)


{
if(x<y) return x;
else return y; // Without "else" is OK here
}

int my_strcmp(char *s1, char *s2)


{

for(int i=0; i<min(strlen(s1), strlen(s2)); i++)


if(s1[i]<s2[i]) return -1;
else if (s1[i]>s2[i]) return 1;
if(strlen(s1)<strlen(s2)) return -1;
else if(strlen(s1)>strlen(s2)) return 1;
return 0;
}

void main()
{ // s1 = s2
char *s1 = "ABC";
char *s2 = "ABC";
cout << my_strcmp(s1, s2) << endl;
// s1 < s2
s1 = "ABB";
s2 = "ABC";
cout << my_strcmp(s1, s2) << endl;
// s1 > s2
s1 = "ABC";
s2 = "ABB";
cout << my_strcmp(s1, s2) << endl;
// s1 < s2
s1 = "ABC";
s2 = "ABCD";
cout << my_strcmp(s1, s2) << endl;
// s1 > s2
s1 = "ABCD";
s2 = "ABC";
cout << my_strcmp(s1, s2) << endl;
}

44 | P a g e
Exercises:
1. Write a function that does the same as the function strncat

Solution:

#include<iostream>
#include<cstring>
using namespace std;

char* my_strncat(char *s1, char *s2, int n)


{
int s2_index = 0;
int len = strlen(s1)+n;
for(int i=strlen(s1); i<len; i++)
{
s1[i] = s2[s2_index++];
cout <<"i="<<i<<endl;
}
return s1;
}

void main()
{
char s1[100] = "Philadelphia";
char s2[100] = "University";

int n;
cin >>n;
cout << my_strncat(s1, s2, n) << endl;

2. Write a function that does the same as the function strncpy

Solution

#include<iostream>
#include<cstring>
using namespace std;

char* my_strncpy(char *s1, char *s2, int n)


{
int i;
int len = strlen (s1);
for(i=0; i<n; i++)

45 | P a g e
s1[i] = s2[i];

if (n> len)
s1[i] = '\0';
return s1;
}

void main()
{
char s1[100] = "Philadelphia";
char s2[100] = "University";
int n;
cin >> n;
cout << my_strncpy(s1, s2, n) << endl;

3. Write a function that does the same as the function strncmp

Solution

#include<iostream>

#include<cstring>

using namespace std;

int my_strncmp(char *s1, char *s2, int n)

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

if(s1[i]<s2[i]) return -1;

else if (s1[i]>s2[i]) return 1;

return 0;

46 | P a g e
void main()

{ // s1 = s2

char *s1 = "ABC";

char *s2 = "ABC";

int n;

cin >> n;

cout << my_strncmp(s1, s2, n) << endl;

// s1 < s2

s1 = "ACB";

s2 = "ABC";

cout << my_strncmp(s1, s2, n) << endl;

// s1 > s2

s1 = "CBA";

s2 = "ABB";

cout << my_strncmp(s1, s2, n) << endl;

// s1 < s2

s1 = "ABB";

s2 = "ABBD";

cout << my_strncmp(s1, s2, n) << endl;

// s1 > s2

s1 = "ABCD";

s2 = "ABC";

cout << my_strncmp(s1, s2, n) << endl;

47 | P a g e
Chapter 06

File
Processing
Prepared By:
Dr. Murad Magableh
2013
48 | P a g e
Q1: Write a program that copies a content of a file into a one-dimensional array.
Assume that the content of the file is integers.

Solution:

#include<iostream>
#include<fstream>
using namespace std;

void main()
{
int x, c=0;
ifstream fin1("d:\\test.txt", ios::in);
while(fin1>>x)
c++;

ifstream fin2("d:\\test.txt", ios::in);


int *a = new int[c];
for(int i=0; i<c; i++)
fin2 >> a[i];
// To print the content of the array
for(int i=0; i<c; i++)
cout << a[i] << endl;
}

49 | P a g e
Q2: Write a program that copies a content of a one file into another file. Assume
that the content of the file is integers.

Solution:
#include<iostream>
#include<fstream>
using namespace std;

void main()
{
int x;
ifstream fin("d:\\file_01.txt", ios::in);
ofstream fout("d:\\file_02.txt", ios::out);
while(fin>>x) fout << x << endl;
}

50 | P a g e
Q3: Write a program that copies a content of a one file into another file in a reverse
order. Assume that the content of the file is integers.

Solution:
#include<iostream>
#include<fstream>
using namespace std;

void main()
{
int x, c=0;
ifstream fin1("d:\\file_01.txt", ios::in);
while(fin1>>x)
c++;
// First, copy the file_01 into an array first
ifstream fin2("d:\\file_01.txt", ios::in);
int *a = new int[c];
for(int i=0; i<c; i++)
fin2 >> a[i];
// Then copy the array in reverse order into file_02
ofstream fout("d:\\file_02.txt", ios::out);
for(int i=c-1; i>=0; i--)
fout << a[i] << endl;
}

51 | P a g e
Q4: Assuming that a file contains integer numbers, write a program that reads these
values and calculates the following:

1. The maximum value


2. The minimum value
3. The average of all values
4. How many prime numbers are in the file
5. How many perfect numbers are in the file
6. How many odd values are in the file
7. How many even values are in the file
8. How many negative values are in the file
9. The summation of the positive values
10. The summation of the even negative numbers

Solution:
#include<iostream>
#include<fstream>
using namespace std;

bool isPrime(int num)


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

bool isPerfect(int num)


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

void main()
{
int x;
int counter = 0;
int min, max, avg, sum = 0;
int prime_counter = 0, perfect_counter = 0;
int odd_counter = 0, even_counter = 0, negative_counter = 0;
int positive_sum = 0, even_negative_sum = 0;

52 | P a g e
ifstream fin("d:\\test.txt", ios::in);
while(fin>>x)
{
if(counter==0)
{
min = x;
max = x;
}
else
{
if(x<min) min = x;
if(x>max) max = x;
}

if(isPrime(x)) prime_counter++;
if(isPerfect(x)) perfect_counter++;

if(x%2==0) even_counter++;
else odd_counter++;

if(x<0)
{
negative_counter++;
if(x%2==0) even_negative_sum += x;
}
else positive_sum += x;

sum += x;
counter++;
}

cout << "Max is: " << max << endl;


cout << "Min is: " << min << endl;
cout << "AVG is: " << (float)sum/counter << endl;
cout << "There is " << prime_counter << " prime number(s)"
<< endl;
cout << "There is " << perfect_counter << " perfect number(s)"
<< endl;
cout << "There is " << even_counter << " even number(s)"
<< endl;
cout << "There is " << odd_counter << " odd number(s)" << endl;
cout << "There is " << negative_counter
<< " negative number(s)" << endl;
cout << "The summation of the positive number(s) is: "
<< positive_sum << endl;
cout << "The summation of the even negative number(s) is: "
<< even_negative_sum << endl;
}

53 | P a g e
Structures
Question: Write a C++ program to do the following:

- Set up a structure/record to store products; each product has a name, a model


number and a price.
- Choose appropriate types for these fields.
- Your program should contain a loop which allows entry via the keyboard of
up to 10 products, to be stored in an array.
- The loop can be stopped by entry of "quit" for the product name
- Your program should include a function to display all the products details after
the entry loop has finished.

Solution

#include<iostream>

#include<cstring>

using namespace std;

struct products

string name;

string model;

float price;

};

void printprod(products a[], int i)

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

54 | P a g e
cout <<a[j].name;

cout <<a[j].model;

cout <<a[j].price;

void main ()

products p[10];

cout<<"Enter up to 10 products, when finished, enter quit"<<endl;

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

cout<<"Enter name"<<endl;

cin.getline (p[i].name, 50);

if (p[i].name == "quit")

break;

cout<<"Enter model"<<endl;

cin>> p[i].model;

cout<<"Enter price"<<endl;

cin>> p[i].price;

printprod (p, i);

55 | P a g e
Philadelphia University Faculty of Information Technology

Lecturer : Dr. Raad Alwan Department of CS

Lab Instructor : Eman Alnaji Examination Paper

First Exam

Question1: Write a C++ program that declares a 4X4 array, and fill it as displayed in the
figure below: [3 Marks]

$ # # *
# $ * #
# * $ #
* # # $

Print the resulted array as an output, displayed row by row.

Solution

#include<iostream>

#include<cstring>

using namespace std;

void main ()

char A[4][4];

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

for (int j=0; j<4; j++)

if (i==j)

A[i][j] = '$';

else if (i+j == 3)

A[i][j] = '*';

56 | P a g e
else

A[i][j] = '#';

cout << A[i][j];

cout <<endl;

Question2:

Write a C++ program, that computes the area of a square, or a rectangle according to the
user request. (i.e. the user inputs 's' for square or 'r' for rectangle). Pass this character to a
function that accordingly ask the user for further information to complete its calculations,
and returns the computed area to the main program, where the output is displayed.

Hint: Square area = width * width

Rectangle area = width * height

Solution

#include<iostream>

#include<cstring>

using namespace std;

int area (char shape)

int width, height;

if (shape == 's')

cout << "Enter Width"<<endl;

cin >> width;

return width*width;

else if (shape == 'r')

57 | P a g e
{

cout << "Enter Width and Height"<< endl;

cin >> width>> height;

return width * height;

else

return 0;

void main ()

char shape;

cout << "Enter s for square, and r for rectangle"<<endl;

cin>> shape;

cout << "area = "<< area(shape);

58 | P a g e
Philadelphia University Faculty of Information Technology

Lecturer : Miss Hanan Hardan Department of CS

Lab Instructor : Mrs. Eman Alnaji Examination Paper

Question1: Write a C++ program that declares a 5X5 array, and fill it as displayed in the
figure below: [3 Marks]

Z Z Z Z Z
Z
Z
Z
Z Z Z Z Z
Print the resulted array as an output, displayed row by row.

Solution

#include<iostream>

#include<cstring>

using namespace std;

void main ()

char A[5][5];

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

for (int j=0; j<5; j++)

if ((i+j == 4)||(i==0)||(i==4))

A[i][j] = 'Z';

else

A[i][j] = ' ';

59 | P a g e
cout << A[i][j];

cout <<endl;

Question2: [3 Marks]

A manager of a sports equipment store has decided to apply discounts on certain items in
the sale season. Write a C++ program that takes an item price, and a discount percentage,
passes them to a function AfterPrice, that returns the item price after discount. As an
output, print the price before and after discount.

Hint: Price After Discount = Item Price (Item Price * Discount Percentage)

Solution:

#include<iostream>

#include<cstring>

using namespace std;

float AfterPrice (float price, float dis)

return price - (price * dis);

void main ()

{ float p, d;

cout << "Enter Item price, and discount";

cin>>p>>d;

cout << "Price after discount = "<< AfterPrice (p, d);

60 | P a g e
Philadelphia University Faculty of Information Technology

Lecturer : Miss Hanan Hardan Department of CS

Lab Instructor : Mrs. Eman Alnaji Examination Paper

Question1: Write a C++ program that declares a 5X5 array, and fill it as displayed in the
figure below: [3 Marks]

X X
X X
X
X X
X X
Print the resulted array as an output, displayed row by row.

Solution

#include<iostream>

#include<cstring>

using namespace std;

void main ()

char A[5][5];

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

for (int j=0; j<5; j++)

if ((i+j == 4)||(i==j))

A[i][j] = 'X';

else

A[i][j] = ' ';

61 | P a g e
cout << A[i][j];

cout <<endl;

Question2: [3 Marks]

A super market arranges items into batches with certain quantity, and tags a total price on
each patch. Write a C++ program that takes as input an item unit price, and batch quantity,
passes this information to a function that calculates and returns back the total price to be
printed and tagged on this batch.

Hint: Total Price = Item unit price * quantity.

Solution

#include<iostream>

#include<cstring>

using namespace std;

float TotalPrice (float unitprice, float qty)

return unitprice * qty;

void main ()

{ float uprice, q;

cout << "Enter Item unit price, and its quantity";

cin>>uprice>>q;

cout << "Total Price = "<< TotalPrice (uprice, q);

62 | P a g e
Philadelphia University Faculty of Information Technology

Lecturer : Eman Alnaji Department of CS

Lab Instructor : Eman Alnaji Examination Paper

Question1: Write a C++ program that declares a 4X4 array, and fill it as displayed in the
figure below: [3 Marks]

# # # #
* $ $ *
* $ $ *
# # # #
Print the resulted array as an output, displayed row by row.

Solution

#include<iostream>

#include<cstring>

using namespace std;

void main ()

char A[4][4];

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

for (int j=0; j<4; j++)

if ((i == 0)||(i==3))

A[i][j] = '#';

else if ((j==0)||(j==3))

A[i][j] = '*';

else

A[i][j] = '$';

63 | P a g e
cout << A[i][j];

cout <<endl;

Question2: Write a C++ program that prompts the user to enter the basic salary, and the
bonuses for an employee, and passes this information to a function that computes and
returns the Net Salary, according to the following equations:

Net Salary = Income Discount

Income = Basic Salary + Bonuses

Discount = Basic Salary * Tax

Where Tax = 0.16

Solution

#include<iostream>

#include<cstring>

using namespace std;

float NetSalary (float basic, float bonus)

float Income, Discount;

const double Tax = 0.16;

Income = basic + bonus;

Discount = basic * Tax;

return Income - Discount;

64 | P a g e
}

void main ()

{ float basic, bonus;

cout << "Enter the basic salary and the bonuses";

cin>>basic>>bonus;

cout << "Net Salary = "<< NetSalary (basic, bonus);

65 | P a g e
Philadelphia University Faculty of Information Technology

Lecturer : Dr. Raad Fadel Department of CS

Lab Instructor : Mrs. Eman Alnaji Examination Paper

Second Exam

Question:

Write a C++ program that reads a string, sends it to a function named "count_vowels" that
counts number of vowels in the given string.

Hint: Vowels are 'a', 'A', 'e', 'E', 'o', 'O', 'i', 'I', 'u', 'U'

Examples:

Input: "Mohammad"

Output: 3

Input: "Philadelphia University"

Output: 9

Input: "Omar"

Output: 2

Solution

#include <iostream>

using namespace std;

int count_vowels (char a[])

{ int i=0, c=0;

while (a[i] != '\0')

if (a[i] == 'a' ||a[i] == 'A'||a[i] == 'i'||a[i] == 'I'||a[i] == 'o'||a[i] ==


'O'||a[i] == 'e'||a[i] == 'E'||a[i] == 'u'||a[i] == 'U')

c++;

i++;

return c;

66 | P a g e
}

void main ()

char s[20];

cin.getline (s, 20, '\n');

cout<<count_vowels (s);

67 | P a g e
Philadelphia University Faculty of Information Technology

Lecturer : Miss Hanan Hardan Department of CS

Lab Instructor : Mrs. Eman Alnaji Examination Paper

Second Exam

Question:

Write a C++ program that reads a string, and a character, send them to a function called
"count", which counts number of occurrences of this character in the given string, and
returns it to the main program.

Examples:

Input: "Mohammad", 'm'

Output: 2 (m is repeated twice)

Input: "Philadelphia University", 'i'

Output: 4 (i is repeated 4 times)

Input: "Omar", 'e'

Output: 0 (e does not appear at all in the string)

Solution:

#include <iostream>

using namespace std;

int count (char [], char);

void main ()

char s[50];

char c;

cin.getline (s, 50);

cin >> c;

cout << count (s, c);

68 | P a g e
int count (char st[], char ch)

int i=1, n=0;

while (st[i] != '\0')

if (st[i] == ch)

n++;

i++;

return n;

69 | P a g e
Philadelphia University Faculty of Information Technology

Lecturer : Miss Hanan Hardan Department of CS

Lab Instructor : Mrs. Eman Alnaji Examination Paper

Second Exam

Question:

Write a C++ program that reads two strings, and sends them to a function called
"match_count" and returns number of similar characters at the beginning of the two strings

Examples:

Input: "Mohammad", "Mohannad"

Output: 4 ("Moha" has 4 characters)

Input: "Aya", 'Ayat'

Output: 3 ("Aya" has 3 characters)

Input: "Omar", 'Ahmad'

Output: 0 (No similar characters at the beginning)

Solution

#include <iostream>

using namespace std;

int match_count (char [], char[]);

void main ()

char s1[50];

char s2[50];

cin.getline (s1, 50);

cin.getline (s2, 50);

cout << match_count (s1, s2);

int match_count (char st1[], char st2[])

70 | P a g e
{

int i=0, n=0;

while ((st1[i] != '\0') && (st2[i] != '\0') && (st1[i] == st2[i]))

n++;

i++;

return n;

71 | P a g e
Philadelphia University Faculty of Information Technology

Lecturer : Mrs. Eman Alnaji Department of CS

Lab Instructor : Mrs. Eman Alnaji Examination Paper

Second Exam

Question:

Write a C++ program that reads a string and sends it to a function named "middle", that
returns the middle character in the string. Assume that number of characters in the string is
always odd number.

Examples:

Input: "Ahmad"

Output: 'm'

Input: "Ali"

Output: 'l'

Solution

#include <iostream>

#include <string>

using namespace std;

char middle (char a[])

{ int mid=strlen(a)/2;

int i=0;

while (i<mid)

i++;

return a[i];

72 | P a g e
void main ()

char s[20];

cin.getline (s, 20, '\n');

cout<< middle (s);

73 | P a g e
Philadelphia University Faculty of Information Technology

Lab Instructor : Mrs. Eman Alnaji Department of CS

Second Exam Makeup Examination Paper

Question:

Write a C++ program that reads a string and sends it to a function named "wordcount", that
returns number of words in the given string.

Examples:

Input: "Ahmad Ali"

Output: 2

Input: "I like C++"

Output: 3

Solution

#include<iostream>

#include<cstring>

using namespace std;

int wordcount (char a[])

int i=0;

int count=0;

while (a[i] != '\0')

if (a[i] == ' ')

count++;

i++;

74 | P a g e
if (a[i-1] != ' ')

count++; //to count the last word if not space

return count;

void main ()

char s[50];

cout<<"Enter string"<<endl;

cin.getline(s, 50);

cout << "Number of words = "<<wordcount(s);

75 | P a g e

You might also like