0% found this document useful (0 votes)
6 views24 pages

Week 7 Worksheet

Uploaded by

jou20230893
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
6 views24 pages

Week 7 Worksheet

Uploaded by

jou20230893
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 24

Using the function to print array 1D and 2D and sort 1D and more

….

#include <stdio.h>
#include <stdlib.h>
void print1D( int a[],int size){
for(int i=0;i<size;i++)
printf("%d ,",a[i]);
}
void print2D(int a[][3],int rz){
for(int i=0;i<rz;i++){
for(int j=0;j<3;j++){
printf("%d ",a[i][j]);
}
printf("\n");
}

}
int max(int a[],int s){
int m=a[0];
for(int i=0;i<s;i++){
if(a[i]>m)
m=a[i]; }
return m;
}
int main(void) {
int r[8]={1,4,6,7,18,4,3,1};
int m[100];
for(int i=0;i<100;i++){
m[i]=rand()%6;
}
print1D(r,3);
printf("\n**************\n");
print1D(m, 20);
printf("\n**************\n");
printf("maximum of m=%d\n",max(m,8));
int grades[100][3];
for(int i=0;i<100;i++){
for(int j=0;j<3;j++)
grades[i][j]=35+rand()%66;
}
print2D(grades,5);
for(int r=0;r<100;r++){
grades[r][0]=100;
}
printf("\n**************\n");
print2D(grades,5);
printf("\n**************\n");
return 0;
}
Week 7

● 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

● Nested Loops
Q1 :What is the output of the following question :

#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;

Q2 :Given an array of integers, find all pairs of elements whose sum is equal to a given value.
#include <stdio.h>

int main() {
int arr[5] = {1, 2, 3, 4, 5};
int i, j, sum = 0;
for (i = 0; i < 5; i++) {
for (j = i+1; j < 5; j++) {
sum += arr[i] + arr[j];
}
}
printf("The sum of all pairs of elements is: %d\n", sum);
return 0;
}
Q3 pattern printing like
Right tringle
#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;}

Q4 :Sorting arrays (bubble sort only)

#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;
}

2D Array and nested loop


Question # 1 (Traversing)

Consider a 2D grid of size 4 x 5, where each cell contains a cost. A game character has to get from
the top left corner to the bottom right corner moving either to the right cell or to the cell below:
If the right cell has a lower cost, the character moves to the right.
Otherwise, the character moves to the cell below.
Write a complete C program to simulate the movement of this game character.
1. Define a function named show_path that receives the 2D grid as an argument. This function
must print the path (as shown in the sample output) and return the cost of the path.
2. Define a main() function that:
○ Defines a 2D array and fills it with random integers between 0 and 9 inclusive.
○ Calls function show_path to print the path and then prints the cost of the path.

Alternatives.
● Start at the bottom right corner and move to the top left corner (only up and right
allowed)
● Start at the top right corner and move to the bottom left corner (only down and left
allowed)
● Start at the bottom left corner and move to the top right corner (only up and right
allowed)
Grading.
● [3 points] main(): 2 for defining and filling the 2D array + 1 for calling the function and
printing.
● [7 points] show_path():
○ Loop condition: 1 point
○ Each if statement: 1 point
○ Updating the sum: 1 point
○ 0.5 for initializing the variables and 0.5 for returning the sum.

Answer

#include <stdio.h>
#include <cstdlib>
#include <ctime>

#define ROWS 4
#define COLS 5

int show_path(int a[][COLS]) {


int a[ROWS][COLS];
int i = 0, j = 0, sum = 0;
while (i < ROWS && j < COLS) {
sum += a[i][j];

if (i == ROWS-1) {
j++; printf("right ");
}
else if (j == COLS-1) {
i++; printf("down ");
}
else if (a[i+1][j] < a[i][j+1]) {
i++; printf("down ");
}
else {
j++; printf("right ");
}
}
printf("\n");

return sum;
}

int main() {
srand(time(0));

int a[ROWS][COLS];
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLS; j++)
a[i][j] = rand() % 10;

printf("path = ");
printf("cost = %d\n", shortest_path(a));
return 0;
}

Question 2 (Nested Loop)

int a[SIZE][SIZE];

int c = 1;
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
if (j == 0)
a[i][j] = -1;
else
a[i][j] = c;
c++;
}
}

