본문 바로가기
프로그래밍 언어/C언어

재귀함수와 증감연산자

by 엉덩이싸움 2024. 4. 8.

Multiplication Tables with Recursion

Goal

Create a program to generate and print the multiplication table up to 10 for a given number N using recursion.

Concept Explanation

Multiplication tables are a basic mathematical tool used for learning multiplication.

They list the products of a number series multiplied by integers from 1 to 10.

Recursion is a programming technique where a function calls itself to solve smaller instances of the same problem.

By using recursion to generate multiplication tables, students can learn how to apply recursive thinking to break down and solve problems.

Question

Your task is to write a C program that:

Prompts the user to enter a number N.

Defines and uses a recursive function, print_table, to print the multiplication table for N from 1 to 10.

Each line of the table should be printed by a separate recursive call.

Constraints

Define the recursive function void print_table(int N, int i) where N is the number to generate the table for, and i is the current multiplier in the table, initially 1.

Use scanf to read the user's input and printf to output each line of the multiplication table.

The function should stop making recursive calls once i exceeds 10.

증감 연산자 설명
++x 피연산자 값을 1 증가시킨 후, 해당 연산 진행
x++ 먼저 해당 연산을 수행 후, 피연산자 값을 1 증가
--x 피연산자 값을 1 감소시킨 후, 해당 연산 진행
x-- 해당 연산을 수행 후, 피연산자 값 1 감소

재귀함수의 return값에서 증감연산자를 ++i가 아닌 i++를 쓰게되는 경우,

값을  return한 이후 증감되기 때문에 i  = 1로 무한반복이 일어남

#include <stdio.h>

int print_table(int N, int i);

int main(void)
{
    int N;
    int i = 1;
    scanf("%d", &N);

    print_table(N, i);

    return 0;
}

int print_table(int N, int i)
{
    if( i <= 10)
    {
        printf("%d X %d = %d\n", N, i, N*i);
        return print_table(N, ++i);
    }
    else return 0;
}