Experience Top-Rated Tutoring – 4.3/5 ★★★★★ by Parents & Students
Course Details
JOIN OUR

C Language

Book a free trial session and start your personalized learning journey with our expert tutors.

Send Us Your Enquiry To Get Started

Fill out the form below and one of our experts will contact you shortly

TutorX Smart Learning Dashboard

Everything You Need, All in One Place

TutorX Learning Platform

At The TutorX, we believe learning should be clear, focused, and at your fingertips. That’s why we’ve built a smart and user-friendly dashboard to empower every student on their academic journey. From live sessions and homework to performance tracking and resources—everything is seamlessly integrated to help you stay ahead with confidence.

  • View upcoming sessions and join with a single click.
  • Track your progress through weekly reports.
  • Access study materials tailored to your goals.
  • Get reminders so you never miss a session.
  • Connect with tutors and ask questions anytime.
Tutela Dashboard

C Tutorial | Learn C Programming Language

What is the C programming language?

The C programming language is a general-purpose, procedural, and structured programming language developed by Dennis Ritchie at AT&T Bell Labs in the early 1970s. It was initially used to develop the UNIX Operating System and is now the most widely used programming language. C is mainly developed to create system applications that directly interact with hardware devices such as drivers and kernels. It is considered the base for other programming languages, which is why it is known as the mother language.

Structure of a C Program

Documentation Section // Program description, author, date — written as comments Preprocessor / Link Section #include #include Definition Section #define PI 3.14 #define MAX 100 Global Declaration Section int globalVar; float globalFloat; Main Function int main() { ... return 0; } Subprogram / User-Defined Functions void myFunction() { ... }

A C program consists of the above six sections. The Documentation Section contains comments. The Preprocessor Section includes header files. The Definition Section defines macros. Global variables are declared in the Global Section. The main() function is the entry point, and user-defined functions (subprograms) are defined below it.

Features of C Language

1. Simple: C is a simple language with structured approach, rich library functions, and clean syntax easy to learn.

2. Machine Independent / Portable: C programs can run on different machines with little or no modification.

3. Mid-level Programming Language: Supports both high-level and low-level features like direct memory access using pointers.

4. Structured: Programs can be divided into smaller modules or functions — easier to debug and maintain.

5. Rich Library: Provides built-in functions for I/O, string handling, math, and memory management.

6. Memory Management: Direct control over memory via pointers and malloc(), calloc(), realloc(), free().

7. Fast and Efficient: Closer to hardware, so programs execute quickly and consume less memory.

8. Pointer Support: Enables direct access to memory addresses — ideal for system-level programming.

9. Extensible: Programmers can create and add their own functions to the C library.

10. Recursion: A function can call itself — useful for factorial, Fibonacci, tree traversal, and binary search.

C Control Statements

What are Control Statements in C?

Control statements in C control the flow of execution of a program. They allow the programmer to make decisions, repeat tasks, and jump to different parts of the program. C provides three main types: Decision-Making Statements, Looping Statements, and Jump Statements.

Control Statements in C Flow of program execution Decision Making if, if-else, switch Looping for, while, do-while Jump Statements break, continue, goto if if-else switch for while do-while break continue goto C provides 3 categories of control statements to manage program flow

