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; } |Page2 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; } |Page3 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; } |Page4 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; } |Page5 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; } |Page6 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; } |Page7 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; } |Page8 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; } |Page9 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 V6 V11 V16 The one-dimensional array will be: V1 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++; } } | P a g e 10 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; } | P a g e 11 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; } | P a g e 12 Chapter 02 Functions Prepared By: Dr. Murad Magableh 2013 | P a g e 13 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; } | P a g e 14 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; } | P a g e 15 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 << round(number) << endl; } is: " | P a g e 16 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); } | P a g e 17 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; } | P a g e 18 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(); } | P a g e 19 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; } | P a g e 20 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] << " "; } | P a g e 21 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; } | P a g e 22 Chapter 03 Pointers Prepared By: Dr. Murad Magableh 2013 | P a g e 23 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 << " << *p << *p+=12; a++; cout << a << " << *p << *p = 100; *q = 200; cout << a << " << *p << int * t; t = q; q = p; p = t; cout << a << " << *p << t = &a; p = t; q = t; cout << a << " << *p << } " << b << " " " " << *q << endl; " << b << " " " " << *q << endl; " << b << " " " " << *q << endl; " << b << " " " " << *q << endl; " << b << " " " " << *q << endl; Solution: 8 4 8 4 21 4 21 4 100 200 100 200 100 200 200 100 100 200 100 100 | P a g e 24 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 | P a g e 25 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); } | P a g e 26 Q4: Write a program that reads 10 integers from the user and stores them in a onedimensional 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; } | P a g e 27 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 | P a g e 28 Chapter 04 Recursion Prepared By: Dr. Murad Magableh 2013 | P a g e 29 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; } | P a g e 30 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; } | P a g e 31 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 | P a g e 32 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; } | P a g e 33 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; } | P a g e 34 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: | P a g e 35 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; } | P a g e 36 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; } | P a g e 37 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 | P a g e 38 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; } | P a g e 39 Chapter 05 Strings Prepared By: Dr. Murad Magableh 2013 | P a g e 40 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; } | P a g e 41 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; } | P a g e 42 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; } | P a g e 43 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, // s1 < s2 s1 = "ABB"; s2 = "ABC"; cout << my_strcmp(s1, // s1 > s2 s1 = "ABC"; s2 = "ABB"; cout << my_strcmp(s1, // s1 < s2 s1 = "ABC"; s2 = "ABCD"; cout << my_strcmp(s1, // s1 > s2 s1 = "ABCD"; s2 = "ABC"; cout << my_strcmp(s1, } s2) << endl; s2) << endl; s2) << endl; s2) << endl; s2) << endl; | P a g e 44 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++) | P a g e 45 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; } | P a g e 46 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; } | P a g e 47 Chapter 06 File Processing Prepared By: Dr. Murad Magableh 2013 | P a g e 48 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; } | P a g e 49 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; } | P a g e 50 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; } | P a g e 51 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; | P a g e 52 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 cout cout cout cout cout cout cout cout cout << << << << << << << << << << << << << << << << "Max is: " << max << endl; "Min is: " << min << endl; "AVG is: " << (float)sum/counter << endl; "There is " << prime_counter << " prime number(s)" endl; "There is " << perfect_counter << " perfect number(s)" endl; "There is " << even_counter << " even number(s)" endl; "There is " << odd_counter << " odd number(s)" << endl; "There is " << negative_counter " negative number(s)" << endl; "The summation of the positive number(s) is: " positive_sum << endl; "The summation of the even negative number(s) is: " even_negative_sum << endl; } | P a g e 53 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++) { | P a g e 54 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); } | P a g e 55 Philadelphia University Faculty of Information Technology Lecturer Department of CS : Dr. Raad Alwan Lab Instructor Examination Paper : Eman Alnaji First Exam Question1: figure below: $ # # * # $ * # Write a C++ program that declares a 4X4 array, and fill it as displayed in the [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] = '*'; | P a g e 56 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') | P a g e 57 { 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); } | P a g e 58 Philadelphia University Faculty of Information Technology Lecturer Department of CS : Miss Hanan Hardan Lab Instructor Question1: figure below: Z Z Examination Paper : Mrs. Eman Alnaji Write a C++ program that declares a 5X5 array, and fill it as displayed in the [3 Marks] 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] = ' '; | P a g e 59 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); } | P a g e 60 Philadelphia University Faculty of Information Technology Lecturer Department of CS : Miss Hanan Hardan Lab Instructor Question1: figure below: Examination Paper : Mrs. Eman Alnaji Write a C++ program that declares a 5X5 array, and fill it as displayed in the [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] = ' '; | P a g e 61 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); } | P a g e 62 Philadelphia University Faculty of Information Technology Lecturer Department of CS : Eman Alnaji Lab Instructor Question1: figure below: Examination Paper : Eman Alnaji Write a C++ program that declares a 4X4 array, and fill it as displayed in the [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] = '$'; | P a g e 63 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; | P a g e 64 } void main () { float basic, bonus; cout << "Enter the basic salary and the bonuses"; cin>>basic>>bonus; cout << "Net Salary = "<< NetSalary (basic, bonus); } | P a g e 65 Philadelphia University Faculty of Information Technology Lecturer Department of CS : Dr. Raad Fadel 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; | P a g e 66 } void main () { char s[20]; cin.getline (s, 20, '\n'); cout<<count_vowels (s); } | P a g e 67 Philadelphia University Faculty of Information Technology Lecturer Department of CS : Miss Hanan Hardan 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); } | P a g e 68 int count (char st[], char ch) { int i=1, n=0; while (st[i] != '\0') { if (st[i] == ch) n++; i++; } return n; } | P a g e 69 Philadelphia University Faculty of Information Technology Lecturer Department of CS Lab Instructor : Miss Hanan Hardan : 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[]) | P a g e 70 { int i=0, n=0; while ((st1[i] != '\0') && (st2[i] != '\0') && (st1[i] == st2[i])) { n++; i++; } return n; } | P a g e 71 Philadelphia University Faculty of Information Technology Lecturer Department of CS : Mrs. Eman Alnaji 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]; } | P a g e 72 void main () { char s[20]; cin.getline (s, 20, '\n'); cout<< middle (s); } | P a g e 73 Philadelphia University Faculty of Information Technology Lab Instructor Department of CS : Mrs. Eman Alnaji Examination Paper Second Exam – Makeup 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++; } | P a g e 74 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); } | P a g e 75