Ardowi
Ardowi

Reputation: 59

Using Multiples in C

I'm trying to teach myself C and have only done a few things in CodeAcademy so far. I'm pretty lacking when it comes to loops in my current online course. Let's say I wanted to use a loop to make the first 5 multiples of 1 through 10 like below.

Number  1st     2nd     3rd     4th     5th
1       1       2       3       4       5
2       2       4       6       8       10
3       3       6       9       12      15
4       4       8       12      16      20
5       5       10      15      20      25
6       6       12      18      24      30
7       7       14      21      28      35
8       8       16      24      32      40
9       9       18      27      36      45
10      10      20      30      40      50

I'm drawing a blank on how I would use loop nesting or even a single loop to do the above. Anyone have any advice on where to start, I'm not understanding this I guess.

Upvotes: 0

Views: 768

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40145

see printf description

#include <stdio.h>

int main(void){
    char *field_name[] = {"Number", "1st", "2nd", "3rd", "4th", "5th" };
    int field_size = 10;
    int num_of_fields = 6;
    int number_max = 10;

    //print field_name
    for(int i = 0; i < num_of_fields; ++i)
        printf("%-*s", field_size, field_name[i]);
    puts("");
    //print numbers
    for(int n = 1; n <= number_max; ++n){
        printf("%-*d", field_size, n);
        for(int i = 1; i < num_of_fields; ++i)
            printf("%-*d", field_size, n * i);
        puts("");
    }
    return 0;
}

Upvotes: 0

user1084944
user1084944

Reputation:

A big part of programming is about breaking larger problems into smaller problems.

If the problem of making this table is too much for you, then break the problem into pieces. e.g.

  • Write a function that can print the header
  • Write a function capable of printing one line of the table
  • Write a program that uses those two functions to print the whole table

Upvotes: 1

Related Questions