C Programming Tutorial

C is a foundational programming language used in many applications, from operating systems to embedded systems. This tutorial covers the basics of C programming with examples for each topic.

2. C Get Started

To get started, write your C code in a file with a .c extension. Then, compile it with a compiler like GCC. Example:

// hello.c #include <stdio.h> int main() { printf("Hello, World!"); return 0; }

Compile and run with:

bash
gcc hello.c -o hello ./hello

3. C Syntax

C uses a structure where code blocks are enclosed in {} and statements end with ;. Example:

#include <stdio.h> int main() { int number = 10; printf("The number is %d", number); return 0; }

4. C Output

Use printf() from <stdio.h> to display output. Example:

printf("Hello, %s!", "Alice");

5. C Comments

Add comments to make code more understandable. Example:

// This is a single-line comment /* This is a multi-line comment */

6. C Variables

Variables store data values. Example:

int age = 25; float height = 5.9; char grade = 'A';

7. C Data Types

Define data types for storing specific values. Example:

int age = 20; float salary = 55000.50; char letter = 'A';

8. C Constants

Use constants to store unchangeable values. Example:

const int PI = 3.1415;

9. C Operators

Operators perform operations on variables. Example:

int a = 5, b = 3; int sum = a + b; // sum is 8

10. C Booleans

C uses integers for booleans (0 for false, non-zero for true). Example:

#include <stdbool.h> bool isStudent = true; if (isStudent) { printf("The person is a student."); }

11. If…Else

The if...else statement controls conditional execution. Example:

int score = 85; if (score >= 90) { printf("Grade: A"); } else if (score >= 80) { printf("Grade: B"); } else { printf("Grade: C"); }

12. Switch

The switch statement selects code to run based on matching cases. Example:

int day = 2; switch (day) { case 1: printf("Monday"); break; case 2: printf("Tuesday"); break; default: printf("Other day"); }

13. While Loop

A while loop repeats as long as the condition is true. Example:

int i = 1; while (i <= 5) { printf("%d ", i); i++; }

14. For Loop

A for loop is used for repeated actions. Example:

for (int i = 0; i < 5; i++) { printf("%d ", i); }

15. Break and Continue

Use break to exit a loop, and continue to skip to the next iteration. Example:

for (int i = 0; i < 5; i++) { if (i == 3) break; printf("%d ", i); }

16. Arrays

Arrays store multiple values of the same type. Example:

int numbers[] = {1, 2, 3, 4}; printf("%d", numbers[0]); // Outputs 1

17. Strings

Strings are arrays of characters. Example:

char greeting[] = "Hello"; printf("%s", greeting);

18. User Input

Use scanf() for user input. Example:

int age; printf("Enter your age: "); scanf("%d", &age); printf("You are %d years old.", age);

19. Memory Address

Use the & operator to get a variable’s address. Example:

int number = 10; printf("%p", &number); // Prints the memory address of number

20. Pointers

Pointers store memory addresses. Example:

int number = 10; int* ptr = &number; printf("%d", *ptr); // Outputs 10

21. Functions

Functions organize reusable code blocks. Example:

int add(int a, int b) { return a + b; } printf("Sum: %d", add(2, 3));

22. Function Parameters

Functions can have parameters. Example:

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

23. Scope

Variables have local or global scope. Example:

int globalVar = 10; void test() { int localVar = 20; // Local to this function }

24. Function Declaration

Declare a function before calling it if it appears later in the file. Example:

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

25. Recursion

Recursion occurs when a function calls itself. Example:

int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); }

26. Math Functions

Use <math.h> for math functions. Example:

#include <math.h> double result = sqrt(25.0); // result is 5.0

27. Files

File handling allows reading and writing data. Example:

FILE *file = fopen("example.txt", "w"); fprintf(file, "Hello, World!"); fclose(file);

28. Create Files

Open a file for writing with w. Example:

FILE *file = fopen("newfile.txt", "w"); if (file) { fclose(file); }

29. Write to Files

Use fprintf() to write data to a file. Example:

FILE *file = fopen("data.txt", "w"); fprintf(file, "Data here"); fclose(file);

30. Read Files

Read data from a file with fscanf(). Example:

FILE *file = fopen("data.txt", "r"); int data; fscanf(file, "%d", &data); fclose(file);

31. Structures

Structures group variables of different types. Example:

struct Person { char name[50]; int age; }; struct Person person1 = {"Alice", 30}; printf("%s is %d years old", person1.name, person1.age);

32. Enums

Enums define named integer constants. Example:

enum Day {MON, TUE, WED}; enum Day today = MON;

33. Memory Management

Use malloc() and free() for dynamic memory. Example:

int *ptr = malloc(10 * sizeof(int)); free(ptr);

34. Reference

In C programming, a reference section typically includes keywords, standard libraries, and header files that provide essential functions and tools. Here’s a closer look at each component in the reference section:

Keywords

C keywords are reserved words that have a specific purpose and cannot be used as variable names. They define the core language structure and control flow. Examples include:

  • int: Declares an integer variable.
  • return: Exits a function and optionally returns a value.
  • if, else, while, for: Used for flow control.
  • const, volatile: Modify variable behavior, like declaring constants.
  • struct, enum, typedef: Define data structures and types.

A complete list of C keywords can be found in C documentation or through compiler resources.

Header Files

Header files in C define functions, macros, and constants. Including header files enables you to use prewritten code without rewriting it, improving code efficiency and readability. Header files in C are included with #include <header.h>.

Here’s a brief overview of some commonly used header files:

  • <stdio.h>

    • The standard input-output library provides functions for data input and output.
    • Common functions: printf() (to display output) and scanf() (to read user input).
    • Example:
      #include <stdio.h> int main() { printf("Hello, World!"); return 0; }
  • <stdlib.h>

    • The standard library provides utility functions for memory allocation, control functions, conversions, and more.
    • Common functions: malloc() and free() for dynamic memory management.
    • Example:
      #include <stdlib.h> int *ptr = malloc(sizeof(int) * 10); free(ptr);
  • <string.h>

    • The string library includes functions to manipulate and handle strings.
    • Common functions: strlen() (get string length), strcpy() (copy strings), strcmp() (compare strings).
    • Example:
      #include <string.h> char name[] = "Alice"; printf("Length of name: %zu", strlen(name));
  • <math.h>

    • This library provides functions for mathematical calculations.
    • Common functions: sqrt() (square root), pow() (power), abs() (absolute value).
    • Example:
      #include <math.h> double result = sqrt(25.0); // result is 5.0
  • <ctype.h>

    • The character type library includes functions to test and manipulate individual characters.
    • Common functions: isalpha() (check if alphabetic), isdigit() (check if numeric), toupper() (convert to uppercase).
    • Example:
      #include <ctype.h> char letter = 'a'; if (isalpha(letter)) { printf("%c is a letter", letter); }

Each header file provides a suite of functions that enhances the functionality of your C program, helping with common tasks like mathematical calculations, string manipulation, memory allocation, and character handling. Understanding how to use these libraries and keywords allows you to write more efficient and organized C code.

References

  1. The C Programming Language” by Brian W. Kernighan and Dennis M. Ritchie
    • C Programming Language Documentation
      • GNU C Library (glibc)
        • TutorialsPoint – C Programming Tutorial
          • GeeksforGeeks – C Programming Language
            • cppreference.com – C Standard Library
              • CProgramming.com