Beginner Logical Thinking C

C Programs for Beginners with Output

Write and run the basic C programs that first-year lab exams ask for, and read their output correctly.

  • TimeO(1) for the decision programs, O(d) for digit programs (d = number of digits), O(sqrt n) for the prime check
  • SpaceO(1)
  • Hints3
  • Read4 min
Quick answer

The basic C programs for beginners are hello world, add two numbers, even or odd, largest of three, simple interest, temperature conversion, factorial, sum of digits, reverse a number and prime check. Each one uses printf to show output, scanf to read input, if-else to decide and a for or while loop to repeat. Practise them until you can write each one without notes.

printf and scanfif-elsefor and while loopsInteger division and modulus
1

Problem statement

These are the basic C programs that first-year B.Tech labs and viva exams ask again and again. For each one, write the code, compile it, give the sample input and check that your output matches.

The main program below has six of them as functions. Six more that read input with scanf are in the solution section. For loop practice, see loop programs in C.

Input

Fixed values in the main program. The scanf programs read numbers typed by the user.

Output

One line of output per program, as shown under each one.

Examples

Example 1
InputevenOdd(7)
Output7 is odd

7 % 2 is 1, so the else branch runs.

Example 2
InputreverseNumber(1234)
OutputReverse of 1234 is 4321

Each step takes the last digit with % 10 and adds it to rev * 10.

Constraints

  • Values fit in an int (about -2.1 billion to 2.1 billion on common compilers)
  • Factorial uses long long, which holds up to 20!
2

Think before you code

Reveal the questions to ask yourself first
  • Which header gives you printf and scanf?
  • Do you need a decision (if), a repeat (loop), or both?
  • Will the answer fit in an int, or do you need long long or float?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Every program starts with #include <stdio.h> and int main(void).
2 Hint 2
n % 10 gives the last digit and n / 10 removes it. Many number programs use this pair.
3 Hint 3
In scanf, put & before each int or float variable, for example scanf("%d", &a).
4

Approach

Reveal the step-by-step approach

How to write any basic C program

  1. Input: fix the values, or read them with scanf.
  2. Process: use if-else for decisions and a loop for repeated work.
  3. Output: print with printf and a format code.
Format code Type Example
%d int printf("%d", 25);
%lld long long printf("%lld", fact);
%f, %.2f float printf("%.2f", 3.14159); prints 3.14
%c char printf("%c", 'A');
%s string printf("%s", "hi");

The digit trick

Sum of digits, reverse a number, count digits and Armstrong numbers all use the same loop:

while (n > 0) {
    int d = n % 10;   /* last digit */
    /* use d here */
    n = n / 10;       /* drop the last digit */
}

If you are new to C, read learn C programming step by step first.

5

Dry run

Walk through the example step by step

reverseNumber(1234). rev starts at 0.

n    | n % 10 | rev = rev * 10 + n % 10 | n / 10
-----+--------+-------------------------+-------
1234 | 4      | 4                       | 123
123  | 3      | 43                      | 12
12   | 2      | 432                     | 1
1    | 1      | 4321                    | 0

The loop stops when n becomes 0. rev is 4321.

6

Solution

Reveal the full C solution
solution.c
#include <stdio.h>

/* 1. Even or odd */
void evenOdd(int n) {
    if (n % 2 == 0) {
        printf("%d is even\n", n);
    } else {
        printf("%d is odd\n", n);
    }
}

/* 2. Largest of three numbers */
void largest(int a, int b, int c) {
    int max = a;
    if (b > max) {
        max = b;
    }
    if (c > max) {
        max = c;
    }
    printf("Largest of %d, %d, %d is %d\n", a, b, c, max);
}

/* 3. Factorial */
void factorial(int n) {
    long long fact = 1;
    for (int i = 2; i <= n; i++) {
        fact = fact * i;
    }
    printf("%d! = %lld\n", n, fact);
}

/* 4. Sum of digits */
void sumOfDigits(int n) {
    int original = n, sum = 0;
    while (n > 0) {
        sum = sum + n % 10;
        n = n / 10;
    }
    printf("Sum of digits of %d is %d\n", original, sum);
}