Assuming that SIZE = 100, what are the contents of each of the following array cells after the
above code finishes execution?

a[0][99] =

a[99][0] =

a[99][99] =

Alternatives. Use other values for SIZE, like: 200, 300, 400, etc.

Question 3
Write a program that reads a non-negative integer n. For each number x from 1 to n inclusive, the
program must print all the positive divisors ( ‫عوامل‬/‫ )قواسم‬of x. If the user enters a negative number,
the program should not do anything.

The following is an example run of the program:

Enter a number: 10
Divisors of 1: 1
Divisors of 2: 1 2
Divisors of 3: 1 3
Divisors of 4: 1 2 4
Divisors of 5: 1 5
Divisors of 6: 1 2 3 6
Divisors of 7: 1 7
Divisors of 8: 1 2 4 8
Divisors of 9: 1 3 9
Divisors of 10: 1 2 5 10

#include <stdio.h>
int main() {

int n;

printf("Enter a number: ");

scanf("%d", &n);

if (n < 0)

return 0;

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

printf("Divisors of %d: ", i);

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

if (i % j == 0)

printf("%d ", j);

printf("\n");

return 0;

Question 4
Implement function int check(int a[], int size), which returns 1 if any of the elements in the first
half of the given array is also in the second half. The function returns 0 otherwise.
You can assume that the array size is even (no need to check for this).

Example 1.
Example 2.

The function returns 0, because none of the


numbers in the first half is present in the second The function returns 1, because 6 from the
half.
first half is present in the second half.
Solution.

int check(int a[], int size) {


for (int i = 0; i < size / 2; i++) {
for (int j = size / 2; j < size; j++)
if (a[i] == a[j])
return 1;
}
return 0;
Question 5

Implement function 2 d array not included in the exam 2022


void check(char board[][64], int i, int j)

which receives a chess board of size 64x64 and the position of


a rook (♖ ).
The function prints 'yes' if there is another rook in its same
column or in its same row and 'no' otherwise.
Assume that the board contains the character 'R' in a cell if there is
a rook in that cell.

Solution.

void check(char board[][64], int i, int j) {


// check same row
for (int k = 0; k < 64; k++)
if (board[i][k] == 'R' && k
!= j) { printf("yes");

return;
}

// check same column


for (int k = 0; k < 64; k++)
if (board[k][j] == 'R' && k
!= i) { printf("yes");

return;
}

printf("no");
Question 6 2D Arrays

PART 1.

Implement a function named count(…) that receives as an argument a character array


of size 7 x 10. Each cell in the array is assumed to contain only '0' or '#'. The function must modify the
array such that each '0' is changed to become the number of '#' around it (above, below, left and right).

0 0 0 # # # # # 0 0 1 0 2 # # # # # 2 1
# 0 # # 0 0 0 0 # # # 2 # # 3 1 1 3 # #
0 0 0 0 # 0 0 # # 0 1 1 2 2 # 1 1 # # 2
0 # # 0 # 0 0 0 0 0 1 # # 3 # 1 1 1 2 0
0 # 0 # 0 0 # 0 # 0 1 # 4 # 3 2 * 3 # 1
0 0 # # # # # # # 0 0 2 # # # # # # # 1
0 0 # # 0 0 0 # # 0 0 1 # # 2 1 2 # # 1

Example.

Before calling the function After calling the function

Solution.
#define ROWS 7
#define COLS 10

void count(char a[ROWS][COLS]) {

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


for (int j = 0; j < COLS; j++) {
if (a[i][j] == '#')
continue;
if (i != 0 && a[i-1][j] == '#')
a[i][j]++;
if (i != ROWS-1 && a[i+1][j] == '#')
a[i][j]++;
if (j != 0 && a[i][j-1] == '#')
a[i][j]++;
if (j != COLS-1 && a[i][j+1] == ‘#')
a[i][j]++;
}
}
PART 2.

Write a complete C program that creates a 2D array of size 7 x 10 , fills it randomly with
either '0' or '#' and sends it to function count(…). The program should then print the
array after the function call (in the same format as the sample in part 1).

Solution.

int main() {
char a[ROWS][COLS];

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


for (int j = 0; j < COLS; j++) {
if (rand() % 2 == 0)
a[i][j] = '0';
else
a[i][j] = '#';
}
}

count(a);

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


for (int j = 0; j < COLS; j++)
printf("%c ", a[i][j]);

printf("\n");
}

return 0;
}
Question 7: [8 Points]
Write a C function called RotateLine90. The function receives a (2D) two dimensional array of
type integer of size 5 by 5, also the function receives coordinates of line points. The function
should have the following signature:
void RoateLine90( int A[][5], int x1, int y1, int x2, int y2)
The integer array represents an image that has two colors (black and white). Each array cell of
value 1 represents black color and each array cell of value 0 represents white color. The image
can have only horizontal vertical lines. Function is supposed to rotate the given line by 90
degrees counter clockwise.
For example, below is an image of 5 by 5 with two horizontal lines, the left side shows the
image and the right side shows the equivalent matrix of it:

0 0 0 0 0

0 0 0 0 0

0 0 1 1 1

0 0 0 0 0

1 1 1 1 0

Calling the function RoateLine90(A,2,2,2,4) will result in rotating the line from (2,2) to (2,4) by
90 degrees. The final shape should be
0 0 1 0 0

0 0 1 0 0

0 0 1 0 0

0 0 0 0 0

1 1 1 1 0

#include <stdio.h>

void RotateLine90(int A[][5], int x1, int y1, int x2, int y2) {

// Check that the line is either horizontal or vertical

if (x1 != x2 && y1 != y2) {

printf("Error: Line is not horizontal or vertical\n");

return;

// Rotate the line by swapping coordinates and negating one of them

int dx = x2 - x1;

int dy = y2 - y1;

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

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

int tmp = A[x1+i][y1+j];

A[x1+i][y1+j] = A[x1+j][y1+i];

A[x1+j][y1+i] = tmp;

}
// Flip the line if it was horizontal (top to bottom)

if (y1 == y2) {

int mid = (x1 + x2) / 2;

for (int i = x1; i <= mid; i++) {

for (int j = y1; j <= y2; j++) {

int tmp = A[i][j];

A[i][j] = A[x2-(i-x1)][j];

A[x2-(i-x1)][j] = tmp;

// Flip the line if it was vertical (left to right)

if (x1 == x2) {

int mid = (y1 + y2) / 2;

for (int i = x1; i <= x2; i++) {

for (int j = y1; j <= mid; j++) {

int tmp = A[i][j];

A[i][j] = A[i][y2-(j-y1)];

A[i][y2-(j-y1)] = tmp;

int main() {

// Example usage of RotateLine90 function

int A[5][5] = {{0, 0, 0, 0, 0},


{0, 0, 0, 0, 0},

{0, 0, 1, 0, 0},

{0, 0, 1, 0, 0},

{0, 0, 1, 0, 0}};

RotateLine90(A, 2, 1, 4, 1); // Rotate vertical line (2,1) to (4,1)

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

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

printf("%d ", A[i][j]);

printf("\n");

return 0;

Question 8
a) How many A’s, B’s and C’s will the following piece of code print?
Provide your answer on three lines as follows:
A = {insert a number here}
B = {insert a number here}
C = {insert a number here}

Q for (int i = 0; i < 50; i++) { Answ


printf("A"); er
for (int j = 0; j < 10; j+
+)
printf("B");

for (int j = 0; j < 10; j+


+) {
printf("B");
printf("C");
}
}

For each of the pieces of code below, show the output in the given box.

(b)

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


for (int j = 10; j > 0; j--) {
printf("%d %d\n", i, j);
j -= 3;
}
printf("--\n");
}

(c)

int i = -1;
do {
i++;
switch (i) {
case 0:
printf("Zero\n");
break;
case 1:
case 2:
case 3:
i > 2 ? printf("Three\n") : printf("One or Two\n");
break;
case 6:
printf("Six\n");
case 10:
printf("Ten\n");
break;
default:
printf("Other\n");
}
} while (i < 10);
Question 9
Write a program that reads a number N and outputs the shape of a tornado of size N. The following are
examples:

Tornado of size 7 Tornado of size 4 Tornado of size 1

******* **** *
******* **** *
****** ***
****** ***
***** **
***** **
**** *
**** *
***
***
**
**
*
*

Question 10 (Nested loop)


Write a program that reads grades of students in 5 sections. Each section has exactly 5 students. For
each section, the program should output the highest grade.
The input and output of your program should be as shown in the screen-shot below.

You might also like