Concepts of C Programming

 

C Programming for Beginners: A Complete Guide to the Fundamentals

Introduction

C is one of the most influential and widely used programming languages in computer science. Developed by Dennis Ritchie at Bell Laboratories in the early 1970s, C has become the foundation for many modern programming languages, including C++, Java, and others.

C is a general-purpose, procedural programming language that provides excellent performance, efficient memory management, and direct access to low-level system resources.

Whether you want to become a software developer, work with embedded systems, develop operating systems, or understand how computers work internally, learning C programming is an excellent starting point.

This blog covers the basic concepts of C programming, starting from the fundamentals and progressing toward more advanced topics.

1. What is C Programming?

C is a structured, procedural programming language used to develop system software and application software.

Key characteristics of C:

  • Simple and efficient programming structure.

  • Fast execution.

  • Portable across different platforms.

  • Supports pointers and direct memory access.

  • Provides dynamic memory allocation.

  • Rich collection of built-in operators and library functions.

  • Supports modular programming through functions.

Applications of C programming:

  1. Operating systems such as Linux.

  2. Embedded systems and microcontrollers.

  3. Device drivers.

  4. Industrial automation systems.

  5. Compiler development.

  6. Database systems.

  7. Automotive control systems.

  8. Networking applications.

2. Structure of a C Program

Every C program follows a basic structure.

Let's understand it using a simple example.

#include <stdio.h>

int main()
{
    printf("Hello, World!");

    return 0;
}

Explanation of each statement:

Statement

Purpose

#include <stdio.h>

Includes standard input/output library

int main()

Main function where program execution starts

{ }

Defines the function body

printf()

Displays output on the screen

return 0;

Indicates successful program execution

The main() function is the entry point of a standard hosted C program.

3. Variables in C

A variable is a named memory location used to store data.

For example:

int age = 25;
float temperature = 36.5;
char grade = 'A';

Here:

  • age stores an integer.

  • temperature stores a decimal value.

  • grade stores a character.

Rules for naming variables:

  1. A variable name must begin with a letter or underscore.

  2. It cannot begin with a number.

  3. Spaces are not allowed.

  4. C keywords cannot be used as variable names.

  5. C is case-sensitive.

Example:

int totalMarks;
int TotalMarks;

These are two different variables.

4. Data Types in C

Data types define the type of information a variable can store.

The basic data types are:

Data type

Purpose

Example

int

Integer numbers

100

char

Single character

'A'

float

Decimal numbers

12.5f

double

Higher precision decimal

123.456

void

No value

void function

Other type modifiers include:

  • short

  • long

  • signed

  • unsigned

Example:

int count = 100;
unsigned int quantity = 500;
long int population = 1000000;
float voltage = 230.5f;
double pressure = 12.345678;
char symbol = 'X';

Important: The exact memory size of data types depends on the compiler and platform.

You can check the size using sizeof():

#include <stdio.h>

int main()
{
    printf("Size of int: %zu bytes\n", sizeof(int));
    printf("Size of float: %zu bytes\n", sizeof(float));
    printf("Size of char: %zu bytes\n", sizeof(char));

    return 0;
}

5. Constants in C

A constant is a value that should not change during program execution.

There are two common ways to define constants.

Using const:

const float PI = 3.14159;

Using #define:

#define MAX_LIMIT 100

Example:

#include <stdio.h>

#define PI 3.14159

int main()
{
    float radius = 5;
    float area;

    area = PI * radius * radius;

    printf("Area = %.2f", area);

    return 0;
}

6. Input and Output Functions

C provides standard functions to receive input and display output.

The commonly used functions are:

Function

Purpose

printf()

Displays output

scanf()

Reads formatted input

getchar()

Reads a character

putchar()

Displays a character

fgets()

Reads a string safely

puts()

Displays a string

Example using printf() and scanf():

#include <stdio.h>

int main()
{
    int a, b, sum;

    printf("Enter two numbers: ");

    scanf("%d %d", &a, &b);

    sum = a + b;

    printf("Sum = %d", sum);

    return 0;
}

