---
title: "53 C Programs for Beginners With Output (Practice List)"
description: "53 C programs for beginners with code and real output: basics, loops, patterns, arrays, strings, pointers, structures and files. All compiled and run."
slug: c-programs-for-beginners
canonical: https://learn.modernagecoders.com/blog/c-programs-for-beginners/
date: 2026-11-15
dateModified: 2026-11-15
category: "Programming"
tags: ["C", "Programming", "Beginners", "Practice"]
keywords: ["c programs for beginners", "c programs with output", "basic c programs", "c programming examples for beginners", "c programs for practice", "simple c programs", "c pattern programs", "c programs pdf"]
readTime: "21 min read"
author: "Modern Age Coders Team"
---
# 53 C Programs for Beginners, With Output

> From Hello World to pointers, structures and files: every program compiled, run, and shown with the exact output it printed.

![53 C programs for beginners with code and output](/images/blog/c-programs-for-beginners/00-hero.png)

*By Modern Age Coders Team · 2026-11-15 · 21 min read*

**Quick answer:** This page has 53 C programs for beginners, each compiled with clang and run, with its exact output: basics and input, if-else and switch, loops and number programs, patterns, arrays and matrices, strings, functions, recursion, pointers, structures and file handling. It also explains how to compile and run C, the most common beginner mistakes, and a 12-problem practice list.

Here are **53 C programs for beginners**, each with its full code and the exact output it printed when we compiled and ran it. They start with Hello World and simple input, then move through if-else and switch, loops and number programs, patterns, arrays and matrices, strings, and finally functions, recursion, pointers, structures and files. Work through them in order and you will have practised every topic a first C course or exam covers.

Each program is short, self-contained and uses fixed sample values, so it runs the moment you compile it. A few read input with `scanf()`, and for those the output box shows exactly what appeared on screen, including what we typed. At the end you will find the mistakes beginners make most often, and a practice list to try on your own.

> **How these were tested**

> Every program was saved as a .c file, compiled with `cc -std=c11 -Wall -Wextra` (Apple clang 17) with zero warnings, and run in a terminal. The output boxes are copied from that run, character for character. GCC on Windows or Linux gives the same output, except the `sizeof` program, whose sizes depend on the system.

## How to compile and run a C program

C is a compiled language: a compiler turns your source file into a program your computer can run, and then you run that program. You need a compiler once, and then it is two commands per program.

- **Windows:** install a GCC compiler such as MinGW-w64, or an IDE that bundles one, such as Code::Blocks.
- **Mac:** run `xcode-select --install` in Terminal to get clang (the `cc` and `gcc` commands both work after that).
- **Linux:** GCC is usually installed already; if not, install the `gcc` or `build-essential` package.
- **No install at all:** an online C compiler works for every program here except the file program, which needs a real folder to write to.

**Terminal**

```bash
cc hello.c -o hello      # compile (use gcc on Windows or Linux)
./hello                  # run (on Windows: hello.exe)
```

If the compiler prints an error, read the first one only, fix it, and compile again. Later errors are often caused by the first.

![How a C program runs: hello.c source code goes into the compiler (cc or gcc), which produces an executable file, which prints Hello, World! when run](/images/blog/c-programs-for-beginners/01-compile-run.png)

*Write, compile, run. The compiler is the step Python does not have.*

## All 53 C programs at a glance

Use this as a practice checklist. The programs get harder as the numbers go up, so a complete beginner can work straight down the list.

| No. | Program | Topic |
| --- | --- | --- |
| 1 | Hello, World | Basics |
| 2 | Add two numbers entered by the user | Basics |
| 3 | Swap two numbers using a third variable | Basics |
| 4 | Swap two numbers without a third variable | Basics |
| 5 | Size of the basic data types | Basics |
| 6 | Area and circumference of a circle | Basics |
| 7 | Simple interest | Basics |
| 8 | Celsius to Fahrenheit | Basics |
| 9 | ASCII value of a character | Basics |
| 10 | Even or odd | Decisions |
| 11 | Largest of three numbers | Decisions |
| 12 | Leap year check | Decisions |
| 13 | Vowel or consonant using switch | Decisions |
| 14 | Grade from marks | Decisions |
| 15 | Simple calculator using switch | Decisions |
| 16 | Roots of a quadratic equation | Decisions |
| 17 | Sum of the first n natural numbers | Loops and number programs |
| 18 | Factorial of a number | Loops and number programs |
| 19 | Multiplication table | Loops and number programs |
| 20 | Fibonacci series | Loops and number programs |
| 21 | Prime number check | Loops and number programs |
| 22 | All prime numbers from 1 to 50 | Loops and number programs |
| 23 | Reverse a number | Loops and number programs |
| 24 | Palindrome number | Loops and number programs |
| 25 | Armstrong numbers from 100 to 999 | Loops and number programs |
| 26 | Sum and count of digits | Loops and number programs |
| 27 | GCD and LCM of two numbers | Loops and number programs |
| 28 | Power of a number using a loop | Loops and number programs |
| 29 | Right triangle of stars | Pattern programs |
| 30 | Pyramid of stars | Pattern programs |
| 31 | Floyd's triangle | Pattern programs |
| 32 | Number triangle | Pattern programs |
| 33 | Sum and average of an array | Arrays and matrices |
| 34 | Largest and smallest element | Arrays and matrices |
| 35 | Reverse an array | Arrays and matrices |
| 36 | Linear search | Arrays and matrices |
| 37 | Bubble sort | Arrays and matrices |
| 38 | Binary search | Arrays and matrices |
| 39 | Second largest element | Arrays and matrices |
| 40 | Addition of two matrices | Arrays and matrices |
| 41 | Transpose of a matrix | Arrays and matrices |
| 42 | Multiplication of two matrices | Arrays and matrices |
| 43 | Length of a string without strlen() | Strings |
| 44 | Reverse a string | Strings |
| 45 | Palindrome string | Strings |
| 46 | Count vowels, consonants, digits and spaces | Strings |
| 47 | Convert a string to uppercase | Strings |
| 48 | A function that returns a value | Functions, recursion, pointers, structures and files |
| 49 | Factorial using recursion | Functions, recursion, pointers, structures and files |
| 50 | Swap two numbers using pointers | Functions, recursion, pointers, structures and files |
| 51 | Pointers and arrays | Functions, recursion, pointers, structures and files |
| 52 | Structure for student records | Functions, recursion, pointers, structures and files |
| 53 | Write to a file and read it back | Functions, recursion, pointers, structures and files |

### C programs for beginners as a PDF

To keep a printable copy, open this page and press Ctrl+P (Cmd+P on a Mac), then choose "Save as PDF". Every program and output prints in order. You will learn far more, though, by typing each program yourself and comparing your output with ours.

## Basics: output, input, variables and operators

Every C program starts in `main()`, prints with `printf()` and reads with `scanf()`. These nine programs are the grammar the rest of the list is built on.

### 1. Hello, World

**Task:** Print a message on the screen.

```c
#include <stdio.h>

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

**Output**

```text
Hello, World!
```

`#include <stdio.h>` brings in `printf()`. `\n` moves to a new line, and `return 0` tells the system the program finished normally.

### 2. Add two numbers entered by the user

**Task:** Read two integers with scanf() and print their sum.

```c
#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;
}
```

**Output (typed input included)**

```text
Enter two numbers: 25 17
Sum = 42
```

`&a` passes the address of `a`, so `scanf()` can store the number there. Forgetting the `&` is a classic crash.

### 3. Swap two numbers using a third variable

**Task:** Swap the values of two variables.

```c
#include <stdio.h>

int main(void) {
    int a = 10, b = 20, temp;
    printf("Before: a = %d, b = %d\n", a, b);
    temp = a;
    a = b;
    b = temp;
    printf("After:  a = %d, b = %d\n", a, b);
    return 0;
}
```

**Output**

```text
Before: a = 10, b = 20
After:  a = 20, b = 10
```

### 4. Swap two numbers without a third variable

**Task:** Swap two integers using only addition and subtraction.

```c
#include <stdio.h>

int main(void) {
    int a = 7, b = 3;
    a = a + b;   /* a = 10 */
    b = a - b;   /* b = 7  */
    a = a - b;   /* a = 3  */
    printf("a = %d, b = %d\n", a, b);
    return 0;
}
```

**Output**

```text
a = 3, b = 7
```

A favourite interview question. In real code, use the temporary variable: it is clearer and cannot overflow.

### 5. Size of the basic data types

**Task:** Print how many bytes each basic data type uses on this computer.

```c
#include <stdio.h>

int main(void) {
    printf("char:   %zu byte\n", sizeof(char));
    printf("int:    %zu bytes\n", sizeof(int));
    printf("float:  %zu bytes\n", sizeof(float));
    printf("double: %zu bytes\n", sizeof(double));
    printf("long:   %zu bytes\n", sizeof(long));
    return 0;
}
```

**Output**

```text
char:   1 byte
int:    4 bytes
float:  4 bytes
double: 8 bytes
long:   8 bytes
```

These are the sizes on our test machine, a 64-bit Mac. `char` is always 1 byte, but `int` and `long` can differ on other systems; on 64-bit Windows, `long` is 4 bytes.

### 6. Area and circumference of a circle

**Task:** Find the area and circumference of a circle of radius 7.

```c
#include <stdio.h>

#define PI 3.14159

int main(void) {
    float r = 7.0f;
    printf("Area = %.2f\n", PI * r * r);
    printf("Circumference = %.2f\n", 2 * PI * r);
    return 0;
}
```

**Output**

```text
Area = 153.94
Circumference = 43.98
```

`#define` creates a constant before compiling. `%.2f` prints two decimal places.

### 7. Simple interest

**Task:** Calculate simple interest for principal 10000, rate 6.5% and 3 years.

```c
#include <stdio.h>

int main(void) {
    float p = 10000, r = 6.5, t = 3;
    float si = p * r * t / 100;
    printf("Simple interest = %.2f\n", si);
    return 0;
}
```

**Output**

```text
Simple interest = 1950.00
```

### 8. Celsius to Fahrenheit

**Task:** Convert a temperature from Celsius to Fahrenheit.

```c
#include <stdio.h>

int main(void) {
    float c = 37.5;
    float f = c * 9 / 5 + 32;
    printf("%.1f C = %.1f F\n", c, f);
    return 0;
}
```

