In: Computer Science
Lab 7: 2D Arrays
Project Goals
The goals of this project are to:
1. Get students familiar with 2D arrays
2. Continue loop practice
Important Notes:
1. Formatting: Make sure that you follow the precise recommendations for the output content and formatting: for example, do not change the text of the problem from “Enter the number of rows in your array: ” to “Enter the number of rows: ”. Your assignment will be auto-graded and any change in formatting will result in a loss in the grade.
2. Comments: Header comments are required on all files and recommended for the rest of the program. Points will be deducted if no header comments are included.
Problem 1
Save your program as squaring.c
It’s better to be odd, so let’s square those values. Write a program which gets values into an array and then squares the odd values. The program should prompt the user to enter the number of rows -1[1] and columns they would like in an array. Then it should prompt the user to enter values to fill that array. It should iterate over all the values in the array and square any which are odd. Display those values back to the user.
The program should function as follows (items underlined are to be entered by the user):
Enter the number of rows in your 2D array: 2
Enter the number of columns in your 2D array: 2
Enter a value to save: 1
Enter a value to save: 2
Enter a value to save: 3
Enter a value to save: 4
1 2
9 4
Run your program again, testing it with different values.
Notes:
[1]I think this should be ...rows... and not ...rows-1...
Save your program as squaring.c. Hence, the required programming language is C.
C Program:
#include <stdio.h>
int main()
{
int rows,cols,i,j;
printf("Enter the number of rows in your 2D array: ");
scanf("%d",&rows);
printf("Enter the number of columns in your 2D array: ");
scanf("%d",&cols);
int arr[rows][cols];
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
printf("Enter a value to save: ");
scanf("%d",&arr[i][j]);
if(arr[i][j]%2!=0)
arr[i][j]=arr[i][j] * arr[i][j];
}
}
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
return 0;
}
Output: