0% found this document useful (0 votes)
3 views

Lab sheet 5 with answer

The document provides a series of programming exercises for CSC1100, focusing on C++ programming concepts such as arrays, loops, and functions. It includes solutions for calculating sums and averages, finding maximum elements, counting string lengths, identifying repeated numbers, and sorting arrays in wave form. Each exercise is accompanied by code snippets and expected outputs to illustrate the concepts being taught.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lab sheet 5 with answer

The document provides a series of programming exercises for CSC1100, focusing on C++ programming concepts such as arrays, loops, and functions. It includes solutions for calculating sums and averages, finding maximum elements, counting string lengths, identifying repeated numbers, and sorting arrays in wave form. Each exercise is accompanied by code snippets and expected outputs to illustrate the concepts being taught.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

CSC1100: Lab Sheet 5

1. Create a program to find the sum and average of five elements


entered by user in an array.

Solution

int SIZE = 5;

int numbers[SIZE];

cout << "Enter " << SIZE << " integers:\n";

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

cout << "Enter number " << (i + 1) << ": ";

cin >> numbers[i];

int sum = 0;

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

sum += numbers[i];

double average = sum / SIZE;

cout << "\nSum: " << sum << endl;

cout << "Average: " << average << endl;

///////

int arr[5];

int sum=0;

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

1 CSC1100: Computer Programming I 2024