**Output**

```text
37.5 C = 99.5 F
```

### 9. ASCII value of a character

**Task:** Print the ASCII code of a character, and the character for a code.

```c
#include <stdio.h>

int main(void) {
    char ch = 'A';
    printf("ASCII value of %c is %d\n", ch, ch);
    printf("Character for 98 is %c\n", 98);
    return 0;
}
```

**Output**

```text
ASCII value of A is 65
Character for 98 is b
```

A `char` is stored as a small number. `%c` prints it as a character, `%d` as the number.

## Decisions: if, else and switch

Programs that choose. Watch the difference between `=` (assign) and `==` (compare); mixing them up is the most common beginner bug in C.

### 10. Even or odd

**Task:** Read a number and say whether it is even or odd.

```c
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    if (n % 2 == 0)
        printf("%d is even\n", n);
    else
        printf("%d is odd\n", n);
    return 0;
}
```

**Output (typed input included)**

```text
Enter a number: 47
47 is odd
```

### 11. Largest of three numbers

**Task:** Find the largest of three numbers using if-else.

```c
#include <stdio.h>

int main(void) {
    int a = 42, b = 87, c = 19;
    if (a >= b && a >= c)
        printf("Largest = %d\n", a);
    else if (b >= c)
        printf("Largest = %d\n", b);
    else
        printf("Largest = %d\n", c);
    return 0;
}
```

**Output**

```text
Largest = 87
```

### 12. Leap year check

**Task:** Check whether some years are leap years.

```c
#include <stdio.h>

int main(void) {
    int years[] = {1900, 2000, 2024, 2026};
    for (int i = 0; i < 4; i++) {
        int y = years[i];
        if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
            printf("%d is a leap year\n", y);
        else
            printf("%d is not a leap year\n", y);
    }
    return 0;
}
```

**Output**

```text
1900 is not a leap year
2000 is a leap year
2024 is a leap year
2026 is not a leap year
```

1900 is divisible by 4 but also by 100 (and not 400), so it is not a leap year. Testing the edge cases is the point of this program.

### 13. Vowel or consonant using switch

**Task:** Use a switch statement to classify a character.

```c
#include <stdio.h>

int main(void) {
    char ch = 'e';
    switch (ch) {
        case 'a': case 'e': case 'i': case 'o': case 'u':
        case 'A': case 'E': case 'I': case 'O': case 'U':
            printf("%c is a vowel\n", ch);
            break;
        default:
            printf("%c is a consonant\n", ch);
    }
    return 0;
}
```

**Output**

```text
e is a vowel
```

Stacking several `case` labels lets them share one block of code.

### 14. Grade from marks

**Task:** Print a grade for given marks using an if-else ladder.

```c
#include <stdio.h>

int main(void) {
    int marks = 76;
    char grade;
    if (marks >= 90) grade = 'A';
    else if (marks >= 75) grade = 'B';
    else if (marks >= 60) grade = 'C';
    else if (marks >= 40) grade = 'D';
    else grade = 'F';
    printf("Marks %d, grade %c\n", marks, grade);
    return 0;
}
```

**Output**

```text
Marks 76, grade B
```

### 15. Simple calculator using switch

**Task:** Perform +, -, * or / on two numbers based on an operator.

```c
#include <stdio.h>

int main(void) {
    double a, b;
    char op;
    printf("Enter expression (e.g. 8 * 5): ");
    scanf("%lf %c %lf", &a, &op, &b);
    switch (op) {
        case '+': printf("Result = %.2f\n", a + b); break;
        case '-': printf("Result = %.2f\n", a - b); break;
        case '*': printf("Result = %.2f\n", a * b); break;
        case '/':
            if (b != 0) printf("Result = %.2f\n", a / b);
            else printf("Cannot divide by zero\n");
            break;
        default: printf("Unknown operator\n");
    }
    return 0;
}
```

**Output (typed input included)**

```text
Enter expression (e.g. 8 * 5): 22 / 7
Result = 3.14
```

`%lf` reads a `double` in `scanf()`. The space before `%c` skips the space you typed before the operator.

### 16. Roots of a quadratic equation

**Task:** Find the roots of ax&sup2; + bx + c = 0 using the discriminant.

```c
#include <stdio.h>
#include <math.h>

int main(void) {
    double a = 1, b = -5, c = 6;
    double d = b * b - 4 * a * c;
    if (d > 0) {
        printf("Two real roots: %.2f and %.2f\n",
               (-b + sqrt(d)) / (2 * a), (-b - sqrt(d)) / (2 * a));
    } else if (d == 0) {
        printf("One real root: %.2f\n", -b / (2 * a));
    } else {
        printf("Complex roots: %.2f + %.2fi and %.2f - %.2fi\n",
               -b / (2 * a), sqrt(-d) / (2 * a), -b / (2 * a), sqrt(-d) / (2 * a));
    }
    return 0;
}
```

**Output**

```text
Two real roots: 3.00 and 2.00
```

`sqrt()` lives in `math.h`. On Linux you may need to add `-lm` when compiling to link the maths library.

## Loops and number programs

for, while and do-while, used on the number problems every C course and exam returns to.

