LearnFrenzy
Sign in Take a free test

Declarations and Initializations · Declaration Programs · Question 7

Fill a zero-initialised 2D array with a times table in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Declare a 4 × 4 array initialised to zero, fill cells 1–3 with a times table, and show that untouched cells are still zero.

Solution
main.c
#include <stdio.h>

int main(void) {
    int t[4][4] = {0};
    for (int r = 1; r <= 3; r++)
        for (int c = 1; c <= 3; c++)
            t[r][c] = r * c;
    for (int r = 1; r <= 3; r++) {
        for (int c = 1; c <= 3; c++)
            printf("%3d", t[r][c]);
        printf("\n");
    }
    printf("row 0 sum: %d\n", t[0][0] + t[0][1] + t[0][2] + t[0][3]);
    return 0;
}

Output Verified by compiling and running

  1  2  3
  2  4  6
  3  6  9
row 0 sum: 0

= {0} initialises the first element explicitly and every other element implicitly, so row 0 and column 0 are guaranteed zero. Without it they would be garbage.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links