{

cout<<"enter element"<<i+1<<endl;

cin>> arr[i];

sum = sum +arr[i];

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

cout<< "avg ="<<sum/5.0;

2. Find max element in the array and 2d array ( N )(M).

Solution

int SIZE=5;

int arr[]={1,2,5,88,6};

int max1d=arr[0];

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

if(arr[i] > max1d){

max1d=arr[i];

cout << "Maximum element in the 1D array: " << max1d << endl;

////////////////////////////////

int N=3;

int M=4;

int arr[N][M]={

12 CSC1100: Computer Programming I 2024


{1,2,3,4},

{545,5,6,4},

{4,5,5,8}

};

int max2d=arr[0][0];

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

for(int j=0;j<M;j++){

if(arr[i][j]>max2d){

max2d=arr[i][j];

cout << "Maximum element in the 2D array: " << max2d << endl;

3. print the size of the entered string using loops

solution

string s;

cin>> s;

int i=0;

while(s[i]!='\0'){

//cout<<s[i];

i++;

cout<<i;

31 CSC1100: Computer Programming I 2024


4. Write a program to find the most repeated number in an array
of integers and print both the number and its frequency.

Solution

int SIZE = 10;

int myArray[SIZE] = {1, 3, 2, 4, 2, 1, 3, 2, 4, 4};

int repeatedNum = -1, maxFrequency = 0;

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

int currNum = myArray[i];

int currFreq = 1;

for (int j = i + 1; j < SIZE; ++j)

if (myArray[j] == currNum)

++currFreq;

if (currFreq > maxFrequency)

repeatedNum = currNum;

maxFrequency = currFreq;

if (repeatedNum != -1)

14 CSC1100: Computer Programming I 2024


{

cout << "Most repeated number: " << repeatedNum ;

cout << "\nFrequency: " << maxFrequency << endl;

else

cout << "The array is empty." << endl;

5. Tracing
What is the output?

A function is a block of code that performs a specific task.

Result

1 CSC1100: Computer Programming I 2024


5
6. Display array elements
#include <iostream>
using namespace std;

int main() {

int numbers[5] = {7, 5, 6, 12, 35};

cout << "The numbers are: ";

// Printing array elements


// using range based for loop
for (int n : numbers) {
cout << n << " ";
}

cout << "\nThe numbers are: ";

// Printing array elements


// using traditional for loop
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " ";
}

return 0;
}

The output

The numbers are: 7 5 6 12 35


The numbers are: 7 5 6 12 35

7. Display Sum and Average of Array Elements Using for Loop

#include <iostream>
using namespace std;

int main() {

// initialize an array without specifying size


double numbers[] = {7, 5, 6, 12, 35, 27};

double sum = 0;
double count = 0;

1 CSC1100: Computer Programming I 2024


6
double average;

cout << "The numbers are: ";

// print array elements


// use of range-based for loop
for (const double &n : numbers) {
cout << n << " ";

// calculate the sum


sum += n;

// count the no. of array elements


++count;
}

// print the sum


cout << "\nTheir Sum = " << sum << endl;

// find the average


average = sum / count;
cout << "Their Average = " << average << endl;

return 0;
}
Run Code

Output

The numbers are: 7 5 6 12 35 27


Their Sum = 92
Their Average = 15.3333

8. Write a C++ program to find the largest element of a given array


of integers
Visual Presentation:

7
1 CSC1100: Computer Programming I 2024
9.

10. Sample Solution:


11. C++ Code :
12. #include <algorithm>
13. #include<iostream> // Header file for input/output
stream
14. using namespace std; // Using the standard namespace
15.
16. int find_largest(int nums[], int n) { // Function
definition for finding the largest element in an array
17. return *max_element(nums, nums + n); // Return the
maximum element in the array using max_element from
algorithm library
18. }
19.
20. int main() { // Main function where the program
execution starts
21. int nums[] = { // Declaring and initializing an
integer array
22. 5,
23. 4,
24. 9,
25. 12,
26. 8
27. };

1 CSC1100: Computer Programming I 2024


28. int n = sizeof(nums) / sizeof(nums[0]); // Determining
the number of elements in the array
29.
30. cout << "Original array:"; // Output message
8 indicating the original array is being displayed
31. for (int i=0; i < n; i++) // Loop to display each
element of the array
32. cout << nums[i] <<" "; // Output each element of the
array
33.
34. cout << "\nLargest element of the said array: "<<
find_largest(nums, n); // Output message showing the
largest element in the array
35. return 0; // Return statement indicating successful
execution and program termination
36. }
37. Copy
38. Sample Output:
39. Original array:5 4 9 12 8
40. Largest element of the said array: 12
41. Flowchart:

9. Taking Input for Two Dimensional Array

1 CSC1100: Computer Programming I 2024


#include <iostream>
using namespace std;

int main() {
int numbers[2][3];
9
cout << "Enter 6 numbers: " << endl;

// Storing user input in the array


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cin >> numbers[i][j];
}
}

cout << "The numbers are: " << endl;

// Printing array elements


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cout << "numbers[" << i << "][" << j << "]: " <<
numbers[i][j] << endl;
}
}

return 0;
}
Run Code

Output

Enter 6 numbers:
1
2
3
4
5
6
The numbers are:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6

1 CSC1100: Computer Programming I 2024


10. Write a C++ program to sort a given unsorted array of integers,
in wave form.
Note:
10
An array is in wave form when array[0] >= array[1] <=
array[2] >= array[3] <= array[4] >= . . . .

Sample Solution:

C++ Code :
#include<iostream> // Header file for input/output stream

#include<algorithm> // Header file for using algorithms like


sort

using namespace std; // Using the standard namespace

void swap_elements(int *a, int *b)

int t = *a; // Temporary variable to store the value at


pointer a

*a = *b; // Assigning the value at pointer b to pointer a

*b = t; // Assigning the value in the temporary variable


to pointer b

void array_wave(int nums[], int n)

sort(nums, nums+n); // Sorting the array in ascending


order using the sort function

// Loop to create the wave pattern in the array

for (int i = 0; i < n - 1; i += 2)

1 CSC1100: Computer Programming I 2024


swap_elements(&nums[i], &nums[i+1]); // Swapping
adjacent elements to create the wave pattern

11
int main()

int nums[] = {4, 5, 9, 12, 9, 22, 45, 7}; // Declaration


and initialization of an integer array

int n = sizeof(nums) / sizeof(nums[0]); // Calculating the


number of elements in the array

cout << "Original array: ";

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

cout << nums[i] << " "; // Outputting each element of


the array

array_wave(nums, n); // Calling the function to create a


wave pattern in the array

cout << "\nWave form of the said array: ";

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

cout << nums[i] << " "; // Outputting each element of


the modified array in a wave pattern

return 0;

Sample Output:
Original array: 4 5 9 12 9 22 45 7
Wave form of the said array: 5 4 9 7 12 9 45 22
Flowchart:

1 CSC1100: Computer Programming I 2024


11. Write a C++ program to find the next more powerful element of
every element of a given array of integers. Ignore those elements
that have no greater element.

Visual Presentation:

113 CSC1100: Computer Programming I 2024


1 14 CSC1100: Computer Programming I 2024
12. Write a C++ program to find the second lowest and highest
numbers in a given array.

C++ Code :
#include <iostream>

#include <string>

using namespace std;

// Function to find the second highest and second lowest


numbers in an array of integers

void Second_highest_lowest(int array_nums[], int array_size) {

// Check if the array has only two elements

if (array_size == 2)

// Output the elements in ascending order

if (array_nums[0] < array_nums[1])

cout << array_nums[0] << " " <<


array_nums[1];

else

cout << array_nums[1] << " " <<


array_nums[0];

else

1 CSC1100: Computer Programming I 2024


15
{

// Sorting the array in ascending order using


Bubble Sort

bool flag;

int temp;

do

flag = false;

for (int x = 0; x < array_size - 1; x++)

// Swap elements if they are in the


wrong order

if (array_nums[x] > array_nums[x +


1])

temp = array_nums[x];

array_nums[x] = array_nums[x
+ 1];

array_nums[x + 1] = temp;

flag = true;

} while (flag);

// Determine the index of the second lowest


number in the sorted array

int index = 0;

1 CSC1100: Computer Programming I 2024


16
for (int y = 0; y < array_size - 1; y++)

if (array_nums[y] == array_nums[y + 1])

index++;

else

break;

// Determine the index of the second highest


number in the sorted array

int index2 = array_size - 1;

for (int z = array_size - 1; z > 0; z--)

if (array_nums[z] == array_nums[z - 1])

index2--;

else

break;

1 17 CSC1100: Computer Programming I 2024


// Output the results

cout << "\nSecond lowest number of the said


array: " << array_nums[index + 1];

cout << "\nSecond highest Number of the said


array: " << array_nums[index2 - 1];

// Main function

int main() {

// Sample arrays of integers

int nums1[] = { 1, 12, 122, 9 };

int size_A = sizeof(nums1)/sizeof(nums1[0]);

// Display array elements in reverse order

cout <<"Array elements: ";

for (int i = size_A - 1; i >= 0; i--)

cout << nums1[i] << " ";

// Call the Second_highest_lowest function and display the


result

Second_highest_lowest(nums1, size_A );

cout << endl;

// Repeat the process for the other arrays

int nums2[] = { 1, 12, 12, 9 };

size_A = sizeof(nums2)/sizeof(nums2[0]);

1 18 CSC1100: Computer Programming I 2024


cout <<"\nArray elements: ";

for (int i = size_A - 1; i >= 0; i--)

cout << nums2[i] << " ";

Second_highest_lowest(nums2, size_A );

cout << endl;

int nums3[] = { 1, 12, 12, 9, 9, 5, 5 };

size_A = sizeof(nums3)/sizeof(nums3[0]);

cout <<"\nArray elements: ";

for (int i = size_A - 1; i >= 0; i--)

cout << nums3[i] << " ";

Second_highest_lowest(nums3, size_A );

cout << endl;

int nums4[] = { 9, 9 , 9, 9, 9 };

size_A = sizeof(nums4)/sizeof(nums4[0]);

cout <<"\nArray elements: ";

for (int i = size_A - 1; i >= 0; i--)

cout << nums4[i] << " ";

Second_highest_lowest(nums4, size_A );

cout << endl;

return 0; // Return 0 to indicate successful execution

Sample Output:
Array elements: 9 122 12 1
Second lowest number of the said array: 9

119 CSC1100: Computer Programming I 2024


Second highest NUmber of the said array: 12

Array elements: 9 12 12 1
Second lowest number of the said array: 9
Second highest NUmber of the said array: 9

Array elements: 5 5 9 9 12 12 1
Second lowest number of the said array: 5
Second highest NUmber of the said array: 9

Array elements: 9 9 9 9 9
Second lowest number of the said array: 0
Second highest NUmber of the said array: 0

13. Write a C++ program to find and print all distinct elements of a
given array of integers.

Visual Presentation:

14. Write a c++ program about two dimensional array

.
// C++ Program to display all elements
// of an initialised two dimensional array

#include <iostream>
using namespace std;

int main() {
int test[3][2] = {{2, -5},

120 CSC1100: Computer Programming I 2024


{4, 0},
{9, 1}};

// use of nested for loop


// access rows of the array
for (int i = 0; i < 3; ++i) {

// access columns of the array


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

return 0;
}
Run Code

Output

test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1

15.write a c++ about Taking Input for Two Dimensional Array


#include <iostream>
using namespace std;

int main() {
int numbers[2][3];

cout << "Enter 6 numbers: " << endl;

// Storing user input in the array


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cin >> numbers[i][j];
}
}

cout << "The numbers are: " << endl;

1 21 CSC1100: Computer Programming I 2024


// Printing array elements
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cout << "numbers[" << i << "][" << j << "]: " <<
numbers[i][j] << endl;
}
}

return 0;
}
Run Code