### 17. Sum of the first n natural numbers

**Task:** Add 1 + 2 + ... + n with a for loop.

```c
#include <stdio.h>

int main(void) {
    int n = 100, sum = 0;
    for (int i = 1; i <= n; i++)
        sum += i;
    printf("Sum of 1 to %d = %d\n", n, sum);
    return 0;
}
```

**Output**

```text
Sum of 1 to 100 = 5050
```

### 18. Factorial of a number

**Task:** Find n! using a loop.

```c
#include <stdio.h>

int main(void) {
    int n = 10;
    unsigned long long fact = 1;
    for (int i = 2; i <= n; i++)
        fact *= i;
    printf("%d! = %llu\n", n, fact);
    return 0;
}
```

**Output**

```text
10! = 3628800
```

Factorials grow fast. An `int` overflows after 12!, so we use `unsigned long long`, which holds up to 20!.

### 19. Multiplication table

**Task:** Print the multiplication table of 7.

```c
#include <stdio.h>

int main(void) {
    int n = 7;
    for (int i = 1; i <= 10; i++)
        printf("%d x %2d = %2d\n", n, i, n * i);
    return 0;
}
```

**Output**

```text
7 x  1 =  7
7 x  2 = 14
7 x  3 = 21
7 x  4 = 28
7 x  5 = 35
7 x  6 = 42
7 x  7 = 49
7 x  8 = 56
7 x  9 = 63
7 x 10 = 70
```

`%2d` pads numbers to two characters so the columns line up.

### 20. Fibonacci series

**Task:** Print the first 15 Fibonacci numbers.

```c
#include <stdio.h>

int main(void) {
    int a = 0, b = 1;
    for (int i = 0; i < 15; i++) {
        printf("%d ", a);
        int next = a + b;
        a = b;
        b = next;
    }
    printf("\n");
    return 0;
}
```

**Output**

```text
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 
```

### 21. Prime number check

**Task:** Check whether a number is prime.

```c
#include <stdio.h>

int main(void) {
    int n;
    printf("Enter a number: ");
    scanf("%d", &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");
    return 0;
}
```

**Output (typed input included)**

```text
Enter a number: 97
97 is prime
```

The loop runs only while `i * i <= n`, so 97 needs just 8 checks instead of 95.

### 22. All prime numbers from 1 to 50

**Task:** Print every prime number up to 50 using nested loops.

```c
#include <stdio.h>

int main(void) {
    for (int n = 2; n <= 50; n++) {
        int isPrime = 1;
        for (int i = 2; i * i <= n; i++)
            if (n % i == 0) { isPrime = 0; break; }
        if (isPrime) printf("%d ", n);
    }
    printf("\n");
    return 0;
}
```

**Output**

```text
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 
```

### 23. Reverse a number

**Task:** Reverse the digits of a number using a while loop.

```c
#include <stdio.h>

int main(void) {
    int n = 12345, rev = 0;
    while (n != 0) {
        rev = rev * 10 + n % 10;
        n /= 10;
    }
    printf("Reversed = %d\n", rev);
    return 0;
}
```

**Output**

```text
Reversed = 54321
```

`n % 10` gives the last digit and `n / 10` removes it, because integer division in C drops the decimal part.

### 24. Palindrome number

**Task:** Check whether a number reads the same backwards.

```c
#include <stdio.h>

int main(void) {
    int n = 1221, original = n, rev = 0;
    while (n > 0) {
        rev = rev * 10 + n % 10;
        n /= 10;
    }
    if (rev == original)
        printf("%d is a palindrome\n", original);
    else
        printf("%d is not a palindrome\n", original);
    return 0;
}
```

**Output**

```text
1221 is a palindrome
```

### 25. Armstrong numbers from 100 to 999

**Task:** Print all three-digit Armstrong numbers (the sum of the cubes of the digits equals the number).

```c
#include <stdio.h>

int main(void) {
    for (int n = 100; n <= 999; n++) {
        int t = n, sum = 0;
        while (t > 0) {
            int d = t % 10;
            sum += d * d * d;
            t /= 10;
        }
        if (sum == n) printf("%d ", n);
    }
    printf("\n");
    return 0;
}
```

**Output**

```text
153 370 371 407 
```

### 26. Sum and count of digits

**Task:** Find the sum of the digits of a number and how many digits it has, using do-while.

```c
#include <stdio.h>

int main(void) {
    int n = 90817, sum = 0, count = 0;
    do {
        sum += n % 10;
        count++;
        n /= 10;
    } while (n > 0);
    printf("Digits = %d, sum = %d\n", count, sum);
    return 0;
}
```

**Output**

```text
Digits = 5, sum = 25
```

A do-while loop always runs at least once, so the number 0 correctly counts as one digit.

### 27. GCD and LCM of two numbers

**Task:** Find the GCD with Euclid's algorithm, then the LCM.

```c
#include <stdio.h>

int main(void) {
    int a = 48, b = 180, x = a, y = b;
    while (y != 0) {
        int r = x % y;
        x = y;
        y = r;
    }
    printf("GCD = %d\n", x);
    printf("LCM = %d\n", a / x * b);
    return 0;
}
```

**Output**

```text
GCD = 12
LCM = 720
```

