Week 4 Code Examples
// Week 4 Lecture 2
// This program is aiming
// to demonstrate the use of simple
// array of arrays
// Basic printing out of an array of arrays
#include <stdio.h>
#define ROWS 3
#define COLS 4
int sum_grid(int array[ROWS][COLS]);
int main(void) {
//int array[ROWS] = {1, 2, 3};
int array[ROWS][COLS] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
printf("The beautiful array of arrays:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%3d ", array[i][j]);
}
printf("\n");
}
// Function to sum the grid!
printf("The sum of the grid is: %d\n", sum_grid(array));
return 0;
}
// FUNCTION is going to sum up the grid
// INPUT: array, size
// OUTPUT: int
int sum_grid(int array[ROWS][COLS]) {
int sum = 0;
for(int i = 0; i < ROWS; i++) {
for(int j = 0; j < COLS; j++) {
sum = sum + array[i][j];
}
}
return sum;
}
// Week 4 Lecture 1
// This program is trying
// to demonstrate the use of a simple
// array of structs
#include <stdio.h>
#define SIZE 3
#define MAX 20
// 1. Define the struct outside the main
struct Athlete {
char name[MAX];
char country[MAX];
double score;
};
int main(void) {
//2. Declare an array of structs
struct Athlete team[SIZE];
// struct Athlete team_member;
// team_member.name = "Sasha"
for (int i = 0; i < SIZE; i++) {
printf("Athlete %d name : ", i);
fgets(team[i].name, MAX, stdin);
printf("Athlete's %d country: ", i);
fgets(team[i].country, MAX, stdin);
printf("Athlete's %d score: ", i);
scanf("%lf", &team[i].score);
// Special function that reads one character at a time from stdin
// It is grabbing that newline from the buffer
getchar();
}
printf("Scoreboard: \n");
for (int i = 0; i < SIZE; i++) {
printf("%s from %s scored %.2lf\n", team[i].name, team[i].country, team[i].score);
}
return 0;
}
ELF >