1.1. 각 자리 수 더하기 ¶
Write a program that reads a four digit integer and prints the sum of its digits as an output.
- Simple Implementation
#include <stdio.h> #include <math.h> int main(){ int four_digit_num, sum = 0, i, positional; scanf("%d", &four_digit_num); for(i = 3; i >= 0; i--){ positional = pow(10, i); sum += four_digit_num / positional; four_digit_num %= positional; } printf("%d\n", sum); return 0; }
- Basic Implementation
#include <stdio.h> int main(){ int four_digit_num, sum = 0, i, positional, j; scanf("%d", &four_digit_num); for(i = 3; i >= 0; i--){ positional = 1; for(j = 0; j < i; j++){ positional *= 10; } sum += four_digit_num / positional; four_digit_num %= positional; } printf("%d\n", sum); return 0; }
- Advanced Implementation
#include <stdio.h> #include <math.h> int main(){ int n_digit_num, sum = 0, positional, n; scanf("%d", &n_digit_num); n = log10(n_digit_num); if((n_digit_num >= pow(10, n)) && (n_digit_num < pow(10, n+1))){ for(; n >= 0; n--){ positional = pow(10, n); sum += n_digit_num / positional; n_digit_num %= positional; } printf("%d\n", sum); return 0; } exit(1); }
1.2. 별찍기 ¶
#include <stdio.h> int main() { int i,j; for (i = 0; i < 5; i++) { for (j = 4; j > i; j--) printf(" "); for (j = 0; j < 2*i+1; j++) printf("*"); printf("\n"); } return 0; }
1.3. 원리합계 구하기 ¶
Write a program that gets a starting principal(A, 원금), annual interest rate(r, 연이율) from a keyboard (standard input) and print the total amount on deposit (예치기간이 지난 뒤 총금액, 원리합계) for the year(n) from 0 to 10. total deposit = A*(1+r)^n
#include <stdio.h> int main(){ double a, r, interest = 1; int n; scanf("%lf %lf", &a, &r); for(n = 0; n <= 10; n++){ printf("%d\t%.2f\n", n, a * interest); interest *= 1+r; } return 0; }