Dividing before multiplying (`a / x * b`) keeps the numbers small and avoids overflow.

### 28. Power of a number using a loop

**Task:** Calculate base to the power exp without pow().

```c
#include <stdio.h>

int main(void) {
    int base = 3, exp = 5;
    long result = 1;
    for (int i = 0; i < exp; i++)
        result *= base;
    printf("%d^%d = %ld\n", base, exp, result);
    return 0;
}
```

**Output**

```text
3^5 = 243
```

## Pattern programs

Nested loops: the outer loop picks the row, the inner loop prints what is on it.

### 29. Right triangle of stars

**Task:** Print a right-angled triangle of stars with 5 rows.

```c
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= i; j++)
            printf("* ");
        printf("\n");
    }
    return 0;
}
```

**Output**

```text
* 
* * 
* * * 
* * * * 
* * * * * 
```

### 30. Pyramid of stars

**Task:** Print a centred pyramid with 5 rows.

```c
#include <stdio.h>

int main(void) {
    int n = 5;
    for (int i = 1; i <= n; i++) {
        for (int s = 1; s <= n - i; s++)
            printf(" ");
        for (int j = 1; j <= 2 * i - 1; j++)
            printf("*");
        printf("\n");
    }
    return 0;
}
```

**Output**

```text
    *
   ***
  *****
 *******
*********
```

Each row has n &minus; i spaces and 2i &minus; 1 stars. Work out those two formulas on paper first and the code writes itself.

### 31. Floyd's triangle

**Task:** Print Floyd's triangle with 5 rows.

```c
#include <stdio.h>

int main(void) {
    int k = 1;
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= i; j++)
            printf("%3d", k++);
        printf("\n");
    }
    return 0;
}
```

**Output**

```text
  1
  2  3
  4  5  6
  7  8  9 10
 11 12 13 14 15
```

### 32. Number triangle

**Task:** Print rows 1, 1 2, 1 2 3 and so on.

```c
#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 5; i++) {
        for (int j = 1; j <= i; j++)
            printf("%d ", j);
        printf("\n");
    }
    return 0;
}
```

**Output**

```text
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
```

## Arrays and matrices

An array stores many values of one type under one name. Indexes start at 0, and C does not check them for you, so stay inside the size you declared.

### 33. Sum and average of an array

**Task:** Find the sum and average of the elements of an array.

```c
#include <stdio.h>

int main(void) {
    int a[] = {12, 45, 7, 23, 56, 89, 34};
    int n = sizeof(a) / sizeof(a[0]);
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += a[i];
    printf("Sum = %d\n", sum);
    printf("Average = %.2f\n", (float)sum / n);
    return 0;
}
```

**Output**

```text
Sum = 266
Average = 38.00
```

`sizeof(a) / sizeof(a[0])` counts the elements. The `(float)` cast stops integer division from cutting off the decimals.

### 34. Largest and smallest element

**Task:** Find the largest and smallest values in an array.

```c
#include <stdio.h>

int main(void) {
    int a[] = {34, -5, 78, 12, 99, 0, 41};
    int n = 7, max = a[0], min = a[0];
    for (int i = 1; i < n; i++) {
        if (a[i] > max) max = a[i];
        if (a[i] < min) min = a[i];
    }
    printf("Largest = %d, smallest = %d\n", max, min);
    return 0;
}
```

**Output**

```text
Largest = 99, smallest = -5
```

### 35. Reverse an array

**Task:** Reverse an array in place by swapping from both ends.

```c
#include <stdio.h>

int main(void) {
    int a[] = {1, 2, 3, 4, 5, 6};
    int n = 6;
    for (int i = 0, j = n - 1; i < j; i++, j--) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
    for (int i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}
```

**Output**

```text
6 5 4 3 2 1 
```

### 36. Linear search

**Task:** Search for a value in an array, one element at a time.

```c
#include <stdio.h>

int main(void) {
    int a[] = {15, 8, 42, 23, 4, 16};
    int n = 6, key = 23, pos = -1;
    for (int i = 0; i < n; i++) {
        if (a[i] == key) {
            pos = i;
            break;
        }
    }
    if (pos >= 0)
        printf("%d found at index %d\n", key, pos);
    else
        printf("%d not found\n", key);
    return 0;
}
```

**Output**

```text
23 found at index 3
```

### 37. Bubble sort

**Task:** Sort an array in ascending order using bubble sort.

```c
#include <stdio.h>

int main(void) {
    int a[] = {64, 34, 25, 12, 22, 11, 90};
    int n = 7;
    for (int i = 0; i < n - 1; i++)
        for (int j = 0; j < n - 1 - i; j++)
            if (a[j] > a[j + 1]) {
                int t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
            }
    printf("Sorted: ");
    for (int i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}
```

**Output**

```text
Sorted: 11 12 22 25 34 64 90 
```

After each pass the largest remaining value has "bubbled" to the end, which is why the inner loop gets shorter by one each time (`n - 1 - i`).

### 38. Binary search

**Task:** Search a sorted array by halving the range each step.

