Algo Infinity Verse

Start Your Journey With C Programming Beginner-Friendly Concepts, Code & Practice

|
0 Topics
0 Examples
0 Exercises

🔵 Learn C

Master the fundamentals of C with clear explanations and hands-on examples

0 / 11 topics completed
01

Introduction to C

C is a powerful, general-purpose programming language developed by Dennis Ritchie at Bell Labs in 1972. It is one of the most influential languages ever created — the foundation for UNIX, Linux, Windows, and countless other systems. C combines the efficiency of assembly language with the readability of high-level languages.

Why Learn C?

  • Foundation of Modern Computing – C influenced C++, Java, Python, and many other languages
  • Systems Programming – Used for operating systems, embedded systems, and compilers
  • High Performance – Minimal runtime overhead, direct memory access
  • Portable – C compilers exist for virtually every platform
  • Essential for DSA – The language of choice for understanding data structures at a low level

Your first C program is the classic "Hello, World!":

C
#include <stdio.h>

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

Every C program needs a main() function — it's the entry point. #include <stdio.h> gives access to input/output functions like printf. return 0; signals successful execution.

02

Installation & Setup

To write and run C code, you need a C compiler and a text editor or IDE. The most common compilers are GCC (GNU Compiler Collection) and Clang.

Installing a Compiler

  • Linux – Install via package manager: sudo apt install gcc
  • macOS – Install Xcode Command Line Tools: xcode-select --install
  • Windows – Download MinGW-w64 or use Visual Studio with the "Desktop development with C++" workload
Bash
# Verify your compiler installation
gcc --version
clang --version

Choosing an IDE

  • VS Code – Lightweight with C/C++ extension pack (recommended)
  • Code::Blocks – Free, beginner-friendly IDE
  • CLion – Full-featured C/C++ IDE by JetBrains
Bash
# Compile and run a C program
gcc hello.c -o hello    # compiles to executable
./hello                 # runs the executable

C is a compiled language: you write .c source files, compile them to a machine-executable binary with gcc, and run the binary directly on your operating system.

03

Variables & Data Types

In C, every variable must have a declared type. C is statically typed — once you declare a variable's type, it cannot hold a different type of value.

C
#include <stdio.h>

int main() {
    int age = 25;               // Whole number
    float height = 5.7f;        // Decimal number (single precision)
    double pi = 3.14159;        // Decimal number (double precision)
    char grade = 'A';           // Single character
    char name[] = "Alice";     // String (character array)

    printf("%d\n", age);
    printf("%.1f\n", height);
    printf("%c\n", grade);
    printf("%s\n", name);
    return 0;
}
Output
25
5.7
A
Alice
Type Size Format Specifier Description
int4 bytes%dWhole number
float4 bytes%fSingle precision decimal
double8 bytes%lfDouble precision decimal
char1 byte%cSingle ASCII character
voidNo type (for functions)
💡

C does not have a built-in string type. Strings are represented as character arrays (char name[]) terminated by a null character \0. C also supports unsigned variants (unsigned int) and short/long modifiers.

Practice: Variables & Data Types

Create variables of different types and print them:

  1. Create an int variable score with value 95
  2. Create a float variable gpa with value 3.85
  3. Create a char array city[] with value "New York"
  4. Print each variable using printf with the correct format specifier
C
#include <stdio.h>

int main() {
    int score = 95;
    float gpa = 3.85f;
    char city[] = "New York";

    printf("Score: %d\n", score);
    printf("GPA: %.2f\n", gpa);
    printf("City: %s\n", city);
    return 0;
}
04

Input & Output (printf, scanf)

C uses printf() for output and scanf() for input. Both are defined in the <stdio.h> header and use format specifiers to handle different data types.

printf — Displaying Output

printf("format string", variables) prints formatted text. Common specifiers: %d (int), %f (float), %c (char), %s (string), %lf (double).

C
#include <stdio.h>

int main() {
    char name[] = "Alice";
    int age = 25;

    printf("My name is %s and I am %d years old.\n", name, age);
    printf("Name: %s | Age: %d\n", name, age);
    return 0;
}
Output
My name is Alice and I am 25 years old.
Name: Alice | Age: 25

scanf — Reading User Input

scanf("format", &variable) reads input from the console. The & operator gives the memory address of the variable (required for non-array types).

C
#include <stdio.h>