1. if Statement: Executes a block only if the condition is true.
if (condition) { // code }

2. if-else Statement: Provides alternate code when condition is false.

3. switch Statement: Selects one block from many alternatives based on a variable's value.

4. for Loop: Used when number of iterations is known. for(init; condition; increment)

5. while Loop: Repeats as long as condition is true. Used when iterations are unknown in advance.

6. do-while Loop: Executes at least once before checking condition.

7. break: Exits the nearest loop or switch immediately.

8. continue: Skips current iteration and jumps to next.

9. goto: Transfers control to a labeled statement (generally discouraged).

10. return: Exits the current function and optionally returns a value.

C Functions

What are Functions in C?

A function in C is a self-contained block of code that performs a specific task and can be reused. Every C program must have at least one function — main(). Functions provide code reusability, modularity, easy debugging, and readability.

1. Declaration (Prototype) int add(int a, int b); 2. Definition (Function Body) int add(int a, int b){return a+b;} 3. Function Call (Execute) result = add(5, 3); Tells compiler Actual code logic Invokes the function Every C function follows these 3 steps: Declaration → Definition → Call

Library Functions: Predefined functions like printf(), scanf(), strlen(), sqrt(), malloc(). Require including header files.

User-Defined Functions: Written by programmer for specific tasks. Must be declared, defined, and called.

Call by Value: Copy of value passed — changes inside function don't affect original variable.

Call by Reference: Address passed via pointers — changes inside function directly affect original variable.

Recursion: A function calling itself. Must have a base case to stop. Example: Factorial — int factorial(int n) { if(n==0) return 1; return n * factorial(n-1); }

C Array

What is an Array in C?

An array in C is a collection of elements of the same data type stored in contiguous memory locations. Arrays allow storing multiple values under a single variable name accessed using an index. Arrays are zero-indexed — first element at index 0. Declaration: int numbers[5];

int numbers[5] = {10, 20, 30, 40, 50}; Memory Address → 10 index [0] 20 index [1] 30 index [2] 40 index [3] 50 index [4] 0x100 0x104 0x108 0x10C 0x110 Contiguous Memory — Elements stored side by side Access: numbers[0]=10 numbers[2]=30 numbers[4]=50

1. One-Dimensional Array: int marks[5] = {90, 85, 78, 92, 88}; — stores a list in a single row.

2. Two-Dimensional Array (Matrix): int matrix[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; — stores in rows and columns.

3. Multi-Dimensional Array: int arr[2][3][4]; — three or more dimensions for scientific computations.

4. Array of Strings: char names[3][20] = {"Alice", "Bob", "Charlie"}; — 2D char array.

Passing Arrays to Functions: The base address (pointer to first element) is passed. Changes inside the function affect the original array.

C Pointers

What are Pointers in C?

A pointer in C is a variable that stores the memory address of another variable. Pointers enable dynamic memory allocation, efficient array handling, and passing variables by reference. Declared with *. The & operator gets the address; * dereferences to get the value.

Variable: num 10 Value stored Address: 0x200 Pointer: ptr 0x200 Stores address of num Address: 0x300 ptr points to num int num = 10; int *ptr = # // & gets address printf("%d", *ptr); // * gets value = 10 & (Address-of): Returns memory address * (Dereference): Returns value at address int *ptr: Declares pointer to int

NULL Pointer: int *ptr = NULL; — does not point to any valid location. Always initialize pointers.

Void Pointer: void *ptr; — generic pointer, can point to any data type. Must be typecast before dereferencing.

Wild Pointer: Uninitialized pointer — causes undefined behavior. Always initialize before use.

Dangling Pointer: Points to freed/deleted memory — leads to undefined behavior. Set to NULL after free().

Double Pointer: int **pptr; — stores address of another pointer. Used for dynamic 2D arrays.

Pointer Arithmetic: ptr++ moves to next element. ptr-- moves to previous. Useful for traversing arrays.

C Dynamic Memory Allocation

What is Dynamic Memory Allocation in C?

Dynamic memory allocation allows programs to request memory at runtime from the heap using four functions in : malloc(), calloc(), realloc(), and free(). Unlike stack memory (automatic), heap memory is manually managed.

malloc() Allocates memory NOT initialized (garbage values) int *p = malloc(5*sizeof(int)) calloc() Allocates + zeros Initialized to 0 (2 arguments) int *p = calloc(5, sizeof(int)) realloc() Resize memory Increase / decrease block size p = realloc(p, 10*sizeof(int)) free() Release memory Back to system Prevents memory leak free(p); p = NULL; All 4 functions defined in #include

malloc(size): Allocates a block of uninitialized memory. Returns void pointer. Example: int *ptr = (int *) malloc(5 * sizeof(int));

calloc(n, size): Allocates n elements, each of given size, all initialized to zero. Example: int *ptr = (int *) calloc(5, sizeof(int));

realloc(ptr, new_size): Resizes previously allocated block. Extra bytes are uninitialized if size grows.

free(ptr): Releases allocated memory. Always free memory after use to prevent memory leaks. Set pointer to NULL after free.

C Strings

What are Strings in C?

In C, a string is a sequence of characters stored in a character array terminated by a null character '\0'. C has no built-in string type — strings are char arrays. The null terminator marks the end of the string.

char str[] = "Hello"; H str[0] e str[1] l str[2] l str[3] o str[4] \0 str[5] NULL Null Terminator '\0' Marks end of string strlen("Hello") = 5 (null '\0' not counted in length)

strlen(str): Returns length excluding '\0'. strlen("Hello") = 5

strcpy(dest, src): Copies src string into dest.

strcat(dest, src): Appends src to end of dest.

strcmp(str1, str2): Returns 0 if equal, negative if str1 < str2, positive if str1 > str2.

strstr(str, substr): Finds first occurrence of substr in str.

strtok(str, delim): Splits string into tokens by delimiter.

All string functions require #include

C Math Functions

What is the C Math Library?

The C math library provides mathematical functions in . Compile with -lm flag: gcc program.c -lm

sqrt(x): Square root. sqrt(25.0) = 5.0

pow(base, exp): Power. pow(2, 10) = 1024.0

abs(x) / fabs(x): Absolute value for int / float.

ceil(x): Round up. ceil(4.2) = 5.0

floor(x): Round down. floor(4.9) = 4.0

round(x): Round to nearest. round(4.5) = 5.0

log(x) / log10(x): Natural log / base-10 log.

exp(x): e raised to the power x.

sin(x), cos(x), tan(x): Trigonometric functions (x in radians).

fmod(x, y): Floating-point remainder of x/y.

C Structure and Union

What is a Structure in C?

A structure groups variables of different data types under a single name using the struct keyword. A union is similar but all members share the same memory location — only one member holds a value at a time.

struct Student (Separate memory for each member) char name[50] 50 bytes — own memory block int age 4 bytes — own memory block float marks 4 bytes — own memory block Total Size = 50 + 4 + 4 = 58 bytes union Data (All members share SAME memory) SHARED MEMORY BLOCK int i (4 bytes) float f (4 bytes) char str[20] (20 bytes) Total Size = 20 bytes (largest)

Structure: Each member has its own memory. All members can hold values simultaneously. Size = sum of all members. Used for complex records like student/employee data.

Union: All members share same memory. Only one holds a value at a time. Size = size of largest member. Used when memory efficiency is critical.

Accessing members: Use dot operator (.) with variable: s1.name, s1.age. Use arrow operator (->) with pointer: ptr->name, ptr->age.

C File Handling

What is File Handling in C?

File handling allows C programs to store and retrieve data permanently from disk. C provides file functions in . Files can be opened in text mode or binary mode.

fopen(filename, mode): Opens file. Modes — "r" (read), "w" (write/create), "a" (append), "r+" (read+write), "b" for binary (e.g., "rb", "wb").

fclose(fp): Closes file. Always close to free system resources.

fprintf(fp, format, ...): Writes formatted data to file. fscanf(fp, format, ...) reads formatted data.

fgetc(fp) / fputc(ch, fp): Read/write single character.

fgets(buf, n, fp) / fputs(str, fp): Read/write string.

fread(ptr, size, count, fp) / fwrite(ptr, size, count, fp): Binary read/write of blocks of data.

fseek(fp, offset, origin) / ftell(fp) / rewind(fp): Random file access — move pointer to specific position.

feof(fp): Returns true when end of file is reached. while(!feof(fp)) { ... }

C Preprocessor

What is the C Preprocessor?

The preprocessor processes source code before compilation. Directives start with #. Build process: Source Code → Preprocessor → Modified Source → Compiler → Object Code → Linker → Executable.

#include: Includes header files. for system headers; "filename" for user headers.

#define: Defines macros. #define PI 3.14159 or #define MAX(a,b) ((a)>(b)?(a):(b))

#undef: Undefines a macro so it can be redefined.

#ifdef / #ifndef / #endif: Conditional compilation — commonly used as include guards to prevent duplicate inclusion.

#if / #elif / #else / #endif: More general conditional — checks expressions, not just macro existence.

#pragma: Compiler-specific instructions. #pragma once prevents duplicate header inclusion.

#error: Forces a compilation error with a custom message.

C Command Line Arguments

What are Command Line Arguments in C?

Command line arguments allow users to pass input to a program at runtime from the terminal. They are handled through int argc and char *argv[] parameters of main().

argc: Count of arguments including program name. Running ./program hello world gives argc = 3.

argv[]: Array of strings. argv[0] = program name, argv[1] = first argument, etc.

Example program:
int main(int argc, char *argv[]) {
    printf("Program: %s\n", argv[0]);
    for(int i=1; i    return 0;
}

Running: ./program Apple Mango → Arg 1: Apple Arg 2: Mango

C Programs

Important C Programs for Practice

1. Hello World: printf("Hello, World!\n");

2. Swap Two Numbers: temp=a; a=b; b=temp;

3. Fibonacci Series: a=0, b=1, c=a+b; loop to print series.

4. Factorial (Recursion): int factorial(int n){ if(n==0) return 1; return n*factorial(n-1); }

5. Bubble Sort: Compare adjacent pairs, swap if needed. Repeat n-1 passes.

6. Check Prime: Check if n is divisible by any i from 2 to sqrt(n). If not, it's prime.

7. Reverse a String: Swap characters from both ends moving inward using strlen().

8. Linear Search: Loop through array, return index when element found.

9. Binary Search: Find mid, compare with target; search left or right half. Requires sorted array.

10. Matrix Multiplication: Use nested loops — C[i][j] += A[i][k] * B[k][j];

C Interview Questions and Answers

Top C Programming Interview Questions

Q1. What is the difference between ++i and i++?
Ans: ++i (pre-increment) increments first then uses. i++ (post-increment) uses current value first then increments.

Q2. malloc() vs calloc()?
Ans: malloc() allocates uninitialized memory (1 arg: total size). calloc() allocates zero-initialized memory (2 args: count, size).

Q3. What is a dangling pointer?
Ans: A pointer pointing to already freed/deleted memory. Leads to undefined behavior. Set to NULL after free().

Q4. struct vs union?
Ans: struct — each member has own memory, all members usable simultaneously, size = sum of members. union — all share one memory block, one at a time, size = largest member.

Q5. Storage classes in C?
Ans: auto (default local), extern (global across files), static (retains value between calls), register (suggests CPU register).

Q6. volatile keyword?
Ans: Tells compiler the variable may change outside program control (hardware/interrupt). Prevents compiler caching/optimization.

Q7. #include <> vs #include ""?
Ans: <> searches system directories. "" searches current directory first, then system directories.

Q8. What is a memory leak?
Ans: Allocating memory with malloc/calloc but failing to free() it. Causes program to consume increasing memory over time.

Q9. Pointer vs Array?
Ans: Array is fixed-size, name is constant pointer. Pointer is variable storing address, reassignable. sizeof(array) gives total size; sizeof(pointer) gives pointer size.

Q10. const keyword?
Ans: Makes variable read-only after initialization. const int MAX = 100; — attempting to change MAX gives compile error.

C Programming MCQ (Multiple Choice Questions)

C MCQs with Answers

Q1. Correct syntax to declare a pointer in C?
a) int ptr; b) int &ptr; c) int *ptr; d) pointer int ptr;
Answer: c) int *ptr;