```c
#include <stdio.h>

int main(void) {
    int a[] = {3, 9, 14, 21, 35, 47, 58, 62, 77, 90};
    int n = 10, key = 58, low = 0, high = n - 1, steps = 0;
    while (low <= high) {
        int mid = (low + high) / 2;
        steps++;
        if (a[mid] == key) {
            printf("%d found at index %d in %d steps\n", key, mid, steps);
            return 0;
        } else if (a[mid] < key) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    printf("%d not found\n", key);
    return 0;
}
```

**Output**

```text
58 found at index 6 in 4 steps
```

Binary search only works on sorted data. Each step throws away half of what is left, so 1,000 items need at most 10 steps.

### 39. Second largest element

**Task:** Find the second largest distinct value in one pass.

```c
#include <stdio.h>

int main(void) {
    int a[] = {12, 35, 1, 10, 34, 35, 1};
    int n = 7, first = a[0], second = -1;
    for (int i = 1; i < n; i++) {
        if (a[i] > first) {
            second = first;
            first = a[i];
        } else if (a[i] < first && a[i] > second) {
            second = a[i];
        }
    }
    printf("Largest = %d, second largest = %d\n", first, second);
    return 0;
}
```

**Output**

```text
Largest = 35, second largest = 34
```

35 appears twice. The `a[i] < first` check stops the duplicate from being counted as the second largest. (Starting `second` at &minus;1 assumes the values are not negative.)

### 40. Addition of two matrices

**Task:** Add two 2 by 3 matrices.

```c
#include <stdio.h>

int main(void) {
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int b[2][3] = {{6, 5, 4}, {3, 2, 1}};
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++)
            printf("%d ", a[i][j] + b[i][j]);
        printf("\n");
    }
    return 0;
}
```

**Output**

```text
7 7 7 
7 7 7 
```

### 41. Transpose of a matrix

**Task:** Swap the rows and columns of a 2 by 3 matrix.

```c
#include <stdio.h>

int main(void) {
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
    for (int j = 0; j < 3; j++) {
        for (int i = 0; i < 2; i++)
            printf("%d ", a[i][j]);
        printf("\n");
    }
    return 0;
}
```

**Output**

```text
1 4 
2 5 
3 6 
```

Reading columns in the outer loop prints the 3 by 2 transpose without needing a second array.

### 42. Multiplication of two matrices

**Task:** Multiply a 2 by 3 matrix by a 3 by 2 matrix.

```c
#include <stdio.h>

int main(void) {
    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int b[3][2] = {{7, 8}, {9, 10}, {11, 12}};
    int c[2][2] = {0};
    for (int i = 0; i < 2; i++)
        for (int j = 0; j < 2; j++)
            for (int k = 0; k < 3; k++)
                c[i][j] += a[i][k] * b[k][j];
    for (int i = 0; i < 2; i++)
        printf("%d %d\n", c[i][0], c[i][1]);
    return 0;
}
```

**Output**

```text
58 64
139 154
```

Entry (i, j) is row i of the first matrix times column j of the second, added up: 1&times;7 + 2&times;9 + 3&times;11 = 58.

## Strings

In C a string is an array of `char` ending in a hidden `'\0'` character. Doing these by hand first shows you what library functions like `strlen()` really do.

### 43. Length of a string without strlen()

**Task:** Count the characters in a string by looking for the terminating '\0'.

```c
#include <stdio.h>

int main(void) {
    char s[] = "Programming";
    int len = 0;
    while (s[len] != '\0')
        len++;
    printf("Length of \"%s\" = %d\n", s, len);
    return 0;
}
```

**Output**

```text
Length of "Programming" = 11
```

### 44. Reverse a string

**Task:** Reverse a string in place.

```c
#include <stdio.h>
#include <string.h>

int main(void) {
    char s[] = "beginner";
    int n = strlen(s);
    for (int i = 0; i < n / 2; i++) {
        char t = s[i];
        s[i] = s[n - 1 - i];
        s[n - 1 - i] = t;
    }
    printf("%s\n", s);
    return 0;
}
```

**Output**

```text
rennigeb
```

### 45. Palindrome string

**Task:** Check whether a word is a palindrome.

```c
#include <stdio.h>
#include <string.h>

int main(void) {
    char s[] = "racecar";
    int n = strlen(s), ok = 1;
    for (int i = 0; i < n / 2; i++)
        if (s[i] != s[n - 1 - i]) { ok = 0; break; }
    printf("%s %s a palindrome\n", s, ok ? "is" : "is not");
    return 0;
}
```

**Output**

```text
racecar is a palindrome
```

### 46. Count vowels, consonants, digits and spaces

**Task:** Classify every character in a sentence.

```c
#include <stdio.h>
#include <ctype.h>

int main(void) {
    char s[] = "Room 204 has 3 windows and 2 doors";
    int v = 0, c = 0, d = 0, sp = 0;
    for (int i = 0; s[i]; i++) {
        char ch = tolower(s[i]);
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') v++;
        else if (isalpha(ch)) c++;
        else if (isdigit(ch)) d++;
        else if (ch == ' ') sp++;
    }
    printf("Vowels %d, consonants %d, digits %d, spaces %d\n", v, c, d, sp);
    return 0;
}
```

**Output**

```text
Vowels 8, consonants 14, digits 5, spaces 7
```

