Write a program which requests two integers, m and n, and produces a table of squares from m to n inclusive.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

void swap(int *, int *);

int main(int argc, char ** argv) {
    int m, n;
    printf("Enter two integers: \n");
    scanf("%d%d", &m, &n);
    if ( m > n) {
        swap(&m, &n);
    }
    printf("Tables of squares from %d to %d inclusive\n", m, n);

    for (; m <= n; m++)
        printf("%d * %d = %d\n", m, m, m*m);

    return 0;
}

void swap(int * m, int *n) {
    int tmp;
    tmp = *m;
    *m = *n;
    *n = tmp;
}

When you compile and execute the above program it produces the following result on Linux:

Enter two integers: 
2
6
Tables of squares from 2 to 6 inclusive
2 * 2 = 4
3 * 3 = 9
4 * 4 = 16
5 * 5 = 25
6 * 6 = 36

Brief Explanation

  • scanf function reads two numbers inputted by the user and assign to the variables m and n.
  • If m is greater than n, the swap function is called which swaps the two numbers. i.e it assigns the value of n to m (lower value) and the value of m to n. Thus, it ensures that n is always greater than m.
  • Using a 'for' loop, a table of squares from m to n inclusive is produced and displayed to the stdout (printf function).

Add comment


Security code
Refresh