Q2. Output of printf("%d", sizeof(char))?
a) 2 b) 4 c) 1 d) 8
Answer: c) 1 — char is always 1 byte.

Q3. Header for malloc() and free()?
a) stdio.h b) string.h c) math.h d) stdlib.h
Answer: d)

Q4. Default value of a local variable?
a) 0 b) NULL c) Garbage value d) -1
Answer: c) Garbage value

Q5. Loop guaranteed to execute at least once?
a) for b) while c) do-while d) None
Answer: c) do-while

Q6. What does break do in switch?
a) Exits program b) Skips to next case c) Exits switch block d) Restarts switch
Answer: c) Exits switch block

Q7. Access structure member via pointer?
a) . (dot) b) * (deref) c) -> (arrow) d) & (address-of)
Answer: c) -> (arrow operator)

Q8. Size of int in a 32-bit system?
a) 1 byte b) 2 bytes c) 4 bytes d) 8 bytes
Answer: c) 4 bytes

Q9. Output of: int a=5; printf("%d", a++);?
a) 6 b) 5 c) 4 d) Error
Answer: b) 5 — post-increment prints 5 first, then a becomes 6.

Q10. Function to compare two strings?
a) strcomp() b) compare() c) strcmp() d) strequal()
Answer: c) strcmp() — returns 0 if equal.

Instructor

Administrator

TUTORX ADMIN

Administrator

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

0 Rating
0 Reviews
93 Students
67 Courses

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Contact TutorX – We're Here to Help You Succeed

Reach out to us for inquiries, support, or more information about our personalized tutoring services

Get in touch

We are happy to hear from you. You can either fill out the form or send us an email.

Address

4th floor, Metro Station, Plot No A1/220, Golf Course Extention Road, Sector 55, Gurugram, Haryana 122011

Email

info@thetutorx.com

Phone

(+91)9013504886

Follow Us

Send Us Message

Shopping Cart

Loading...