int main() {
    char name[50];
    int age;

    printf("What is your name? ");
    scanf("%s", name);

    printf("How old are you? ");
    scanf("%d", &age);

    printf("Hello, %s! In 10 years you will be %d.\n", name, age + 10);
    return 0;
}
⚠️

scanf("%s", name) reads only until the first whitespace — it won't read a full name like "John Doe". Use fgets(name, sizeof(name), stdin) to read an entire line including spaces. Always use & before non-array variables in scanf.

Practice: Input & Output

Write a program that asks the user for their name and favorite color, then prints a greeting.

  1. Include <stdio.h>
  2. Ask for name and favorite color using scanf
  3. Print: "Hello {name}, your favorite color is {color}!"
C
#include <stdio.h>

int main() {
    char name[50];
    char color[50];

    printf("Enter your name: ");
    scanf("%s", name);

    printf("Enter your favorite color: ");
    scanf("%s", color);

    printf("Hello %s, your favorite color is %s!\n", name, color);
    return 0;
}
05

Operators

Operators perform operations on variables and values. C supports arithmetic, assignment, comparison, logical, and bitwise operators.

Category Operators Example
Arithmetic+ - * / %10 + 5 → 15
Assignment= += -= *= /= %=x += 5
Comparison== != < > <= >=10 > 5 → 1 (true)
Logical&& || !1 && 0 → 0
Increment/Decrement++ --i++
Bitwise& | ^ ~ << >>5 & 3 → 1
C
#include <stdio.h>

int main() {
    int a = 10, b = 5;

    // Arithmetic
    int sum = a + b;
    int product = a * b;
    int remainder = a % b;

    // Comparison & Logical
    int isGreater = a > b;
    int bothPositive = (a > 0) && (b > 0);

    printf("Sum: %d\n", sum);
    printf("Product: %d\n", product);
    printf("Remainder: %d\n", remainder);
    printf("Is a > b? %d\n", isGreater);
    printf("Both positive? %d\n", bothPositive);
    return 0;
}
Output
Sum: 15
Product: 50
Remainder: 0
Is a > b? 1
Both positive? 1
Practice: Operators

Calculate the area and perimeter of a rectangle with width 8 and length 12.

  1. Create int variables width and length
  2. Calculate area = width * length
  3. Calculate perimeter = 2 * (width + length)
  4. Print both results using printf
C
#include <stdio.h>

int main() {
    int width = 8;
    int length = 12;
    int area = width * length;
    int perimeter = 2 * (width + length);

    printf("Area: %d\n", area);
    printf("Perimeter: %d\n", perimeter);
    return 0;
}
06

Conditional Statements

Conditionals let your program make decisions. C supports if, else if, else, and switch statements. In C, conditions evaluate to 0 (false) or non-zero (true).

C
#include <stdio.h>

int main() {
    int score = 85;
    char grade;

    if (score >= 90) {
        grade = 'A';
    } else if (score >= 80) {
        grade = 'B';
    } else if (score >= 70) {
        grade = 'C';
    } else {
        grade = 'F';
    }

    printf("Score: %d → Grade: %c\n", score, grade);
    return 0;
}
Output
Score: 85 → Grade: B

switch Statement

The switch statement is useful when checking a variable against many specific integer values.

C
#include <stdio.h>

int main() {
    int day = 3;

    switch (day) {
        case 1:  printf("Monday\n");    break;
        case 2:  printf("Tuesday\n");   break;
        case 3:  printf("Wednesday\n"); break;
        case 4:  printf("Thursday\n");  break;
        case 5:  printf("Friday\n");    break;
        default: printf("Weekend\n");
    }
    return 0;
}
Output
Wednesday
Practice: Conditionals

Write a program that reads a number and prints whether it is positive, negative, or zero.

  1. Use scanf to read an integer
  2. Use if/else if/else to check the number
  3. Print the result using printf
C
#include <stdio.h>

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);

    if (num > 0) {
        printf("Positive\n");
    } else if (num < 0) {
        printf("Negative\n");
    } else {
        printf("Zero\n");
    }
    return 0;
}
07

Loops (for, while, do-while)

Loops let you repeat a block of code. C has three loop types: for, while, and do-while.

for Loop

Use for when you know how many times to iterate.

C
#include <stdio.h>