Output

Enter 6 numbers:
1
2
3
4
5
6
The numbers are:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6

16. Write a C++ program to arrange the numbers in a given


array in a way that the sum of some numbers equals the
largest number in the array.

Visual Presentation:

22
1 CSC1100: Computer Programming I 2024
17. Write a C++ program to find the number of pairs of
integers in a given array of integers whose sum is equal to a
specified number.

C++ Code :

#include <iostream> // Header file for input/output stream

using namespace std; // Using the standard namespace

int main() // Main function

int array1[] = {1, 5, 7, 5, 8, 9, 11, 12}; // Declaration


and initialization of the array

int s1 = sizeof(array1) / sizeof(array1[0]); // Calculate


the size of the array

cout << "Original array: "; // Output label for original


array

23
1 CSC1100: Computer Programming I 2024
for (int i = 0; i < s1; i++) // Loop to output elements of
the original array

cout << array1[i] << " ";

int i, sum = 12, ctr = 0; // Declaration of variables for


sum and count of pairs

cout << "\nArray pairs whose sum equal to 12: "; // Output
label for pairs whose sum equals 12

for (int i = 0; i < s1; i++) // Loop through the array


elements

for (int j = i + 1; j < s1; j++) // Nested loop to


find pairs with sum equal to 12

if (array1[i] + array1[j] == sum) // Check if the


