Professional Documents
Culture Documents
SP-InLab07-Section 4
SP-InLab07-Section 4
Instructor:
Dr. Ahmad Awwad (a.awwad@psut.edu.jo)
Lab Exercises
Mark /5 /5
Total Mark
Lab #7 Objectives
● Nested Loops
● Examples (such as printing patterns)
● Sorting arrays (bubble sort only)
● Defining 2D arrays
● Initialize 2D arrays (initializer list and using loops) and printing arrays
Page 1 of 5
Task 1 – Nested Loop output
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 10; i++) {
for (j = 1; j <= 10; j++) {
printf("%d x %d = %d\n", i, j, i*j);
}
printf("\n");
}
return 0;
}
#include <stdio.h>
int main() {
int rows = 5;
int i, j;
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Page 2 of 5
Task 3 – Sorting Array-Bubble Sort
Q3: What is the output of the following question?
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Page 3 of 5
PART II: Lab Exercises
A. Write a C function called PrintShape () takes the following row(int), and a char to draw
with(char) to draw a pyramid.
B. Test the function.
Sample Output
Page 4 of 5
Exercise 2 – Store and Sort a 2D character array
Exercise Objectives
● Sorting arrays (bubble sort only)
● Defining 2D arrays
● Initialize 2D arrays (initializer list and using loops) and printing arrays
Problem Description
Inside the “Lab7” folder, create a project named “Lab7Ex2”.
A. Create a function named fill_array, that takes as argument an 2D array, row and column
of the array. The function should ask the user to enter the values of the array.
B. Create a function named printArray, that takes as argument an 2D array, row and
column of the array, the function should print the array elements in tabular format.
C. Create a function named swap_Raw, that takes as argument an 2D array, row of the
array, column of the array, two integers. The function should swap the raw of the array
according to the two integers sent.
D. Create a function named Sort_Array that takes as argument an 2D array, row of the
array, column of the array, index of the column of type integer. The function should sort
a column of the array according to the index sent in ascending order.
E. Create a main that will test all the functions above.
Sample Output
Printing Array …
15 20 45 33 16
23 49 11 22 38
27 40 17 12 42
Printing Array …
15 45 20 33 16
27 17 40 12 42
23 11 49 22 38
Printing Array …
15 11 20 33 16
27 17 40 12 42
23 45 49 22 38
Page 5 of 5