int main() {
    // Count from 0 to 4
    for (int i = 0; i < 5; i++) {
        printf("Count: %d\n", i);
    }

    // Iterate over an array
    int numbers[] = {10, 20, 30, 40, 50};
    for (int i = 0; i < 5; i++) {
        printf("numbers[%d] = %d\n", i, numbers[i]);
    }
    return 0;
}
Output
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50

while & do-while Loops

while checks the condition first; do-while runs the body at least once.

C
#include <stdio.h>

int main() {
    // while loop
    int count = 0;
    while (count < 5) {
        printf("While: %d\n", count);
        count++;
    }

    // do-while loop
    int num = 0;
    do {
        printf("Do-while: %d\n", num);
        num++;
    } while (num < 5);
    return 0;
}
⚠️

Always ensure your loop condition eventually becomes 0 (false) to avoid infinite loops. Use break to exit early and continue to skip the current iteration.

Practice: Loops

Write two programs:

  1. Use a for loop to print all even numbers from 2 to 20
  2. Use a while loop to calculate the sum of numbers from 1 to 100
C
#include <stdio.h>

int main() {
    // Even numbers 2-20
    for (int i = 2; i <= 20; i += 2) {
        printf("%d\n", i);
    }

    // Sum of 1 to 100
    int sum = 0;
    int n = 1;
    while (n <= 100) {
        sum += n;
        n++;
    }
    printf("Sum: %d\n", sum);
    return 0;
}
08

Functions

Functions (also called procedures) are reusable blocks of code. They help you avoid repetition and organize your program into logical pieces. In C, every function has a return type, a name, and parameters.

C
#include <stdio.h>

// Function declaration (prototype)
int add(int a, int b);
void greet(char name[]);

// Function definitions
int add(int a, int b) {
    return a + b;
}

void greet(char name[]) {
    printf("Hello, %s!\n", name);
}

int main() {
    int sum = add(10, 5);
    printf("Sum: %d\n", sum);

    greet("Alice");
    return 0;
}
Output
Sum: 15
Hello, Alice!

Function Prototypes

In C, you must declare a function before you call it. A prototype tells the compiler about the function's return type and parameters. You can then define the function later in the file (or in another file).

Practice: Functions
  1. Write a function int square(int n) that returns n * n
  2. Write a function int isEven(int n) that returns 1 if n is even, 0 otherwise
  3. Call both functions from main() and print the results
C
#include <stdio.h>

int square(int n);
int isEven(int n);

int square(int n) {
    return n * n;
}

int isEven(int n) {
    return n % 2 == 0;
}

int main() {
    printf("Square of 7: %d\n", square(7));
    printf("Is 10 even? %d\n", isEven(10));
    printf("Is 7 even? %d\n", isEven(7));
    return 0;
}
09

Arrays & Strings

Arrays store multiple values of the same type in contiguous memory. Strings in C are just character arrays terminated by a null character (\0).

Arrays — Fixed-Size Collections

Arrays in C have a fixed length. Array indices start at 0.

C
#include <stdio.h>

int main() {
    // Creating arrays
    int numbers[5] = {10, 20, 30, 40, 50};
    char vowels[] = {'a', 'e', 'i', 'o', 'u'};

    // Access and modify
    numbers[0] = 99;
    printf("First element: %d\n", numbers[0]);
    printf("Third vowel: %c\n", vowels[2]);

    // Array length (sizeof trick)
    int length = sizeof(numbers) / sizeof(numbers[0]);
    printf("Array length: %d\n", length);
    return 0;
}

Strings — Character Arrays

Strings in C are null-terminated character arrays. The <string.h> header provides useful string functions.

C
#include <stdio.h>
#include <string.h>

int main() {
    char text[] = "Hello, C!";

    printf("Length: %lu\n", strlen(text));
    printf("First 5 chars: %.5s\n", text);
    return 0;
}
Practice: Arrays & Strings
  1. Create an array of 5 integers and calculate their sum using a for loop
  2. Write code to count how many vowels are in a given string
C
#include <stdio.h>
#include <string.h>

int main() {
    // Sum of array
    int nums[] = {10, 20, 30, 40, 50};
    int sum = 0;
    int len = sizeof(nums) / sizeof(nums[0]);
    for (int i = 0; i < len; i++) {
        sum += nums[i];
    }
    printf("Sum: %d\n", sum);

    // Count vowels
    char str[] = "hello world";
    int vowels = 0;
    for (int i = 0; i < strlen(str); i++) {
        char c = str[i];
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            vowels++;
        }
    }
    printf("Vowels: %d\n", vowels);
    return 0;
}
10