Common format specifiers:

Format specifier

Data type

%d

int

%f

float

%lf

double in scanf

%c

char

%s

String

%u

unsigned int

%ld

long int

%x

Hexadecimal

Note: In printf(), %f is used for both float and double arguments because of default argument promotions.

7. Operators in C

Operators are symbols used to perform operations on variables and values.

C provides several categories of operators.

7.1 Arithmetic Operators

Used for mathematical calculations.

Operator

Meaning

Example

+

Addition

a + b

-

Subtraction

a - b

*

Multiplication

a * b

/

Division

a / b

%

Modulus

a % b

Example:

int a = 10, b = 3;

printf("%d", a + b);  // 13
printf("%d", a % b);  // 1

7.2 Relational Operators

Used to compare two values.

Operator

Meaning

==

Equal to

!=

Not equal to

>

Greater than

<

Less than

>=

Greater than or equal

<=

Less than or equal

These operators return either 1 (true) or 0 (false).

7.3 Logical Operators

Used to combine conditions.

Operator

Meaning

&&

Logical AND

||

Logical OR

!

Logical NOT

Example:

if (age >= 18 && age <= 60)
{
    printf("Eligible");
}

7.4 Assignment Operators

Operator

Example

Equivalent

=

a = 10

Assign 10

+=

a += 5

a = a + 5

-=

a -= 5

a = a - 5

*=

a *= 2

a = a * 2

/=

a /= 2

a = a / 2

7.5 Increment and Decrement Operators

int a = 10;

a++;  // a becomes 11
a--;  // a becomes 10
  • ++a: Pre-increment.

  • a++: Post-increment.

  • --a: Pre-decrement.

  • a--: Post-decrement.

The difference is when the value is updated relative to its use in an expression.

7.6 Bitwise Operators

Bitwise operators work directly on individual bits.

Operator

Meaning

&

Bitwise AND

|

Bitwise OR

^

Bitwise XOR

~

Bitwise NOT

<<

Left shift

>>

Right shift

These are particularly useful in embedded programming and hardware control.

Example:

int a = 5;  // Binary: 0101
int b = 3;  // Binary: 0011

printf("%d", a & b);  // Result: 1

8. Decision-Making Statements

Decision-making statements allow a program to execute different blocks of code depending on conditions.

8.1 if Statement

int number = 10;

if (number > 0)
{
    printf("Positive number");
}

8.2 if-else Statement

int number = 7;

if (number % 2 == 0)
{
    printf("Even number");
}
else
{
    printf("Odd number");
}

8.3 else-if Ladder

Used when multiple conditions need to be checked.

int marks = 75;

if (marks >= 90)
{
    printf("Grade A");
}
else if (marks >= 75)
{
    printf("Grade B");
}
else if (marks >= 50)
{
    printf("Grade C");
}
else
{
    printf("Fail");
}

8.4 Nested if

An if statement inside another if statement.

int age = 25;
int hasLicense = 1;

if (age >= 18)
{
    if (hasLicense == 1)
    {
        printf("Can drive");
    }
}

8.5 switch Statement

Used when a variable needs to be compared against multiple constant values.

int choice = 2;

switch (choice)
{
    case 1:
        printf("Start");
        break;

    case 2:
        printf("Stop");
        break;

    case 3:
        printf("Reset");
        break;

    default:
        printf("Invalid choice");
}

The break statement prevents execution from falling through to the next case.

9. Loops in C

Loops are used to execute a block of code repeatedly.

C supports three main types of loops.

9.1 for Loop

Used when the number of iterations is known.

#include <stdio.h>

int main()
{
    int i;

    for (i = 1; i <= 5; i++)
    {
        printf("%d\n", i);
    }

    return 0;
}

Output:

1
2
3
4
5

9.2 while Loop

Used when the number of iterations is not necessarily known in advance.

int i = 1;

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

9.3 do-while Loop