`ctype.h` provides `tolower()`, `isalpha()` and `isdigit()`. The loop condition `s[i]` stops at `'\0'`, which counts as false.

### 47. Convert a string to uppercase

**Task:** Change lowercase letters to uppercase using ASCII arithmetic.

```c
#include <stdio.h>

int main(void) {
    char s[] = "hello, c learners";
    for (int i = 0; s[i] != '\0'; i++)
        if (s[i] >= 'a' && s[i] <= 'z')
            s[i] = s[i] - 32;
    printf("%s\n", s);
    return 0;
}
```

**Output**

```text
HELLO, C LEARNERS
```

In ASCII, each lowercase letter is exactly 32 more than its capital ('a' is 97, 'A' is 65).

## Functions, recursion, pointers, structures and files

The ideas that make C, C: functions that call themselves, addresses you can pass around, your own data types, and saving data to a file.

### 48. A function that returns a value

**Task:** Write a function that returns the larger of two numbers, and call it.

```c
#include <stdio.h>

int max(int a, int b) {
    return a > b ? a : b;
}

int main(void) {
    printf("max(8, 13) = %d\n", max(8, 13));
    printf("max(-4, -9) = %d\n", max(-4, -9));
    return 0;
}
```

**Output**

```text
max(8, 13) = 13
max(-4, -9) = -4
```

### 49. Factorial using recursion

**Task:** Find factorials with a function that calls itself.

```c
#include <stdio.h>

long fact(int n) {
    if (n <= 1)
        return 1;          /* base case stops the recursion */
    return n * fact(n - 1);
}

int main(void) {
    for (int i = 1; i <= 6; i++)
        printf("%d! = %ld\n", i, fact(i));
    return 0;
}
```

**Output**

```text
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
```

Every recursive function needs a base case. Without `if (n <= 1)`, `fact()` would call itself until the program crashed.

### 50. Swap two numbers using pointers

**Task:** Write a swap function that changes the caller's variables.

```c
#include <stdio.h>

void swap(int *x, int *y) {
    int t = *x;
    *x = *y;
    *y = t;
}

int main(void) {
    int a = 5, b = 9;
    swap(&a, &b);
    printf("a = %d, b = %d\n", a, b);
    return 0;
}
```

**Output**

```text
a = 9, b = 5
```

C passes copies of arguments. Passing the addresses (`&a`, `&b`) lets the function reach the original variables through `*x` and `*y`.

![Memory diagram of swap using pointers: main has a = 5 and b = 9 at two addresses, swap receives x and y holding those addresses, and after the swap a = 9 and b = 5](/images/blog/c-programs-for-beginners/02-pointer-swap.png)

*x and y hold addresses, so *x and *y are the original a and b.*

### 51. Pointers and arrays

**Task:** Walk through an array using a pointer instead of an index.

```c
#include <stdio.h>

int main(void) {
    int a[] = {10, 20, 30, 40};
    int *p = a;                 /* same as &a[0] */
    for (int i = 0; i < 4; i++)
        printf("*(p + %d) = %d\n", i, *(p + i));
    printf("a[2] and *(a + 2) are both %d\n", *(a + 2));
    return 0;
}
```

**Output**

```text
*(p + 0) = 10
*(p + 1) = 20
*(p + 2) = 30
*(p + 3) = 40
a[2] and *(a + 2) are both 30
```

An array name works like a pointer to its first element, and `a[i]` is just a shorter way to write `*(a + i)`.

### 52. Structure for student records

**Task:** Store and print student records using a struct.

```c
#include <stdio.h>

struct Student {
    int roll;
    char name[20];
    float marks;
};

int main(void) {
    struct Student s[3] = {
        {1, "Ananya", 88.5f},
        {2, "Rahul", 74.0f},
        {3, "Sneha", 91.0f},
    };
    int top = 0;
    for (int i = 0; i < 3; i++) {
        printf("%d %-8s %.1f\n", s[i].roll, s[i].name, s[i].marks);
        if (s[i].marks > s[top].marks) top = i;
    }
    printf("Topper: %s\n", s[top].name);
    return 0;
}
```

**Output**

```text
1 Ananya   88.5
2 Rahul    74.0
3 Sneha    91.0
Topper: Sneha
```

A `struct` groups different types under one name. `%-8s` left-aligns the name in 8 characters so the marks line up.

### 53. Write to a file and read it back

**Task:** Write three lines to a text file, then read and print them.

```c
#include <stdio.h>

int main(void) {
    FILE *fp = fopen("notes.txt", "w");
    if (fp == NULL) {
        printf("Could not open file\n");
        return 1;
    }
    fprintf(fp, "Line 1: C is fast\n");
    fprintf(fp, "Line 2: C is close to the hardware\n");
    fprintf(fp, "Line 3: C is everywhere\n");
    fclose(fp);

    char line[100];
    fp = fopen("notes.txt", "r");
    while (fgets(line, sizeof(line), fp) != NULL)
        printf("%s", line);
    fclose(fp);
    return 0;
}
```

**Output**

```text
Line 1: C is fast
Line 2: C is close to the hardware
Line 3: C is everywhere
```

Always check that `fopen()` did not return `NULL`, and always `fclose()` what you open. `fgets()` returns `NULL` at the end of the file.