/* 5. Reverse a number */
void reverseNumber(int n) {
    int original = n, rev = 0;
    while (n > 0) {
        rev = rev * 10 + n % 10;
        n = n / 10;
    }
    printf("Reverse of %d is %d\n", original, rev);
}

/* 6. Prime check */
void primeCheck(int n) {
    int isPrime = (n > 1);
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            isPrime = 0;
            break;
        }
    }
    printf("%d is %s\n", n, isPrime ? "prime" : "not prime");
}

int main(void) {
    evenOdd(7);
    largest(12, 45, 30);
    factorial(5);
    sumOfDigits(1234);
    reverseNumber(1234);
    primeCheck(29);
    primeCheck(21);
    return 0;
}

Output:

7 is odd
Largest of 12, 45, 30 is 45
5! = 120
Sum of digits of 1234 is 10
Reverse of 1234 is 4321
29 is prime
21 is not prime
  • Even or odd: n % 2 is 0 for even numbers.
  • Largest of three: assume the first is the largest, then compare the other two.
  • Factorial: multiply 2, 3, ... n. long long holds up to 20!, an int only up to 12!.
  • Prime check: test divisors only up to the square root, which is why the loop runs while i * i <= n. 21 fails at i = 3.

Basic C programs with sample input and output

The programs below read input with scanf. In the sample runs, the numbers after the prompt are what the user types.

7. Hello world

#include <stdio.h>

int main(void) {
    printf("Hello, World!\n");
    return 0;
}
Hello, World!

8. Add two numbers

#include <stdio.h>

int main(void) {
    int a, b;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);
    printf("Sum = %d\n", a + b);
    return 0;
}
Enter two numbers: 10 20
Sum = 30

9. Simple interest

#include <stdio.h>

int main(void) {
    float p, r, t, si;
    printf("Enter principal, rate and time: ");
    scanf("%f %f %f", &p, &r, &t);
    si = (p * r * t) / 100;
    printf("Simple interest = %.2f\n", si);
    return 0;
}
Enter principal, rate and time: 1000 5 2
Simple interest = 100.00

10. Celsius to Fahrenheit

#include <stdio.h>

int main(void) {
    float c, f;
    printf("Enter temperature in Celsius: ");
    scanf("%f", &c);
    f = c * 9 / 5 + 32;
    printf("%.2f C = %.2f F\n", c, f);
    return 0;
}
Enter temperature in Celsius: 37
37.00 C = 98.60 F

Because c is a float, c * 9 / 5 keeps the decimal part. With an int, 37 * 9 / 5 is 66, not 66.6.

11. Swap two numbers and 12. Fibonacci series have their own pages: swap without a third variable in C and Fibonacci series in C.

Simple C programs: practice list

Program Main idea
Area of a circle 3.14159 * r * r with float
Positive, negative or zero if, else if, else
Vowel or consonant switch on a char
Multiplication table for loop, see loop programs in C
Armstrong number digit loop, see Armstrong number in C
Sort an array see selection sort in C

These same programs are common in Java too. Compare them with the core Java practice problems.

TimeO(1) for the decision programs, O(d) for digit programs (d = number of digits), O(sqrt n) for the prime check
SpaceO(1)
7

Review before the interview

Common mistakes

  • Forgetting & in scanf, which makes the program crash or read garbage.
  • Using %d to print a float or long long, which prints wrong values.
  • Storing a factorial above 12! in an int, which overflows.
  • Writing if (n = 0) instead of if (n == 0). The first one assigns 0.
  • Missing \n at the end of printf, so the next output joins the same line.

Edge cases to test

  • Prime check: 0 and 1 are not prime, and 2 is prime.
  • Reverse of 1200 is 21, because leading zeros are not stored in an int.
  • Sum of digits for a negative number: the while (n > 0) loop does not run. Use the absolute value first.
  • 0! is 1.

Interview follow-ups

  • How would you check even or odd without the % operator?
  • How do you find the largest of three numbers with the ternary operator?
  • Why does the prime loop stop at the square root of n?

Keep practising

Building your programming basics?

CodeBegun’s programs build problem-solving with mentor review and mock interviews, online or in Madhapur, Hyderabad.

Chat with us