The do-while loop executes at least once because the condition is checked after execution.

int i = 1;

do
{
    printf("%d\n", i);
    i++;

} while (i <= 5);

Difference between loops:

Loop

Condition checking

Minimum execution

for

Before execution

0 times

while

Before execution

0 times

do-while

After execution

1 time

10. Jump Statements

Jump statements alter the normal flow of program execution.

break

Terminates the nearest enclosing loop or switch.

for (int i = 1; i <= 10; i++)
{
    if (i == 5)
        break;

    printf("%d ", i);
}

Output: 1 2 3 4

continue

Skips the current loop iteration.

for (int i = 1; i <= 5; i++)
{
    if (i == 3)
        continue;

    printf("%d ", i);
}

Output: 1 2 4 5

goto

Transfers control to a labeled statement.

#include <stdio.h>

int main()
{
    goto message;

    printf("This will be skipped");

message:
    printf("Hello C Programming");

    return 0;
}

Use goto sparingly because excessive use can make programs difficult to maintain.

return

Terminates a function and optionally returns a value to its caller.

11. Arrays in C

An array is a collection of elements of the same data type stored in contiguous memory locations.

Example:

int marks[5] = {80, 85, 90, 75, 95};

Array indexing starts from zero.

Accessing array elements:

printf("%d", marks[0]);  // 80
printf("%d", marks[2]);  // 90

Example: Display all array elements

#include <stdio.h>

int main()
{
    int arr[5] = {10, 20, 30, 40, 50};
    int i;

    for (i = 0; i < 5; i++)
    {
        printf("%d\n", arr[i]);
    }

    return 0;
}

Types of Arrays

1. One-dimensional array

int a[5] = {1, 2, 3, 4, 5};

2. Two-dimensional array

Used to store data in rows and columns.

int matrix[2][3] =
{
    {1, 2, 3},
    {4, 5, 6}
};

3. Multidimensional array

int data[2][3][4];

Arrays are useful for storing sensor readings, test measurements, student marks, and other collections of values.

12. Strings in C

A string is a sequence of characters terminated by a null character '\0'.

C does not have a separate built-in string data type. Strings are represented using character arrays.

Example:

char name[20] = "HEICO";

Common string functions:

These functions are available in the string.h header.

Function

Purpose

strlen()

Finds string length

strcpy()

Copies a string

strcat()

Joins two strings

strcmp()

Compares two strings

strchr()

Finds a character

strstr()

Finds a substring

Example:

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

int main()
{
    char str1[30] = "Hello";
    char str2[] = " World";

    strcat(str1, str2);

    printf("%s\n", str1);
    printf("Length = %zu", strlen(str1));

    return 0;
}

Always ensure the destination array has sufficient space before copying or concatenating strings.

13. Functions in C

A function is a reusable block of code designed to perform a specific task.

Functions help make programs modular, readable, and easier to maintain.

Types of functions:

  1. Library functions – predefined functions such as printf(), scanf(), sqrt().

  2. User-defined functions – functions created by the programmer.

Basic structure of a function

return_type function_name(parameters)
{
    // Statements
}

Example:

#include <stdio.h>

int add(int a, int b);

int main()
{
    int result;

    result = add(10, 20);

    printf("Sum = %d", result);

    return 0;
}

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

Four common types of user-defined functions

Type

Arguments

Return value

Type 1

No

No

Type 2

Yes

No

Type 3

No

Yes

Type 4

Yes

Yes

Recursion

Recursion occurs when a function calls itself.

Example: Factorial calculation.

#include <stdio.h>

int factorial(int n)
{
    if (n <= 1)
        return 1;

    return n * factorial(n - 1);
}

int main()
{
    printf("%d", factorial(5));

    return 0;
}

Output: 120

14. Pointers in C

Pointers are one of the most important concepts in C programming.

A pointer is a variable that stores the memory address of another variable.

Example:

#include <stdio.h>