## Common mistakes beginners make in C

Most C bugs in a first course are the same handful. Check for these before anything else:

- **Missing & in scanf():** `scanf("%d", n)` compiles with only a warning, then crashes or reads garbage. It must be `&n`.
- **= instead of ==:** `if (x = 5)` assigns 5 and is always true. Turn on warnings (`-Wall`) and the compiler will point it out.
- **A semicolon after if or for:** `for (i = 0; i < 5; i++);` runs an empty loop, then the block below runs once.
- **Integer division:** `7 / 2` is 3 in C. Make one side a float (`7.0 / 2`) when you want 3.5.
- **Going past the end of an array:** an array of size 5 has indexes 0 to 4. C will not stop you reading `a[5]`; it just gives you whatever is there.
- **Forgetting the '\0':** a string of 5 letters needs an array of at least 6 chars.
- **Wrong format specifier:** `%d` for int, `%f` for float or double in printf, `%lf` for double in scanf, `%c` for char, `%s` for strings.

> **Predict, then run**

> Before you run any program on this page, write down what you think it will print. When you are wrong, you have found exactly the line you did not understand. That habit does more for your C than reading ten more programs.

## Practice list: C programs to try on your own

Each of these uses only ideas from the programs above. Try them without looking anything up, then compare your approach with the nearest program in the list.

1. Print all even numbers between 1 and 50 (use `i += 2`).
2. Read a number and print its multiplication table up to 20.
3. Check whether a number is a perfect number (equal to the sum of its divisors, like 28).
4. Count how many times a given digit appears in a number.
5. Convert a decimal number to binary using a loop and an array.
6. Print an inverted pyramid of stars.
7. Find the sum of the elements on the main diagonal of a 3 by 3 matrix.
8. Remove all spaces from a string.
9. Write a recursive function for the nth Fibonacci number.
10. Store 5 books in an array of structs and print the most expensive one.
11. Sort an array in descending order with selection sort.
12. Count the lines, words and characters in a text file.

## Which C programs to learn first

If you are a school student or in your first semester of BCA, B.Tech or B.Sc, this order works well:

- **Week 1:** programs 1 to 16 (basics and decisions).
- **Week 2:** programs 17 to 32 (loops, number programs and patterns).
- **Week 3:** programs 33 to 42 (arrays and matrices).
- **Week 4:** programs 43 to 53 (strings, functions, recursion, pointers, structures and files).

Recursion and pointers are where most beginners slow down, and that is normal. Our guide to [recursion for beginners](/blog/recursion-explained-for-beginners) walks through what happens on each call, and [how to start learning data structures and algorithms](/blog/how-to-start-learning-data-structures-and-algorithms) shows where these programs lead next.

## How we teach it

Our [how we teach](/how-we-teach) page sets out the method: students explain their thinking, trace a loop line by line until they can predict every step, and treat mistakes as data rather than failures. In C that means drawing the memory boxes for a pointer before writing `*x`, and reading a compiler error out loud before fixing it. Our [C programming course for college beginners](/courses/c-programming-course-for-college-beginners) builds from these programs to pointers, memory and real projects, and our [learn coding from first principles](/learn-coding-from-first-principles) page explains the approach. The first class is free.

[Book a free class](/book-demo) [Book a priority demo](/book-demo)

## Frequently asked questions

**What are the basic C programs for beginners?**

Hello World, adding two numbers, swapping two numbers, even or odd, largest of three numbers, leap year, factorial, Fibonacci series, prime number check, reversing a number, palindrome, multiplication table, and simple star patterns. All of them are on this page with their output.

**How do I run a C program?**

Save the code in a file ending in .c, compile it with cc or gcc (for example cc hello.c -o hello), then run the program it creates (./hello on Mac or Linux, hello.exe on Windows). An IDE such as Code::Blocks does both steps with one button.

**Is C good for beginners?**

C is harder than Python because you manage more details yourself, such as data types, array sizes and memory. That is also why it teaches how computers really work. If you are under about 12, a gentler first language usually makes more sense.

**What is the difference between C and C++?**

C++ began as an extension of C, so most of these programs work in C++ too. C++ adds classes and objects, references, function overloading, templates and the standard library (string, vector, map). Our C++ programs for beginners page has the C++ versions.

**How many C programs should I practise?**

Quality beats quantity. If you can write the 53 programs here from memory, explain each line, and solve the 12 practice problems on your own, you have covered a full first course in C.

**Why does my C program close immediately on Windows?**

If you double-click the .exe, the window closes when the program ends. Run it from a terminal (Command Prompt or PowerShell) instead, or run it from your IDE, which keeps the window open.

**Why is scanf() skipping my input?**

Usually a leftover newline from the previous scanf(). When you read a character with %c, put a space before it (" %c") to skip whitespace, as in the calculator program.

**Where can I get these C programs as a PDF?**

Use your browser: open this page, press Ctrl+P or Cmd+P and choose Save as PDF. Every program and output prints in order.

Moving on to C++? Our [C++ programs for beginners](/blog/cpp-programs-for-beginners) covers the same ground with classes, strings, vectors and the standard library.

---

*Source: https://learn.modernagecoders.com/blog/c-programs-for-beginners/*