sum of two elements is equal to 12

cout << "\n" << array1[i] << "," << array1[j];


// Output the pair

ctr++; // Increment count of pairs

cout << "\nNumber of pairs whose sum equals 12: "; //


Output label for count of pairs

cout << ctr; // Output the count of pairs

124 CSC1100: Computer Programming I 2024


return 0; // Return 0 to indicate successful execution

Sample Output:
Original array: 1 5 7 5 8 9 11 12
Array pairs whose sum equal to 12:
1,11
5,7
7,5
Number of pairs whose sum equal to 12: 3

18. Write a C++ program to find the number of pairs of integers in a


given array of integers whose sum is equal to a specified number.

C++ Code :
#include <iostream> // Header file for input/output stream

using namespace std; // Using the standard namespace

int main() // Main function

int array1[] = {1, 5, 7, 5, 8, 9, 11, 12}; // Declaration


and initialization of the array

int s1 = sizeof(array1) / sizeof(array1[0]); // Calculate


the size of the array

cout << "Original array: "; // Output label for original


array

for (int i = 0; i < s1; i++) // Loop to output elements of


the original array

cout << array1[i] << " ";

int i, sum = 12, ctr = 0; // Declaration of variables for


sum and count of pairs

1 25 CSC1100: Computer Programming I 2024


cout << "\nArray pairs whose sum equal to 12: "; // Output
label for pairs whose sum equals 12

for (int i = 0; i < s1; i++) // Loop through the array


elements

for (int j = i + 1; j < s1; j++) // Nested loop to


find pairs with sum equal to 12

if (array1[i] + array1[j] == sum) // Check if the


sum of two elements is equal to 12

cout << "\n" << array1[i] << "," << array1[j];


// Output the pair