int main()
{
    int a = 10;

    int *ptr = &a;

    printf("Value of a = %d\n", a);

    printf("Address of a = %p\n", (void*)&a);

    printf("Value using pointer = %d\n", *ptr);

    return 0;
}

Important pointer operators:

  • & – Address-of operator.

  • * – Dereference operator when used with a pointer.

For example:

int a = 100;
int *ptr = &a;

*ptr = 200;

Now the value of a becomes 200.

Types of Pointers

  • Null pointer.

  • Void pointer.

  • Wild pointer (uninitialized pointer).

  • Dangling pointer.

  • Function pointer.

  • Pointer to pointer.

Pointers are extensively used in embedded systems, hardware interfacing, memory management, and data structures.

15. Structures in C

A structure is a user-defined data type that groups variables of different data types under one name.

Example:

#include <stdio.h>

struct Sensor
{
    int id;
    float temperature;
    float pressure;
};

int main()
{
    struct Sensor s1;

    s1.id = 1;
    s1.temperature = 35.5;
    s1.pressure = 2.5;

    printf("Sensor ID = %d\n", s1.id);
    printf("Temperature = %.2f\n", s1.temperature);
    printf("Pressure = %.2f\n", s1.pressure);

    return 0;
}

Structures are useful for grouping related information.

For example, an industrial testing system may use a structure to store:

  • Test ID.

  • Load.

  • Displacement.

  • Pressure.

  • Temperature.

  • Test duration.

16. Union in C

A union is similar to a structure, but all members share the same memory location.

Example:

#include <stdio.h>

union Data
{
    int i;
    float f;
    char c;
};

int main()
{
    union Data d;

    d.i = 10;

    printf("%d", d.i);

    return 0;
}

Difference between structure and union:

Structure

Union

Each member has its own storage

Members share storage

All members can hold independent values

Only one member's stored value is meaningfully active at a time

Size accommodates all members plus padding

Size accommodates the largest member plus padding

17. Enumerations (enum)

An enumeration is a user-defined data type that assigns names to integer constants.

Example:

#include <stdio.h>

enum Status
{
    STOP = 0,
    RUN = 1,
    PAUSE = 2
};

int main()
{
    enum Status machineStatus = RUN;

    printf("%d", machineStatus);

    return 0;
}

Enumerations improve readability when working with predefined states.

For example: machine status, motor direction, test conditions, and operating modes.

18. Typedef in C

typedef is used to create an alternative name for an existing data type.

Example:

#include <stdio.h>

typedef unsigned int UINT;

int main()
{
    UINT count = 100;

    printf("%u", count);

    return 0;
}

It is also commonly used with structures.

typedef struct
{
    int id;
    float load;
} TestData;

int main()
{
    TestData t1;

    t1.id = 101;
    t1.load = 50.5;

    return 0;
}

19. Dynamic Memory Allocation

Dynamic memory allocation allows a program to allocate memory during runtime.

The functions are available in stdlib.h.

Function

Purpose

malloc()

Allocates memory without initialization

calloc()

Allocates memory and initializes it to zero

realloc()

Changes allocated memory size

free()

Releases allocated memory

Example:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *ptr;
    int i;

    ptr = (int*)malloc(5 * sizeof(int));

    if (ptr == NULL)
    {
        printf("Memory allocation failed");
        return 1;
    }

    for (i = 0; i < 5; i++)
    {
        ptr[i] = (i + 1) * 10;
    }

    for (i = 0; i < 5; i++)
    {
        printf("%d\n", ptr[i]);
    }

    free(ptr);

    return 0;
}

Important: Always check whether memory allocation succeeded and release allocated memory when it is no longer needed.

20. File Handling in C

File handling allows programs to create, read, write, and modify files.

C provides file handling functions through stdio.h.

Common file functions:

Function

Purpose

fopen()

Opens a file

fclose()

Closes a file

fprintf()

Writes formatted data

fscanf()

Reads formatted data

fgets()

Reads a line

fputs()

Writes a string

fread()

Reads binary data

fwrite()

Writes binary data

fseek()