Pointers Basics

A pointer is a variable that stores the memory address of another variable. Pointers are one of C's most powerful features — they give you direct access to memory and enable dynamic memory allocation.

Pointer Syntax

  • int *ptr; — declares a pointer to an integer
  • &variable — gets the memory address of a variable
  • *ptr — dereferences a pointer (accesses the value at the address)
C
#include <stdio.h>

int main() {
    int x = 42;
    int *ptr = &x;  // ptr stores the address of x

    printf("Value of x: %d\n", x);
    printf("Address of x: %p\n", &x);
    printf("Value of ptr: %p\n", ptr);
    printf("Value at ptr: %d\n", *ptr);  // dereference

    // Modify x through the pointer
    *ptr = 100;
    printf("New value of x: %d\n", x);
    return 0;
}
Output
Value of x: 42
Address of x: 0x16f0a3c1c
Value of ptr: 0x16f0a3c1c
Value at ptr: 42
New value of x: 100

Pointers and Arrays

Array names are essentially pointers to the first element. arr[i] is equivalent to *(arr + i).

C
#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int *p = arr;  // p points to arr[0]

    printf("First element: %d\n", *p);
    printf("Second element: %d\n", *(p + 1));
    printf("Third element: %d\n", *(p + 2));

    // Loop using pointer arithmetic
    for (int i = 0; i < 5; i++) {
        printf("arr[%d] = %d\n", i, *(p + i));
    }
    return 0;
}
⚠️

Always make sure a pointer points to a valid memory address before dereferencing it. Dangling pointers (pointers to freed or invalid memory) and NULL pointer dereferencing are common sources of bugs and crashes in C.

Practice: Pointers
  1. Declare an int variable and a pointer to it
  2. Use the pointer to change the variable's value
  3. Print the variable's value before and after the change
C
#include <stdio.h>

int main() {
    int num = 50;
    int *ptr = &num;

    printf("Before: %d\n", num);

    *ptr = 500;
    printf("After: %d\n", num);
    printf("Via pointer: %d\n", *ptr);
    return 0;
}
11

Structures (struct)

A struct (short for structure) is a user-defined data type that groups related variables of different types together under one name. Structures are C's way of creating custom data types before C++ introduced classes.

C
#include <stdio.h>
#include <string.h>

// Define a struct
struct Student {
    char name[50];
    int age;
    float gpa;
};

int main() {
    // Create a struct variable
    struct Student student1;

    // Assign values
    strcpy(student1.name, "Alice");
    student1.age = 20;
    student1.gpa = 3.85f;

    // Access members using dot operator
    printf("Name: %s\n", student1.name);
    printf("Age: %d\n", student1.age);
    printf("GPA: %.2f\n", student1.gpa);
    return 0;
}
Output
Name: Alice
Age: 20
GPA: 3.85

typedef — Creating Type Aliases

The typedef keyword lets you create an alias for a struct, so you don't have to type struct every time.

C
#include <stdio.h>
#include <string.h>

typedef struct {
    char title[100];
    char author[50];
    int year;
} Book;

int main() {
    Book book1;
    strcpy(book1.title, "1984");
    strcpy(book1.author, "George Orwell");
    book1.year = 1949;

    printf("\"%s\" by %s (%d)\n", book1.title, book1.author, book1.year);
    return 0;
}
💡

Use the dot operator (.) to access struct members. For pointers to structs, use the arrow operator (): ptr->name is equivalent to (*ptr).name. Structs can also contain pointers as members — this is the foundation for linked lists and other dynamic data structures.

Practice: Structures

Define a Rectangle struct with width and height (both int). Write a function that takes a Rectangle and returns its area. Create a rectangle and print its area.

C
#include <stdio.h>

typedef struct {
    int width;
    int height;
} Rectangle;

int getArea(Rectangle r) {
    return r.width * r.height;
}

int main() {
    Rectangle rect = {10, 5};
    printf("Area: %d\n", getArea(rect));
    return 0;
}
12

C Learning Playground

Ready to practice what you've learned? Use our interactive C editor to write, compile, and run your code directly in the browser.

Interactive C Editor

Test pointers, structs, and loops with real-time output.

Launch Editor