ctr++; // Increment count of pairs

cout << "\nNumber of pairs whose sum equals 12: "; //


Output label for count of pairs

cout << ctr; // Output the count of pairs

return 0; // Return 0 to indicate successful execution

Sample Output:
Original array: 1 5 7 5 8 9 11 12
Array pairs whose sum equal to 12:
1,11
5,7

1 26 CSC1100: Computer Programming I 2024


7,5
Number of pairs whose sum equal to 12: 3

19. Write a C++ program to find the third largest string in a given
array of strings.

C++ Code :
#include <iostream> // Including the Input/Output Stream
Library

#include <string> // Including the String Library

using namespace std; // Using the Standard Namespace

// Function to find the third highest length string from an


array of strings

string third_highest(string strArr[], int size) {

int len1, len2, len3, index1, index2, index3; // Declaring


variables to store lengths and indices

len1 = len2 = len3 = 0; // Initializing length variables


to 0

// Get the length of the largest word in the string array

for (int y = 0; y < size; y++) {

if (strArr[y].length() > len1) {

len1 = strArr[y].length(); // Update len1 if a


longer string is found

index1 = y; // Save the index of the longest


string

127 CSC1100: Computer Programming I 2024


// Get the length of the second largest word in the string
array

for (int z = 0; z < size; z++) {

if (strArr[z].length() >= len2 && z != index1) {

len2 = strArr[z].length(); // Update len2 if a


longer string (excluding the first largest) is found

index2 = z; // Save the index of the second


longest string

// Get the length of the third largest word in the string


array

for (int x = 0; x < size; x++) {

if (strArr[x].length() >= len3 && x != index1 && x !=


index2) {

len3 = strArr[x].length(); // Update len3 if a


longer string (excluding the first and second largest) is
found

index3 = x; // Save the index of the third


longest string

// Check if the lengths of the second and third largest


strings are the same

if (len2 == len3) {

return strArr[index2]; // If equal, return the second


longest string

} else {

128 CSC1100: Computer Programming I 2024


return strArr[index3]; // Otherwise, return the third
longest string

// Main function

int main() {

// Arrays of strings

string S1[] = { "abcdefgh", "abcdefg", "abcdef", "abcde",


"abcd" };

string S2[] = { "abc", "abc", "abc", "abc", "abc" };

string S3[] = { "abc", "abcd", "abcd" };

// Determining the size of each array

int size_S1 = sizeof(S1)/sizeof(S1[0]); // Size of S1

cout <<"Array elements: ";

for (int i = size_S1 - 1; i >= 0; i--)

cout << S1[i] << " "; // Printing elements of S1 in


reverse order

third_highest(S1, size_S1 ); // Calling the third_highest


function

cout << "\nThird highest length string: " <<


third_highest(S1, size_S1 ); // Printing the third highest
length string of S1

cout << endl;

int size_S2 = sizeof(S2)/sizeof(S2[0]); // Size of S2

cout <<"\nArray elements: ";

for (int i = size_S2 - 1; i >= 0; i--)

1 29 CSC1100: Computer Programming I 2024


cout << S2[i] << " "; // Printing elements of S2 in
reverse order

cout << "\nThird highest length string: " <<


third_highest(S2, size_S2 ); // Printing the third highest
length string of S2

cout << endl;

int size_S3 = sizeof(S3)/sizeof(S3[0]); // Size of S3

cout <<"\nArray elements: ";

for (int i = size_S3 - 1; i >= 0; i--)

cout << S3[i] << " "; // Printing elements of S3 in


reverse order

cout << "\nThird highest length string: " <<


third_highest(S3, size_S3 ); // Printing the third highest
length string of S3

cout << endl;

return 0; // Return statement indicating successful


completion

Sample Output:
Array elements: abcd abcde abcdef abcdefg abcdefgh
Third highest length string: abcdef

Array elements: abc abc abc abc abc


Third highest length string: abc

Array elements: abcd abcd abc


Third highest length string: abc

130 CSC1100: Computer Programming I 2024


20. Write a C++ program to find the k largest elements in a given
array of integers.

Visual Presentation:

131 CSC1100: Computer Programming I 2024

You might also like