Moves file position

ftell()

Returns current position

rewind()

Moves to beginning

File opening modes

Mode

Description

r

Read

w

Write (creates or truncates)

a

Append

r+

Read and write

w+

Read and write (truncates)

a+

Read and append

rb

Read binary

wb

Write binary

Example:

#include <stdio.h>

int main()
{
    FILE *fp;

    fp = fopen("test.txt", "w");

    if (fp == NULL)
    {
        printf("File cannot be opened");
        return 1;
    }

    fprintf(fp, "Hello C Programming");

    fclose(fp);

    return 0;
}

File handling is particularly useful in data logging applications, where sensor readings, machine parameters, and test results need to be stored.

21. Preprocessor Directives

Preprocessor directives are instructions processed before the actual compilation of a C program.

They begin with #.

Common directives:

Directive

Purpose

#include

Includes header files

#define

Defines macros

#undef

Removes a macro definition

#ifdef

Checks whether a macro is defined

#ifndef

Checks whether a macro is not defined

#if

Conditional compilation

#else

Alternative compilation branch

#endif

Ends conditional compilation

Example:

#include <stdio.h>

#define MAX_VALUE 100

int main()
{
    printf("Maximum = %d", MAX_VALUE);

    return 0;
}

Header Files

Header files contain declarations of functions, macros, data types, and other interfaces.

Some common header files are:

  • stdio.h – Input and output.

  • stdlib.h – Memory allocation and utility functions.

  • string.h – String handling.

  • math.h – Mathematical functions.

  • time.h – Date and time functions.

  • ctype.h – Character handling.

22. Storage Classes in C

Storage classes define the scope, lifetime, and linkage of variables and functions.

The commonly taught storage-class specifiers are:

Storage class

Description

auto

Default storage class for ordinary local variables

register

Suggests register storage to the compiler

static

Gives static storage duration

extern

Declares an object or function defined elsewhere

Example of static:

#include <stdio.h>

void counter()
{
    static int count = 0;

    count++;

    printf("%d\n", count);
}

int main()
{
    counter();
    counter();
    counter();

    return 0;
}

Output:

1
2
3

The static local variable retains its value between function calls.

23. Scope and Lifetime of Variables

Scope defines where a variable can be accessed.

Lifetime defines how long a variable exists during program execution.

Common scopes:

  • Local scope.

  • File scope.

  • Block scope.

  • Function scope (primarily labels).

Example:

#include <stdio.h>

int globalValue = 100;

int main()
{
    int localValue = 50;

    printf("%d\n", globalValue);
    printf("%d\n", localValue);

    return 0;
}

Here, globalValue has file scope, while localValue has block scope.

24. Type Casting in C

Type casting converts a value from one data type to another.

There are two main forms:

  1. Implicit conversion – performed automatically by the compiler.

  2. Explicit conversion – performed using a cast operator.

Example:

#include <stdio.h>

int main()
{
    int a = 10;
    int b = 3;

    float result;

    result = (float)a / b;

    printf("%.2f", result);

    return 0;
}

Output:

3.33

Without the cast, integer division would produce 3.

25. Command-Line Arguments

Command-line arguments allow users to pass values to a C program when starting it.

The main() function can receive arguments using:

int main(int argc, char *argv[])
  • argc represents the number of arguments.

  • argv is an array of strings containing the arguments.

Example:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    for (i = 0; i < argc; i++)
    {
        printf("%s\n", argv[i]);
    }

    return 0;
}

This is useful for automation tools, command-line utilities, and batch processing applications.

26. Compilation Process in C

A C program must be translated into machine code before execution.

The compilation process consists of four major stages.

  1. Preprocessing: Processes header files, macros, and conditional compilation.

  2. Compilation: Converts preprocessed C code into assembly language.

  3. Assembly: Converts assembly code into object code.

  4. Linking: Combines object code and required libraries to create an executable.



Example using GCC:

gcc program.c -o program

Run the program:

./program

On Windows, the executable is generally:

program.exe

27. Common Errors in C Programming

Understanding errors is essential for becoming a good programmer.

Error type

Explanation

Example

Syntax error

Incorrect language syntax

Missing semicolon

Runtime error

Error during execution

Invalid memory access

Logical error

Program runs but gives wrong result

Incorrect formula

Linker error

Missing function or symbol definition

Undefined reference

Common mistakes to avoid:

  • Forgetting semicolons.

  • Using uninitialized variables.

  • Accessing arrays outside their limits.

  • Using incorrect format specifiers.

  • Forgetting to free dynamically allocated memory.

  • Dereferencing null or invalid pointers.

  • Using = instead of == in conditions.

  • Ignoring compiler warnings.

28. Practical Applications of C Programming in Industrial Automation

C programming is especially important in embedded systems and industrial automation.

Some practical examples include:

Application

C programming concepts

Sensor data acquisition

Variables, arrays, pointers

Load cell measurement

ADC conversion, functions

Motor control

Operators, conditions, loops

PID control

Functions, structures, mathematical operations

Serial communication

Strings, pointers, bitwise operators

Data logging

File handling

Machine status monitoring

Enum, switch, structures

Memory-efficient embedded applications

Pointers, dynamic/static memory

For example, a simple sensor conversion program:

#include <stdio.h>

int main()
{
    int adcValue = 2048;
    float voltage;

    voltage = (adcValue * 5.0f) / 4095.0f;

    printf("ADC Value = %d\n", adcValue);
    printf("Voltage = %.3f V\n", voltage);

    return 0;
}

This example demonstrates how an ADC reading can be converted into an equivalent voltage for a 12-bit ADC with a 5 V reference.

29. Important C Programming Interview Questions

Here are some fundamental questions to test your understanding.

  1. What is the difference between C and C++?

  2. What is the difference between declaration and definition?

  3. What is the difference between while and do-while?

  4. What is a pointer?

  5. What is a NULL pointer?

  6. What is the difference between an array and a pointer?

  7. What is recursion?

  8. What is the difference between a structure and a union?

  9. What is the difference between malloc() and calloc()?

  10. What is the purpose of the static keyword?

  11. What is the difference between break and continue?

  12. What is a segmentation fault?

  13. What is the difference between = and ==?

  14. What is dynamic memory allocation?

  15. What is a function pointer?

30. Beginner-Level C Programming Practice Problems

Practice is the best way to understand programming concepts.

Try writing programs for the following problems:

No.

Programming exercise

Concepts

1

Print Hello World

Basic syntax

2

Add two numbers

Variables, operators

3

Find even or odd

if-else

4

Find the largest of three numbers

Conditions

5

Print multiplication table

Loops

6

Find factorial of a number

Loops, recursion

7

Generate Fibonacci series

Loops

8

Reverse a number

Arithmetic

9

Check palindrome number

Conditions, loops

10

Find maximum element in an array

Arrays

11

Sort an array

Arrays, loops

12

Reverse a string

Strings

13

Swap two numbers using pointers

Pointers

14

Store student details using structures

Structures

15

Read and write data into a file

File handling

31. Recommended Learning Roadmap

If you are starting from zero, follow this sequence:

C Programming Learning Path

  1. Level 1 – Fundamentals

    Variables, data types, constants, input/output, operators.

    Start here
  2. Level 2 – Program Control

    if-else, switch, for, while, do-while, break, continue.

  3. Level 3 – Data Handling

    Arrays, strings, functions, recursion.

  4. Level 4 – Memory Management

    Pointers, structures, unions, enums, dynamic memory.

  5. Level 5 – Advanced Fundamentals

    File handling, preprocessor directives, storage classes, command-line arguments.

  6. Level 6 – Practical Projects

    Sensor reading, serial communication, data logging, and embedded control.

Comments

Popular posts from this blog

Setting up a USB thermal printer with a Raspberry Pi 3B+

Create a autorun for a PyQt5 raspberry pi Application

Basic Input/Output C Program