Skip to main content


Welcome to Daily Updates

*** Happy Learning***

Quick Links


==> Online Fun Games hub

==>Daily Job Updates IT and Non IT

==>Every month Current Affairs

==>Every month Dividend, Bonus Issue and Stock Split information

==> JAVASCRIPT QUIZ

==>AADHAAR download, Date of birth,name and Address correction, PVC card and more links

==> MICROSOFT EXCEL TUTORIAL

==> SQL Editor - For Practice

C Programming Tutorial 2026: Complete Beginner to Advanced Guide with Examples

Learn C Programming – Complete Beginner to Advanced Guide (2026 Edition)

C is one of the most powerful, efficient, and influential programming languages ever created. Despite being over five decades old, it remains one of the most widely used programming languages in software development, embedded systems, operating systems, device drivers, game engines, and high-performance applications.

If you are completely new to programming, this guide is designed especially for you. Every concept is explained in a simple, beginner-friendly manner with practical examples, diagrams, and coding exercises.

By the end of this tutorial, you'll have a strong understanding of C programming fundamentals and enough confidence to build real-world programs.



What is C Programming?

C is a general-purpose, procedural programming language developed for writing efficient and fast software. It provides direct access to computer memory, making it ideal for developing operating systems, embedded systems, device drivers, and performance-critical applications.

Unlike many modern programming languages, C gives programmers greater control over hardware resources. This makes it one of the best languages for understanding how computers work internally.

Definition

C is a procedural programming language that allows programmers to solve problems by dividing them into functions and executing instructions step by step.

History of C Programming

Understanding the history of C helps explain why it became one of the most influential programming languages in the world.

Year Event
1967 BCPL programming language developed by Martin Richards.
1970 B programming language created by Ken Thompson.
1972 Dennis Ritchie developed C at Bell Laboratories.
1978 The famous book "The C Programming Language" was published by Brian Kernighan and Dennis Ritchie.
1989 ANSI standardized C (ANSI C / C89).
1999 C99 introduced many modern language improvements.
2011 C11 introduced multithreading and safer library features.
2018 C17 released as a maintenance update.
2024 C23 became the latest major ISO standard.
Did You Know?

The Linux kernel, many parts of Windows, databases, embedded systems, and thousands of software libraries are primarily written in C.

Why Learn C Programming?

Although many modern programming languages exist, C remains one of the best languages for beginners because it teaches the core concepts of programming without hiding how computers actually work.

Benefits of Learning C

  • Easy to understand programming fundamentals
  • Excellent performance
  • Portable across different platforms
  • Foundation for C++, Java, and many other languages
  • Used in embedded systems and IoT
  • Develop operating systems and device drivers
  • Strong demand in interviews and competitive programming

Features of C Programming

  • Simple syntax
  • Fast execution speed
  • Portable programs
  • Rich standard library
  • Supports pointers
  • Dynamic memory allocation
  • Modular programming using functions
  • Structured programming
  • Efficient memory management
  • Supports recursion

Applications of C Programming

C is used almost everywhere in computing.

Application Examples
Operating Systems Linux, UNIX, Windows components
Embedded Systems Smart TVs, Washing Machines, Routers
Game Engines Game development libraries
Databases MySQL, PostgreSQL
Compilers GCC, Clang
Networking Routers and communication software
Robotics Controllers and firmware

Advantages of C

  • Very fast execution
  • Small memory usage
  • Easy to interface with hardware
  • Highly portable
  • Large community support
  • Excellent career opportunities

Limitations of C

  • No built-in Object-Oriented Programming
  • No automatic garbage collection
  • Manual memory management
  • Less secure compared to some modern languages if used incorrectly

How Does a C Program Work?

Every C program follows a series of steps before it runs.


Source Code
     │
     ▼
Preprocessor
     │
     ▼
Compiler
     │
     ▼
Assembler
     │
     ▼
Linker
     │
     ▼
Executable Program
     │
     ▼
Output

We'll explore each stage in detail in the next chapter.


Installing a C Compiler

To write and run C programs, you need a compiler.

Windows

  • Code::Blocks (Recommended for Beginners)
  • Visual Studio Community
  • MinGW GCC

Linux


sudo apt install gcc

macOS


xcode-select --install


Your First C Program



#include <stdio.h>

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

    return 0;
}

Output


Hello, World!


Understanding the Program

Code Purpose
#include <stdio.h> Includes the Standard Input/Output library.
int main(void) The entry point of every C program.
printf() Displays output on the screen.
return 0; Indicates successful program execution.
Common Beginner Mistake

Many old tutorials use void main(). Modern C recommends using:

int main(void)
{
    return 0;
}
This is portable and follows the C standard.

Compilation Process

When you compile a C program, several steps occur behind the scenes:

  1. Preprocessing – Handles directives like #include and #define.
  2. Compilation – Converts C code into assembly language.
  3. Assembly – Converts assembly into machine code.
  4. Linking – Combines object files and libraries into an executable.

Summary

  • C is a procedural, general-purpose programming language.
  • It was developed by Dennis Ritchie in 1972.
  • C is fast, efficient, and widely used.
  • Modern C programs use int main(void).
  • The compilation process consists of preprocessing, compilation, assembly, and linking.

Practice Questions

  1. Who developed the C programming language?
  2. In which year was C introduced?
  3. What is the purpose of #include <stdio.h>?
  4. Why do we use return 0;?
  5. Name three real-world applications of C.
  6. What are the four stages of compilation?
  7. Write a program to print your name.
  8. Write a program to print your college name.

Next Chapter: Structure of a C Program, Tokens, Keywords, Identifiers, Comments, and Basic Syntax.


Structure of a C Program

Every C program follows a standard structure. Understanding this structure is the first step toward becoming a good C programmer.

A simple C program generally contains the following sections:

  1. Documentation Section
  2. Preprocessor Directives
  3. Global Declaration Section (Optional)
  4. main() Function
  5. User-defined Functions (Optional)

Basic Program Structure


#include <stdio.h>

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

    return 0;
}

Explanation of Each Part

1. Documentation Section

The documentation section contains comments that explain the purpose of the program. Comments are ignored by the compiler but are extremely useful for programmers.


/*
 Program Name : Hello World
 Author       : Your Name
 Description  : Prints Hello World
*/
Good comments make your code easier to understand and maintain.

2. Preprocessor Directives

Preprocessor directives begin with the # symbol and are processed before compilation starts.

Example


#include <stdio.h>
#define PI 3.14159

The preprocessor performs tasks such as:

  • Including header files
  • Creating macros
  • Conditional compilation
  • File inclusion

3. Global Declaration Section

Variables and function declarations placed outside every function are called global declarations.


#include <stdio.h>

int number = 100;

int main(void)
{
    printf("%d", number);

    return 0;
}

4. main() Function

Every C program starts executing from the main() function. It is known as the entry point of the program.


int main(void)
{
    return 0;
}
Without the main() function, a standard C program cannot execute.

5. User-defined Functions

To make programs organized and reusable, programmers divide large problems into smaller functions.


#include <stdio.h>

void greet(void)
{
    printf("Welcome!");
}

int main(void)
{
    greet();

    return 0;
}

Comments in C

Comments improve code readability and help explain logic.

Single-line Comment


// This is a single-line comment

Multi-line Comment


/*
This is a
multi-line comment.
*/
Comments are ignored by the compiler and do not affect program execution.

Tokens in C

A token is the smallest individual unit of a C program. Every C program is made up of tokens.

Types of Tokens

Token Type Example
Keywords int, return, if
Identifiers age, totalMarks
Constants 100, 3.14, 'A'
Strings "Hello"
Operators +, -, *, /
Special Symbols { } ( ) ; ,

Keywords in C

Keywords are reserved words that have predefined meanings in the C language. They cannot be used as variable names, function names, or identifiers.

Examples of Keywords

int char float double
if else switch case
for while do break
continue return struct union
enum typedef const static
Older C standards defined 32 keywords. Modern C standards include additional keywords introduced in later versions (such as C99, C11, and C23).

Identifiers in C

Identifiers are user-defined names given to variables, functions, arrays, structures, and other program elements.

Rules for Naming Identifiers

  • Must begin with a letter or underscore (_).
  • Can contain letters, digits, and underscores.
  • Cannot start with a digit.
  • Cannot contain spaces.
  • Cannot use special characters like @, #, %, !.
  • Cannot be a keyword.

Valid Identifiers


age
studentName
_marks
total1
price_per_item

Invalid Identifiers


2age
student-name
float
total marks
#value

Variables in C

A variable is a named memory location used to store data. The value stored in a variable can change during program execution.

Syntax


data_type variable_name;

Example


int age = 20;
float salary = 25000.50f;
char grade = 'A';

Rules for Naming Variables

  • Must follow identifier rules.
  • Should have meaningful names.
  • Avoid single-letter names except in loops.
  • Use camelCase or snake_case consistently.

Good Examples


studentAge
totalMarks
monthlySalary

Poor Examples


a
x
abc
temp1

Constants in C

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

Integer Constant


100
250
-50

Floating-point Constant


3.14
5.5
0.001

Character Constant


'A'
'Z'
'9'

String Constant


"Hello"
"C Programming"

The const Keyword

The const keyword is used to declare read-only variables whose values cannot be modified after initialization.


const float PI = 3.14159f;

printf("%.2f", PI);
Attempting to modify a const variable results in a compilation error.

Example Program


#include <stdio.h>

int main(void)
{
    int age = 20;
    float height = 5.8f;
    char grade = 'A';
    const float PI = 3.14159f;

    printf("Age    : %d\n", age);
    printf("Height : %.1f\n", height);
    printf("Grade  : %c\n", grade);
    printf("PI     : %.5f\n", PI);

    return 0;
}

Output

Age    : 20
Height : 5.8
Grade  : A
PI     : 3.14159

Common Mistakes

  • Using keywords as variable names.
  • Starting variable names with numbers.
  • Forgetting the semicolon at the end of a statement.
  • Using uninitialized variables.
  • Confusing character constants ('A') with string literals ("A").

Practice Questions

  1. What is the entry point of every C program?
  2. What is a token?
  3. What is the difference between an identifier and a keyword?
  4. Write five valid variable names.
  5. Write five invalid variable names and explain why they are invalid.
  6. What is the purpose of the const keyword?
  7. Write a program that stores your name, age, and percentage using variables.

Chapter Summary

  • Every C program has a standard structure.
  • The main() function is the program's entry point.
  • Comments improve code readability.
  • Tokens are the smallest units in a C program.
  • Keywords are reserved words.
  • Identifiers are user-defined names.
  • Variables store data that can change.
  • Constants store fixed values.

Next Chapter: Data Types, Type Modifiers, Memory Sizes, Literals, and Type Conversion.


Data Types in C Programming

A data type specifies the type of value that a variable can store. It also determines how much memory is allocated for the variable and what operations can be performed on it.

For example, if you want to store a student's age, you can use an int. If you want to store a decimal number such as a salary or temperature, you should use float or double.

Definition

A data type tells the compiler:
  • What kind of data will be stored.
  • How much memory should be allocated.
  • What range of values can be stored.

Why Do We Need Data Types?

Imagine every variable occupied the same amount of memory regardless of what it stores. A single character would consume the same memory as a large decimal number, wasting system resources.

Data types help the compiler allocate only the required amount of memory, making programs efficient.


Classification of Data Types

C data types are broadly classified into the following categories:

Category Examples
Basic (Primitive) int, char, float, double
Derived Array, Pointer, Function
User-defined struct, union, enum, typedef
Void void

Basic Data Types

1. int (Integer)

The int data type is used to store whole numbers (integers) without decimal points.


int age = 25;
int marks = 98;
int population = 1500000;

Output

25
98
1500000

Examples of integers:

  • -100
  • 0
  • 20
  • 99999

2. float

The float data type stores decimal (floating-point) numbers with approximately 6–7 digits of precision.


float temperature = 36.5f;
float price = 99.99f;

Examples

  • 3.14
  • 5.75
  • 0.125

3. double

The double data type is similar to float but provides much higher precision, typically around 15–16 decimal digits.


double pi = 3.141592653589793;
Use double whenever higher precision is required, such as scientific calculations or financial applications.

4. char

The char data type stores a single character enclosed in single quotes.


char grade = 'A';
char symbol = '#';
char digit = '5';

Internally, characters are stored using their ASCII values.


char ch = 'A';

printf("%d", ch);

Output

65

Memory Size of Basic Data Types

The actual size depends on the compiler and system architecture, but the following sizes are common on modern systems:

Data Type Typical Size Purpose
char 1 Byte Single character
short 2 Bytes Small integers
int 4 Bytes Whole numbers
long 4 or 8 Bytes Large integers
long long 8 Bytes Very large integers
float 4 Bytes Decimal numbers
double 8 Bytes High precision decimals
long double Compiler dependent Higher precision
The C standard specifies minimum requirements for data type ranges, not exact sizes. Sizes may vary depending on the compiler and operating system.

Finding the Size of Data Types

The sizeof operator returns the number of bytes occupied by a data type or variable.


#include <stdio.h>

int main(void)
{
    printf("int = %zu\n", sizeof(int));
    printf("char = %zu\n", sizeof(char));
    printf("float = %zu\n", sizeof(float));
    printf("double = %zu\n", sizeof(double));

    return 0;
}

Type Modifiers

Type modifiers change the size or range of basic data types.

Modifier Description
short Reduces integer size.
long Increases integer size.
signed Allows positive and negative values.
unsigned Stores only positive values.

Examples


short int a = 10;
long int b = 500000L;
unsigned int c = 100;
signed int d = -20;

Signed vs Unsigned Integers

Signed Unsigned
Can store positive and negative values. Stores only zero and positive values.
Uses one bit for the sign. Uses all bits for magnitude.

Literals in C

A literal is a fixed value written directly in the source code.

Integer Literal


10
250
-45

Floating Literal


3.14
6.25

Character Literal


'A'
'Z'
'7'

String Literal


"Hello"
"C Programming"

Escape Sequences

Escape sequences are special characters that begin with a backslash (\) and are used to format output.

Escape Sequence Description
\n New line
\t Horizontal tab
\\ Backslash
\" Double quote
\' Single quote
\r Carriage return

Example


printf("Hello\nWorld");

Output

Hello
World

Memory Representation

Suppose we declare the following variable:


int age = 25;

The computer allocates memory for this variable.

+--------------------+
| Variable : age     |
| Value    : 25      |
| Size     : 4 Bytes |
+--------------------+

Every variable occupies memory in RAM, and the compiler keeps track of its location.


Example Program


#include <stdio.h>

int main(void)
{
    int age = 20;
    float height = 5.8f;
    double salary = 45000.75;
    char grade = 'A';

    printf("Age    : %d\n", age);
    printf("Height : %.1f\n", height);
    printf("Salary : %.2lf\n", salary);
    printf("Grade  : %c\n", grade);

    return 0;
}

Common Mistakes

  • Using float when higher precision is needed.
  • Using %f to print an int.
  • Using double quotes for characters instead of single quotes.
  • Assuming the size of every data type is the same on all systems.

Interview Questions

  1. What is a data type?
  2. What is the difference between float and double?
  3. What does the sizeof operator do?
  4. Explain the difference between signed and unsigned integers.
  5. What is a literal?
  6. Why is char stored as an integer internally?

Practice Programs

  1. Print the size of all basic data types.
  2. Store your age, height, and grade in variables and display them.
  3. Write a program to print the ASCII value of a character.
  4. Use different escape sequences to format the output.
  5. Declare variables using all type modifiers and display their values.

Chapter Summary

  • Data types define the kind of data a variable can store.
  • C provides primitive, derived, user-defined, and void data types.
  • sizeof returns the memory occupied by a data type or variable.
  • Type modifiers change the size or range of data types.
  • Literals are fixed values written directly in the source code.
  • Escape sequences help format output.

Next Chapter: Input & Output Functions, Format Specifiers, printf(), scanf(), and Console Input.


Input and Output in C Programming

Every program communicates with users by taking input and displaying output. For example, a calculator takes two numbers as input, performs calculations, and displays the result.

In C, input and output operations are mainly performed using functions provided by the stdio.h (Standard Input and Output) header file.


#include <stdio.h>
The stdio.h header file contains declarations for commonly used input and output functions such as printf(), scanf(), getchar(), and putchar().

Output in C using printf()

The printf() function is used to display text, numbers, and formatted output on the screen.

Syntax


printf("format string", arguments);

Example


#include <stdio.h>

int main(void)
{
    printf("Welcome to C Programming!");

    return 0;
}

Output

Welcome to C Programming!

Printing Variables


#include <stdio.h>

int main(void)
{
    int age = 20;

    printf("Age = %d", age);

    return 0;
}

Output

Age = 20

Format Specifiers

A format specifier tells printf() or scanf() what type of data is being printed or read.

Specifier Data Type Example
%d or %i int 25
%u unsigned int 50
%f float 3.14
%lf double 3.141592
%c char A
%s string Hello
%x Hexadecimal FF
%o Octal 77
%p Pointer Address 0x7ffd...
Always use the correct format specifier. Using the wrong one may produce incorrect output or undefined behavior.

Escape Sequences in printf()

Escape sequences are special characters that begin with a backslash (\) and are used to format the output.

Escape Sequence Description
\nNew line
\tHorizontal tab
\\Backslash
\"Double quotation mark
\'Single quotation mark
\rCarriage return
\bBackspace

Example


printf("Name:\tJohn\nAge:\t20");

Output

Name:   John
Age:    20

Input in C using scanf()

The scanf() function reads formatted input from the keyboard.

Syntax


scanf("format", &variable);
For most scalar variables (such as int, float, and char), scanf() requires the address-of operator (&). Arrays used as strings are an exception because the array name already refers to its first element.

Example


#include <stdio.h>

int main(void)
{
    int age;

    printf("Enter your age: ");
    scanf("%d", &age);

    printf("Your age is %d", age);

    return 0;
}

Sample Output

Enter your age: 20
Your age is 20

Reading Multiple Values


#include <stdio.h>

int main(void)
{
    int a, b;

    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    printf("Sum = %d", a + b);

    return 0;
}

Reading Characters


char grade;

scanf(" %c", &grade);
printf("%c", grade);
Notice the leading space before %c. It tells scanf() to skip leading whitespace (such as a leftover newline) before reading the character.

Reading Strings

For a single word, you can use:


char name[30];

scanf("%29s", name);

To read a full line (including spaces), use fgets() instead:


char name[30];

fgets(name, sizeof(name), stdin);
Prefer fgets() over older functions such as gets(), which is unsafe and has been removed from the C standard.

getchar() and putchar()

These functions work with a single character.

Example


#include <stdio.h>

int main(void)
{
    char ch;

    ch = getchar();

    putchar(ch);

    return 0;
}

Example Program


#include <stdio.h>

int main(void)
{
    char name[30];
    int age;
    float marks;

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

    printf("Enter age: ");
    scanf("%d", &age);

    printf("Enter marks: ");
    scanf("%f", &marks);

    printf("\nStudent Details\n");
    printf("----------------\n");
    printf("Name  : %s\n", name);
    printf("Age   : %d\n", age);
    printf("Marks : %.2f\n", marks);

    return 0;
}

Common Mistakes

  • Using the wrong format specifier.
  • Forgetting the & with scalar variables in scanf().
  • Using %d for a float or %f for an int.
  • Using gets(), which is unsafe.
  • Using scanf("%s") when the input may contain spaces.

Best Practices

  • Use meaningful prompts for user input.
  • Prefer fgets() for reading lines of text.
  • Match every variable with the correct format specifier.
  • Format output neatly using \n and \t.

Interview Questions

  1. What is the difference between printf() and scanf()?
  2. Why do we use & with scanf()?
  3. What is a format specifier?
  4. What is the difference between %f and %lf?
  5. Why is gets() considered unsafe?

Practice Programs

  1. Read two integers and print their sum.
  2. Read a student's name, roll number, and marks, then display them in a formatted table.
  3. Read a character and print its ASCII value.
  4. Read a floating-point number and display it with two decimal places.
  5. Use fgets() to read a full name that includes spaces.

Chapter Summary

  • printf() displays formatted output.
  • scanf() reads formatted input.
  • Format specifiers must match the data type.
  • Escape sequences improve output formatting.
  • getchar() and putchar() handle single characters.
  • fgets() is the preferred way to read a line of text.

Next Chapter: Operators in C Programming (Arithmetic, Relational, Logical, Assignment, Bitwise, Increment/Decrement, Conditional, and Operator Precedence).

Data Types in C Programming

Every variable in C must have a data type. A data type tells the compiler what kind of data the variable will store and how much memory should be allocated.

Definition: A data type specifies the type of value a variable can hold, such as integers, decimal numbers, or characters.

Basic Data Types in C

Data Type Description Typical Size Example
int Stores whole numbers 4 Bytes 10, -25, 500
float Stores decimal numbers (single precision) 4 Bytes 5.75
double Stores decimal numbers (double precision) 8 Bytes 123.456789
char Stores a single character 1 Byte 'A'

1. Integer (int)

The int data type stores whole numbers without decimal values.

Example:

int age = 20;
int marks = 95;

printf("%d", age);

Output


20
Use %d while printing integer values using printf().
---

2. Float

The float data type stores decimal numbers with approximately 6-7 digits of precision.

Example

float pi = 3.14;

printf("%f", pi);
Output

3.140000
You can limit decimal places.

printf("%.2f", pi);
Output

3.14
---

3. Double

The double data type also stores decimal numbers but provides much higher precision than float.

Example

double salary = 12345.987654;

printf("%lf", salary);
Use double whenever higher precision is required, especially in scientific calculations.
---

4. Character (char)

The char data type stores a single character enclosed within single quotes.

Example

char grade = 'A';

printf("%c", grade);
Output

A
---

Signed and Unsigned Data Types

Integer and character data types can be either signed or unsigned.

Type Description
signed int Stores both positive and negative numbers.
unsigned int Stores only positive numbers, giving a larger positive range.
signed char Range: -128 to 127
unsigned char Range: 0 to 255
---

Short and Long Integers

To optimize memory usage or increase range, C provides additional integer types.


short int a;

long int b;

long long int c;
---

Type Modifiers

Modifier Purpose
short Uses less memory
long Stores larger values
signed Allows positive and negative values
unsigned Allows only positive values
---

Size of Data Types

You can determine the memory occupied by a data type using the sizeof() operator. Example

printf("%d", sizeof(int));
printf("%d", sizeof(char));
printf("%d", sizeof(float));
---
Actual memory size depends on your compiler and operating system.

Variables in C Programming

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

Example

int age = 21;
Here,
  • int → Data Type
  • age → Variable Name
  • 21 → Value
---

Variable Declaration

Before using a variable, it must be declared. Example

int marks;
float percentage;
char grade;
---

Variable Initialization

Assigning a value during declaration is called initialization.

int marks = 95;
float pi = 3.14;
char ch = 'A';
---

Rules for Naming Variables

A valid variable name:
  • Can contain letters.
  • Can contain digits.
  • Can contain underscore (_).
  • Cannot start with a number.
  • Cannot contain spaces.
  • Cannot contain special symbols.
  • Cannot be a C keyword.
---

Valid Variable Names


int age;

int student_marks;

int _count;

int total1;
---

Invalid Variable Names


int 2age;

int total marks;

int float;

int @value;
---

Identifier vs Variable

An identifier is any user-defined name in C. Variables, functions, arrays, structures, and labels are all identifiers.

Example

int age;

float salary;

void display();
Here,
  • age is an identifier.
  • salary is an identifier.
  • display is also an identifier.
---
Every variable is an identifier, but every identifier is not necessarily a variable.
---

Best Practices

✔ Use meaningful names. ✔ Keep names short but descriptive. ✔ Follow camelCase or snake_case consistently. Good Examples

studentAge

totalMarks

averageScore
Bad Examples

a

x

abc1234
---
Choosing meaningful variable names makes your code easier to read, debug, and maintain.

Input and Output in C Programming

Every program interacts with users by taking input and displaying output. In C programming, this is done using predefined functions available in the <stdio.h> header file.

Note: The stdio.h header file stands for Standard Input and Output. It provides functions like printf() and scanf().
---

Output Function - printf()

The printf() function is used to display text, numbers, characters, and other values on the screen.

Syntax

printf("Message");
Example

#include <stdio.h>

int main()
{
    printf("Welcome to C Programming");

    return 0;
}
Output

Welcome to C Programming
---

Printing Variables

Example

#include <stdio.h>

int main()
{
    int age = 20;

    printf("%d", age);

    return 0;
}
Output

20
---

Printing Multiple Values


#include <stdio.h>

int main()
{
    int age = 20;
    float cgpa = 8.75;
    char grade = 'A';

    printf("%d %.2f %c", age, cgpa, grade);

    return 0;
}
Output

20 8.75 A
---

Input Function - scanf()

The scanf() function is used to read input from the keyboard.

Syntax

scanf("format_specifier", &variable);
Example

#include <stdio.h>

int main()
{
    int age;

    scanf("%d", &age);

    printf("Age = %d", age);

    return 0;
}
Input

25
Output

Age = 25
---

Why Do We Use (&) in scanf()?

The & (address-of operator) tells the compiler where the entered value should be stored in memory.

Correct

scanf("%d", &age);
Incorrect

scanf("%d", age);
For basic variables such as int, float, and char, always use the & operator with scanf().
---

Reading a Character


char ch;

scanf("%c", &ch);

printf("%c", ch);
Input

A
Output

A
---

Reading a Decimal Number


float salary;

scanf("%f", &salary);

printf("%.2f", salary);
Input

12500.50
Output

12500.50
---

Format Specifiers in C

A format specifier tells the compiler what type of data is being printed or read.

Specifier Data Type Example
%d Integer 25
%f Float 3.14
%lf Double 99.999
%c Character A
%s String Hello
%u Unsigned Integer 250
%x Hexadecimal 2A
%o Octal 52
---

Example Using Different Format Specifiers


#include <stdio.h>

int main()
{
    int a = 25;
    float b = 5.6;
    char c = 'A';

    printf("%d\n", a);
    printf("%.2f\n", b);
    printf("%c", c);

    return 0;
}
Output

25
5.60
A
---

Escape Sequences

Escape sequences are special characters that begin with a backslash (\) and are used to format the output.

Escape Sequence Description
\n New Line
\t Horizontal Tab
\\ Prints Backslash
\" Prints Double Quote
\' Prints Single Quote
\b Backspace
\r Carriage Return
--- Example

printf("Hello\nWorld");
Output

Hello
World
Example

printf("C\tProgramming");
Output

C       Programming
---

Comments in C

Comments are notes written inside a program. They are ignored by the compiler and help programmers understand the code.

---

Single Line Comment


// This is a comment

printf("Hello");
---

Multi-line Comment


/*
This is
a multi-line
comment
*/

printf("Hello");
---

Why Comments Are Important?

  • Improve code readability.
  • Help during debugging.
  • Explain complex logic.
  • Useful for teamwork.
  • Ignored during compilation.
---
Good programmers write code for humans first and computers second. Well-written comments make programs much easier to understand.
---

Practice Programs

Program 1: Print Your Name


#include <stdio.h>

int main()
{
    printf("My name is Rahul");

    return 0;
}
---

Program 2: Read and Print an Integer


#include <stdio.h>

int main()
{
    int number;

    printf("Enter a number: ");

    scanf("%d", &number);

    printf("You entered %d", number);

    return 0;
}
---

Program 3: Read Two Numbers


#include <stdio.h>

int main()
{
    int a, b;

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

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

    printf("Second = %d", b);

    return 0;
}
---
Congratulations! 🎉 You now know how to:
  • Display output using printf()
  • Take user input using scanf()
  • Use format specifiers correctly
  • Format output with escape sequences
  • Write comments for better code readability
These concepts are used in almost every C program you'll write.

Operators in C Programming Language

Operators are special symbols that perform operations on variables and values. They are one of the most important concepts in C programming because almost every program uses operators to perform calculations, comparisons, and logical decisions.

Definition: An operator is a symbol that tells the compiler to perform a specific operation on one or more operands.

Example:


a + b;

Here:

  • + is the operator.
  • a and b are operands.

Types of Operators in C

C operators are mainly classified into the following categories:

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical Operators
  4. Assignment Operators
  5. Increment and Decrement Operators
  6. Bitwise Operators
  7. Conditional (Ternary) Operator
  8. sizeof Operator

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, and division.

Operator Operation Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (remainder) a % b

Example


#include <stdio.h>

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

    printf("%d\n", a+b);
    printf("%d\n", a-b);
    printf("%d\n", a*b);
    printf("%d\n", a/b);
    printf("%d\n", a%b);

    return 0;
}
Output:

13
7
30
3
1
When both numbers are integers, division gives only the integer part. Example: 10 / 3 gives 3, not 3.333.

2. Relational Operators

Relational operators are used to compare two values. The result will be either true (1) or false (0).

Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to
Example:

int a = 10;
int b = 20;

printf("%d", a < b);
Output:

1
Do not confuse = and ==. = → Assignment == → Comparison
Example:

a = 5;     // Assigns value

a == 5;    // Checks equality

3. Logical Operators

Logical operators are used to combine multiple conditions.

Operator Name
&& Logical AND
|| Logical OR
! Logical NOT

Logical AND (&&)

Returns true only when all conditions are true.

Example:

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

Logical OR (||)

Returns true if at least one condition is true.

Example:

if(mark > 90 || attendance > 95)
{
    printf("Allowed");
}

Logical NOT (!)

Example:

int a = 0;

printf("%d", !a);
Output:

1

4. Assignment Operators

Assignment operators are used to assign values to variables.

Operator Example Equivalent
= a = 5 Assign value
+= a += 5 a = a + 5
-= a -= 5 a = a - 5
*= a *= 5 a = a * 5
/= a /= 5 a = a / 5
Example:

int a = 10;

a += 5;

printf("%d", a);
Output:

15

5. Increment and Decrement Operators

These operators increase or decrease the value of a variable by one.

Increment Operator (++ )

Example:

int a = 5;

a++;

printf("%d",a);
Output:

6

Decrement Operator (--)

Example:

int a = 5;

a--;

printf("%d",a);
Output:

4

Types of Increment

Post Increment

Value is used first, then increased.


int a=5;

printf("%d",a++);

Output:

5

Pre Increment

Value is increased first, then used.


int a=5;

printf("%d",++a);

Output:

6

6. Bitwise Operators

Bitwise operators perform operations on individual bits of numbers.

Operator Operation
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Left shift
>> Right shift
Example:

int a = 5;
int b = 3;

printf("%d", a & b);
Binary:

5 = 101
3 = 011

AND = 001
Output:

1

7. Conditional (Ternary) Operator

The ternary operator is a short form of an if-else statement.

Syntax:

condition ? true_value : false_value;
Example:

int a = 10;
int b = 20;

int max = (a>b) ? a : b;

printf("%d", max);
Output:

20

8. sizeof Operator

The sizeof() operator is used to find the memory size occupied by a variable or data type.

Example:

#include <stdio.h>

int main()
{
    printf("%d", sizeof(int));

    return 0;
}
Output may be:

4
The output of sizeof depends on the compiler and system architecture.

Operator Precedence in C

When multiple operators are used in a single expression, C follows operator precedence rules to decide which operation happens first.

Example:

int result = 10 + 5 * 2;
Calculation:

5 * 2 = 10

10 + 10 = 20
Output:

20

Basic Priority Order

  1. Parentheses ()
  2. Unary operators (++ , -- , !)
  3. Multiplication, Division, Modulus
  4. Addition and Subtraction
  5. Relational operators
  6. Logical operators
  7. Assignment operators
Using parentheses makes your code easier to understand and avoids mistakes.

Practice Questions

Question 1


int a = 5;

printf("%d", a++);
Output?

Question 2


printf("%d", 10%3);
Output?

Question 3


printf("%d", 5 < 10);
Output? ---

Arrays in C Programming Language

Arrays are one of the most important concepts in C programming. An array allows us to store multiple values of the same data type using a single variable name.

Definition: An array is a collection of elements having the same data type stored in continuous memory locations.

Why do we need Arrays?

Suppose we want to store marks of 100 students. Creating 100 separate variables is difficult. Instead, we can use an array.

int marks[100];

Array Index

Every array element has an index number. In C programming, array indexing always starts from 0.

Index Value
0 10
1 20
2 30

Types of Arrays

  • 1. One Dimensional Array: Used to store data in a single row.
  • 2. Two Dimensional Array: Used to represent matrices (rows and columns).
  • 3. Multi Dimensional Array: Used when more than two dimensions are required.

1. One Dimensional Array Example

#include <stdio.h>

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

    printf("%d", numbers[2]);

    return 0;
}

Output:

30

Here numbers[2] represents the third element because array indexing starts from zero.

2. Two Dimensional Array Example


#include <stdio.h>

int main()
{
    int matrix[2][2] =
    {
        {1,2},
        {3,4}
    };

    printf("%d",matrix[1][0]);

    return 0;
}

Output:

3

Strings in C Programming Language

In C language, there is no separate string data type. Strings are created using an array of characters.

String Definition: A string is a collection of characters terminated by a special character called NULL character (\0).

Declaring a String


char name[20];

The above statement creates a character array that can store up to 19 characters. The last character is reserved for the NULL character.

String Initialization Example


#include <stdio.h>

int main()
{
    char name[]="C Programming";

    printf("%s",name);

    return 0;
}

Output:

C Programming

Important String Functions

Function Purpose
strlen() Finds length of string
strcpy() Copies one string into another
strcat() Combines two strings
strcmp() Compares two strings

Example: Finding String Length


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

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

    int length;

    length=strlen(text);

    printf("%d",length);

    return 0;
}

Output:

5

Functions in C Programming Language

A function is a block of code designed to perform a specific task. Functions improve code reusability and make programs easier to understand.

Advantages of Functions

  • Reduces code repetition
  • Makes programs easier to maintain
  • Improves readability
  • Helps in debugging

Types of Functions

  • Library Functions: Functions already provided by C language. Example: printf(), scanf(), strlen()
  • User Defined Functions: Functions created by programmers.

Function Syntax


return_type function_name(parameters)
{
    statements;
}

Example Program


#include <stdio.h>

void message()
{
    printf("Welcome to C Programming");
}


int main()
{
    message();

    return 0;
}

Output:

Welcome to C Programming

Function Arguments and Return Values in C

Functions can receive data from the calling function using parameters (arguments). They can also return a value after completing their task.

Types of Functions Based on Arguments and Return Value

Type Description Example
No arguments and no return value Function does not receive or return any data. void display()
Arguments but no return value Function receives data but does not return anything. void add(int a,int b)
No arguments but return value Function returns a value without receiving data. int getNumber()
Arguments with return value Function receives data and returns a result. int sum(int a,int b)

Example: Function with Arguments and Return Value


#include <stdio.h>


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


int main()
{
    int result;

    result = add(10,20);

    printf("%d",result);

    return 0;
}

Output:

30

Recursion in C Programming

Recursion is a process where a function calls itself repeatedly until a specific condition becomes false.

Important: Every recursive function must have a terminating condition; otherwise, it will execute forever and may cause stack overflow.

Example: Factorial Using Recursion


#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

Execution:


5 × 4 × 3 × 2 × 1 = 120


Storage Classes in C Programming

Storage classes define the scope, lifetime, visibility, and default value of variables in C.

Types of Storage Classes

Storage Class Meaning
auto Default storage class for local variables.
register Stores variables in CPU registers for faster access.
static Maintains value throughout program execution.
extern Used to access global variables from another file.

Example of Static Variable


#include <stdio.h>


void count()
{
    static int value=0;

    value++;

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


int main()
{
    count();
    count();
    count();

    return 0;
}

Output:


1
2
3

Because the variable is static, its value is preserved between function calls.


Pointers in C Programming Language

Pointers are one of the most powerful concepts in C programming. A pointer is a variable that stores the memory address of another variable.

Simple Definition: A pointer stores the address of a variable instead of storing the actual value.

Why Do We Need Pointers?

  • Used for dynamic memory allocation
  • Used for efficient array handling
  • Used for passing variables by reference
  • Used in data structures like linked lists and trees

Pointer Declaration


data_type *pointer_name;

Example:


int *ptr;

Pointer Example Program


#include <stdio.h>


int main()
{

    int number=10;

    int *ptr;


    ptr=&number;


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

    printf("Address = %p",ptr);


    return 0;

}

Output:


Value = 10
Address = 0x7ffee...

The address value may change every time the program runs because memory allocation is handled by the operating system.

Important Pointer Operators

Operator Purpose
& Returns the address of a variable.
* Accesses the value stored at an address.

Example of Dereferencing Pointer


#include <stdio.h>


int main()
{

    int a=50;

    int *p=&a;


    printf("%d",*p);


    return 0;

}

Output:

50
Beginner Tip: Remember:
& means "address of"
* means "value stored at that address"

Dynamic Memory Allocation in C Programming

Dynamic memory allocation allows a program to allocate memory during runtime instead of allocating memory before execution.

In C programming, dynamic memory allocation functions are available inside the stdlib.h header file.

Header File Required:
#include <stdlib.h>

Why Do We Need Dynamic Memory Allocation?

  • Memory can be allocated when required.
  • Avoids wastage of memory.
  • Useful for creating dynamic data structures.
  • Helps when the size of data is unknown during compilation.

Dynamic Memory Allocation Functions

Function Purpose
malloc() Allocates a block of memory.
calloc() Allocates multiple blocks and initializes memory with zero.
realloc() Changes the size of previously allocated memory.
free() Releases allocated memory.

Example Using malloc()


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


int main()
{

    int *ptr;


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


    *ptr=100;


    printf("%d",*ptr);


    free(ptr);


    return 0;
}

Output:

100
Always use free() after dynamic memory allocation to avoid memory leaks.

Structures in C Programming Language

A structure is a user-defined data type that allows us to store different types of data under one name.

Example: A student has different information like name, roll number, and marks. A structure can store all these details together.

Syntax of Structure


struct structure_name
{

    data_type variable1;

    data_type variable2;

};

Structure Example Program


#include <stdio.h>


struct Student
{

    int roll;

    float marks;

};


int main()
{

    struct Student s1;


    s1.roll=101;

    s1.marks=95.5;


    printf("%d\n",s1.roll);

    printf("%.1f",s1.marks);


    return 0;

}

Output:


101

95.5

Accessing Structure Members

The dot operator (.) is used to access structure members.


student.roll;

student.marks;


Union in C Programming Language

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

In a structure, every member gets separate memory.
In a union, all members use the same memory.

Syntax of Union


union union_name
{

    data_type variable1;

    data_type variable2;

};

Difference Between Structure and Union

Structure Union
Each member has separate memory. All members share the same memory.
All values can be stored at the same time. Only one member value is meaningful at a time.
Requires more memory. Requires less memory.

Enumeration (enum) in C Programming

Enumeration is a user-defined data type that consists of a set of named integer constants.

Syntax


enum name
{

    value1,

    value2,

    value3

};

Example


#include <stdio.h>


enum Days
{

    Monday,

    Tuesday,

    Wednesday

};


int main()
{

    enum Days today;


    today=Tuesday;


    printf("%d",today);


    return 0;

}

Output:

1

By default, enum values start from zero.


Typedef in C Programming Language

The typedef keyword is used to create a new name (alias) for an existing data type.

Example


#include <stdio.h>


typedef unsigned int number;


int main()
{

    number age=25;


    printf("%d",age);


    return 0;

}

Output:

25
Remember:
struct → groups different data types
union → shares memory between members
enum → creates named constants
typedef → creates a new name for an existing type

File Handling in C Programming

File handling allows programs to permanently store and retrieve data from files. Unlike variables, data stored in files remains available even after the program terminates.

Header File Required:
#include <stdio.h>

Why File Handling?

  • Store data permanently
  • Read previously saved data
  • Maintain records such as student details, employee information, etc.
  • Exchange data between different programs

Steps to Work with Files

  1. Create a file pointer.
  2. Open the file using fopen().
  3. Read or write data.
  4. Close the file using fclose().

Opening a File

FILE *fp;

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

Common File Modes

Mode Description
r Read existing file
w Create a new file or overwrite existing file
a Append data to existing file
r+ Read and write
w+ Read and overwrite
a+ Read and append

Example: Writing to a File

#include <stdio.h>

int main()
{
    FILE *fp;

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

    fprintf(fp,"Welcome to C Programming");

    fclose(fp);

    return 0;
}

Example: Reading from a File

#include <stdio.h>

int main()
{
    FILE *fp;

    char text[100];

    fp = fopen("student.txt","r");

    fscanf(fp,"%s",text);

    printf("%s",text);

    fclose(fp);

    return 0;
}

Command Line Arguments

Command line arguments allow users to pass values to a program while executing it.

int main(int argc, char *argv[])
{
}
Parameter Description
argc Number of command line arguments.
argv Array containing the arguments.

Preprocessor Directives

Preprocessor directives are instructions executed before the actual compilation starts.

Common Preprocessor Directives

Directive Purpose
#include Includes header files
#define Defines constants or macros
#ifdef Checks if macro exists
#ifndef Checks if macro does not exist
#endif Ends conditional compilation
#undef Removes a defined macro

Example

#define PI 3.14159

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

Bitwise Operators

Bitwise operators work directly on binary numbers. They are widely used in embedded systems, operating systems, and competitive programming.

Operator Name
& AND
| OR
^ XOR
~ NOT
<< Left Shift
>> Right Shift

Memory Layout of a C Program

Every C program is divided into different memory segments.

Segment Purpose
Code Segment Stores program instructions.
Data Segment Stores global and static variables.
Heap Stores dynamically allocated memory.
Stack Stores local variables and function calls.

Common Errors in C Programming

Error Description
Syntax Error Wrong grammar in code.
Runtime Error Error occurs while executing the program.
Logical Error Program executes but produces incorrect output.
Linker Error Required library or function is missing.

Best Practices for Beginners

  • Use meaningful variable names.
  • Write comments only where necessary.
  • Indent code properly.
  • Always initialize variables.
  • Free dynamically allocated memory.
  • Avoid global variables unless required.
  • Break large programs into functions.
  • Practice writing small programs every day.

Mini Programs to Practice

  • Hello World
  • Calculator
  • Even or Odd Number
  • Prime Number
  • Palindrome Number
  • Factorial
  • Fibonacci Series
  • Armstrong Number
  • Reverse a Number
  • Swap Two Numbers
  • Linear Search
  • Binary Search
  • Bubble Sort
  • Matrix Addition
  • Matrix Multiplication
  • String Reverse
  • File Copy Program
  • Student Record Management

15. Preprocessor Directives and Macros in C Programming

What is a Preprocessor?

The C preprocessor is a program that processes the source code before the actual compilation starts. The preprocessor performs tasks like including header files, creating macros, conditional compilation and removing comments.

How Does C Compilation Work?

A C program goes through multiple stages before becoming an executable file.

Stage Description
Preprocessing Processes directives like #include and #define.
Compilation Converts C code into assembly code.
Assembly Converts assembly code into object code.
Linking Combines object files and libraries.

Types of Preprocessor Directives

  • File Inclusion Directives
  • Macro Definition Directives
  • Conditional Compilation Directives
  • Other Control Directives

1. File Inclusion Directive (#include)

The #include directive is used to include header files into a program. Header files contain predefined functions and declarations.

#include <stdio.h> int main() { printf("Hello C"); return 0; }
Output:
Hello C

Here, stdio.h contains functions like printf() and scanf().

Types of Header File Inclusion

Syntax Usage
#include <filename.h> Used for standard library header files.
#include "filename.h" Used for user-created header files.

2. Macro Definition (#define)

A macro is a name given to a piece of code. During preprocessing, the compiler replaces the macro name with its value.

Example: Simple Macro

#include <stdio.h> #define PI 3.14159 int main() { float area; area = PI * 5 * 5; printf("%f", area); return 0; }
Output:
78.539750

Types of Macros

1. Object Like Macro

#define VALUE 100 printf("%d", VALUE);

2. Function Like Macro

A macro can also accept arguments like a function.

#define SQUARE(x) (x*x) int result = SQUARE(5);
Output:
25
Important Interview Point: Macros are replaced before compilation, while functions are executed during runtime.

3. Conditional Compilation

Conditional compilation allows programmers to compile specific parts of code depending on conditions.

#if, #ifdef, #ifndef, #else, #endif

#include <stdio.h> #define DEBUG int main() { #ifdef DEBUG printf("Debug mode enabled"); #endif return 0; }
Output:
Debug mode enabled

4. Common Preprocessor Directives

Directive Purpose
#define Creates macros.
#undef Removes a macro definition.
#ifdef Checks whether macro exists.
#ifndef Checks whether macro does not exist.
#pragma Provides compiler-specific instructions.

Advantages of Macros

  • Improves code readability.
  • Reduces repeated code.
  • Provides faster execution compared to function calls.
  • Useful for conditional compilation.

Disadvantages of Macros

  • No type checking is performed.
  • Debugging becomes difficult.
  • Large macros can increase program size.
  • Operator precedence mistakes can occur.

Interview Questions

Q1. What is the difference between macro and function?

Macro:
- Expanded during preprocessing.
- No type checking.
- Faster execution.

Function:
- Executed during runtime.
- Supports type checking.
- Uses memory for function calls.

Q2. Why do we use #ifndef?

It prevents multiple inclusion of the same header file.

16. Storage Classes and Memory Layout in C Programming

What are Storage Classes?

Storage classes define the scope (visibility), lifetime, default value, and memory location of variables in a C program.

In simple words, storage classes tell the compiler:
  • Where a variable is stored.
  • How long the variable exists.
  • Where the variable can be accessed.

Types of Storage Classes in C

Storage Class Keyword Storage Location Lifetime
Automatic auto Stack Memory Until block execution completes
Register register CPU Register (if available) Until block execution completes
Static static Data Segment Entire program execution
External extern Global Memory Entire program execution

1. Automatic Storage Class (auto)

Automatic variables are local variables created inside a function or block. They are automatically created when execution enters the block and destroyed when execution leaves the block.

#include <stdio.h> int main() { auto int a = 10; printf("%d", a); return 0; }
Output:
10
Note: The keyword auto is rarely written because local variables are automatic by default. Example:

int x = 5;
is same as:
auto int x = 5;

2. Register Storage Class

Register variables are stored inside CPU registers instead of RAM whenever possible. They are used when fast access is required.

#include <stdio.h> int main() { register int count; for(count=0; count<5; count++) { printf("%d ",count); } return 0; }
Output:
0 1 2 3 4
Important: We cannot use the address operator (&) with register variables because registers do not have normal memory addresses. Example:

register int a;
&a; // Invalid

3. Static Storage Class

A static variable preserves its value throughout the entire program execution. Unlike normal local variables, static variables are initialized only once.

#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
Why did this happen?

Because the static variable keeps its previous value after the function ends.

4. External Storage Class (extern)

The extern keyword is used to access global variables declared in another file or another location.

#include <stdio.h> int value = 100; int main() { extern int value; printf("%d",value); return 0; }
Output:
100

Memory Layout of a C Program

When a C program runs, memory is divided into different sections. Each section has a specific purpose.
Memory Section Purpose
Code Segment Stores executable instructions of the program.
Read Only Data Stores constant values and string literals.
Data Segment Stores initialized global and static variables.
BSS Segment Stores uninitialized global and static variables.
Heap Stores dynamically allocated memory.
Stack Stores local variables and function calls.

Simple Memory Diagram

High Memory Address -------------------- Stack -------------------- Heap -------------------- BSS Segment -------------------- Data Segment -------------------- Code Segment -------------------- Low Memory Address

Stack vs Heap

Stack Heap
Automatically managed memory Manually managed memory
Faster access Slower compared to stack
Stores local variables Stores dynamic memory
Limited size Larger memory area

Common Interview Questions

Q1. What is the default storage class of local variables?

Answer: auto


Q2. Which storage class retains value between function calls?

Answer: static


Q3. Where are dynamically allocated variables stored?

Answer: Heap memory


Q4. Difference between static and global variables?

A global variable can be accessed from other files using extern, while a static global variable is restricted to the same file.

17. Command Line Arguments and Error Handling in C Programming

What are Command Line Arguments?

Command line arguments allow users to pass values to a C program while executing it from the command line. Instead of taking input after program execution starts, values can be provided during program execution itself.

Syntax of main() Function with Command Line Arguments

int main(int argc, char *argv[]) { // program statements }
Argument Meaning
argc Argument count. It stores the number of arguments passed.
argv Argument vector. It stores the actual arguments as strings.

Example: Printing Command Line Arguments

#include <stdio.h> int main(int argc, char *argv[]) { int i; for(i=0; i<argc; i++) { printf("%s\n", argv[i]); } return 0; }

Suppose we execute the program like this:

program hello 2026
Output:
program
hello
2026
Remember: The first argument (argv[0]) always contains the program name.

Example: Addition Using Command Line Arguments

#include <stdio.h> #include <stdlib.h> int main(int argc,char *argv[]) { int a,b,sum; a = atoi(argv[1]); b = atoi(argv[2]); sum = a+b; printf("Sum = %d",sum); return 0; }

Execution:

program 10 20
Output:
Sum = 30
atoi() Function:

atoi() converts a string value into an integer value. Example:

"100" → 100

Error Handling in C Programming

Errors are unwanted situations that occur during program execution. Proper error handling helps programs handle failures safely.

Types of Errors in C

Error Type Description
Syntax Error Mistakes in program grammar detected by compiler.
Runtime Error Errors occurring while program is running.
Logical Error Program runs but gives incorrect output.

Common Runtime Errors

  • Division by zero
  • Invalid memory access
  • File opening failure
  • Memory allocation failure
  • Invalid input data

Using exit() Function

The exit() function terminates program execution immediately.

#include <stdio.h> #include <stdlib.h> int main() { printf("Program started"); exit(0); printf("This will not execute"); return 0; }
Output:
Program started
exit Value Meaning
exit(0) Successful program termination.
exit(1) Program terminated due to error.

errno in C

The errno variable stores error codes generated by library functions.

#include <stdio.h> #include <errno.h> int main() { FILE *fp; fp=fopen("data.txt","r"); if(fp==NULL) { printf("Error number: %d",errno); } return 0; }

perror() Function

perror() displays a meaningful error message related to the last error.

#include <stdio.h> int main() { FILE *fp; fp=fopen("abc.txt","r"); if(fp==NULL) { perror("File Error"); } return 0; }
Example Output:
File Error: No such file or directory

Best Error Handling Practices

  • Always check return values of functions.
  • Handle file opening failures.
  • Validate user input.
  • Free dynamically allocated memory.
  • Use meaningful error messages.
  • Avoid ignoring compiler warnings.

Interview Questions

Q1. What is argc in C?

argc stores the number of command line arguments.


Q2. What is argv?

argv is an array of strings containing command line arguments.


Q3. Difference between exit() and return?

return exits from the current function, while exit() terminates the entire program.


Q4. Which header file contains errno?

errno.h

18. Standard Library Functions in C Programming

What are Standard Library Functions?

Standard library functions are predefined functions provided by the C language. These functions help programmers perform common tasks without writing code from scratch.

These functions are declared inside header files and can be used by including the required header file.

Common C Standard Library Header Files

Header File Purpose
stdio.h Input and output operations.
stdlib.h Memory allocation, conversions, program control.
string.h String handling functions.
math.h Mathematical operations.
ctype.h Character testing and conversion.
time.h Date and time operations.
stdbool.h Boolean data type support.

1. Input and Output Functions (stdio.h)

printf()

printf() is used to display output on the screen.

#include <stdio.h> int main() { printf("Welcome to C Programming"); return 0; }
Output:
Welcome to C Programming

scanf()

scanf() is used to take input from the user.

int age; scanf("%d",&age);

Other stdio.h Functions

  • getchar() - Reads a single character.
  • putchar() - Prints a single character.
  • fgets() - Reads a string safely.
  • puts() - Displays a string.
  • fopen() - Opens a file.
  • fclose() - Closes a file.
  • fprintf() - Writes formatted data to a file.
  • fscanf() - Reads formatted data from a file.

2. String Functions (string.h)

Strings in C are arrays of characters ending with a null character '\0'. The string.h header provides functions to manipulate strings.

strlen()

Returns the length of a string.

#include <stdio.h> #include <string.h> int main() { char name[]="Programming"; printf("%lu",strlen(name)); return 0; }
Output:
11

strcpy()

Copies one string into another string.

char source[]="C Language"; char destination[20]; strcpy(destination,source);

strcat()

Combines two strings.

strcat(first,second);

strcmp()

Compares two strings.

strcmp("abc","abc");

Important String Functions

Function Purpose
strlen() Find string length.
strcpy() Copy strings.
strcat() Join strings.
strcmp() Compare strings.
strchr() Search character.
strstr() Search substring.

3. Mathematical Functions (math.h)

math.h provides functions for mathematical calculations.

Function Purpose
sqrt() Square root.
pow() Power calculation.
ceil() Rounds value upward.
floor() Rounds value downward.
abs() Absolute value.
sin() Sine value.
cos() Cosine value.
#include <stdio.h> #include <math.h> int main() { printf("%.2f",sqrt(25)); return 0; }
Output:
5.00

4. Memory Functions (stdlib.h and string.h)

Memory functions are used for handling memory blocks.

Function Purpose
malloc() Allocates memory dynamically.
calloc() Allocates and initializes memory.
realloc() Changes allocated memory size.
free() Releases allocated memory.
memcpy() Copies memory blocks.
memset() Sets memory with a value.

5. Character Functions (ctype.h)

Function Purpose
isalpha() Checks alphabet character.
isdigit() Checks digit.
islower() Checks lowercase character.
isupper() Checks uppercase character.
tolower() Converts to lowercase.
toupper() Converts to uppercase.

6. Time Functions (time.h)

Function Purpose
time() Returns current time.
clock() Returns processor time.
difftime() Finds difference between times.

Interview Questions

Q1. Why are header files used in C?

Header files provide declarations of predefined functions.


Q2. Difference between strlen() and sizeof()?

strlen() returns the number of characters in a string. sizeof() returns the memory size occupied by a variable.


Q3. Which function allocates dynamic memory?

malloc()


Q4. Which header file contains string functions?

string.h

19. C Programming Best Practices, Common Mistakes and Interview Preparation

Why Learn Best Practices?

Writing a program that works is important, but writing clean, secure, readable and maintainable code is what makes a programmer professional. Good programming habits help in projects, teamwork and technical interviews.

Best Practices in C Programming

1. Use Meaningful Variable Names

Variable names should describe their purpose. Avoid using confusing names.

// Bad practice int x; // Good practice int studentAge;

2. Write Proper Comments

Comments explain why a particular piece of code exists.

// Calculate total marks total = math + science + english;
Do not write comments for obvious code. Example: // increment i i++; is unnecessary.

3. Always Initialize Variables

// Avoid int number; // Better int number = 0;

Uninitialized variables may contain garbage values.

4. Check Return Values

FILE *file; file=fopen("data.txt","r"); if(file==NULL) { printf("File opening failed"); }

Always check whether functions execute successfully.

5. Avoid Hard Coding Values

// Bad area = 3.14 * r * r; // Better #define PI 3.14159 area = PI * r * r;

6. Use Proper Indentation

Proper formatting improves readability and debugging.

if(age >= 18) { printf("Eligible"); } else { printf("Not Eligible"); }

Common Mistakes in C Programming

Mistake Problem
Missing semicolon Compilation error.
Using uninitialized variables Unexpected output.
Array index out of bounds Memory corruption.
Forgetting free() Memory leak.
Wrong pointer usage Runtime crash.
Using gets() Security vulnerability.

Important C Programming Interview Questions

1. What is C language?

C is a procedural, general-purpose programming language used for system programming, embedded systems and application development.


2. Difference between compiler and interpreter?

Compiler converts the entire program at once. Interpreter executes code line by line.


3. What is a pointer?

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


4. Difference between array and pointer?

Array stores multiple values of the same type. Pointer stores a memory address.


5. What is NULL pointer?

A pointer that does not point to any valid memory location.


6. Difference between malloc() and calloc()?

malloc() allocates memory without initialization. calloc() allocates memory and initializes it to zero.


7. What is recursion?

A function calling itself is called recursion.

Frequently Asked C Programming Programs

Practice these programs to improve programming logic.
  • Hello World Program
  • Addition of Two Numbers
  • Finding Even or Odd Number
  • Finding Largest Among Three Numbers
  • Calculator Using Switch Statement
  • Factorial Program
  • Fibonacci Series
  • Prime Number Checking
  • Palindrome Number
  • Reverse a Number
  • Armstrong Number
  • Swap Two Numbers
  • Sorting an Array
  • Searching an Element in Array
  • Matrix Addition
  • Matrix Multiplication
  • String Length Without strlen()
  • String Reverse Without Library Function
  • Counting Vowels in String
  • File Reading and Writing Program
  • Student Management System
  • Bank Management System

C Programming Learning Roadmap

Level Topics
Beginner Syntax, Variables, Data Types, Operators, Conditions, Loops
Intermediate Functions, Arrays, Strings, Pointers, Structures
Advanced Memory Management, File Handling, Preprocessor, Libraries
Professional Projects, Optimization, Debugging, System Programming

Final Tips for Learning C Programming

  • Practice coding every day.
  • Understand concepts instead of memorizing syntax.
  • Debug your own programs.
  • Read other programmers' code.
  • Build small projects.
  • Master pointers and memory management.
  • Solve programming problems regularly.
Congratulations 🎉

You have completed the complete C Programming 2026 learning roadmap. Continue practicing and building projects to become confident in C programming.

Frequently Asked Questions (FAQ)

Is C programming difficult for beginners?

No. C becomes easy when concepts are learned step by step with practice.

How long does it take to learn C?

A beginner can understand the basics within a few weeks with regular practice. Advanced concepts require continuous coding experience.

Is C still useful in 2026?

Yes. C is still widely used in operating systems, embedded systems, compilers, networking and performance-critical applications.

Should I learn C before C++ or Java?

Learning C first provides a strong foundation because it teaches memory, logic and low-level programming concepts.

Complete C Programming Roadmap

  1. Introduction to C
  2. History of C
  3. Program Structure
  4. Tokens
  5. Keywords
  6. Identifiers
  7. Variables
  8. Data Types
  9. Operators
  10. Input & Output
  11. Type Conversion
  12. Control Statements
  13. Loops
  14. Arrays
  15. Strings
  16. Functions
  17. Recursion
  18. Pointers
  19. Storage Classes
  20. Structures
  21. Unions
  22. Enumerations
  23. Typedef
  24. Dynamic Memory Allocation
  25. File Handling
  26. Command Line Arguments
  27. Preprocessor Directives
  28. Bitwise Operators
  29. Error Handling
  30. Practice Programs
If you understand every topic on this page and practice the example programs, you'll have a strong foundation in C programming. From here, you can confidently move on to Data Structures, Operating Systems, Embedded Systems, C++, or Competitive Programming.

Comments

Popular posts from this blog

JNTUK R16 SGPA and CGPA calculator for Lateral entry b.tech

Lateral entry students those are joined directly engineering by completing polytechnic, they may or may not appeared for ECET for getting seat in engineering course. that is B.Tech students studied course in 4 years but lateral entry students studied course is 3 years, that one year spend in polytechnic course. Lateral entry students strong in Technically than regular students. for SGPA calculator -   click here NOTE: IF ANYONE WANT CALCULATE UPTO SOME SEMISTERS(LIKE UPTO 3-2) FOR PLACEMENTS CAN PROVIDE REMAINING SGPAS AND TOTAL CREDITS AS ZEROS(0) THEN WILL GET ACCURATE CGPA TILL THAT PARTICULAR SEMISTER. FOR LATERAL ENTRY SCHEME B.TECH CGPA IS... FIRST SEMISTER SGPA    total credits   SECOND SEMISTER SGPA    total credits   THIRD SEMISTER SGPA    total credits   FOURTH SEMISTER SGPA    total credits  ...

JNTUK Convocation VIII for 2018-19 and 2019-20 batch OD apply

JNTUK Convocation VIII for 2018-19 and 2019-20 batch, who have taken the PC in the period of 01/01/2019 to 31/12/2020 For more details Click here last Date to apply - 18-12-2021 Required Documents: 1. PC 2. CMM (For UG ) 3. SSC 4. Recent Photo  5. For PG courses - Sem wise mark sheets 6. Adhaar front and back scanned copy 7. Bank challan or Payment - Those made offline payment should submit hard copies of above documents at the university examination Fee - Rs.2000/- Process to apply: 1. Register with Hall ticket number and email Id(user name) - Click here 2. Login with user name(E-mail ID) and password - click here 3. Enter the details and next step will be payment  Note: Updation of payment status into complete status may take 2-3 days 4. Then need to attach the required documents 5. Next step is to check the details and everything and then click on check box by agreeing that there information was furnished by you is true. 6. There will be no Submit option that is only downlo...

JNTUK R16, R19 SGPA CALCULATOR

JNTUK R16, R19 SGPA calculator, it is calculated as the sum of multiple of grade point with credit and then division with sum of credits to that semister. SGPA gives the marks in points out of 10 in the particular semister. Grade - Grade points 1. O - 10 2. S - 9 3. A - 8 4. B - 7 5. C - 6 6. D - 5 7. F - FAIL NOTE: IF ANY SEMISTER HAVE LESS THAN 9 SUBJECTS THEN PLACE ZEROS REMAINING BOXES IN GARDE POINT AS WELL AS CREDT BOX PLACE ZEROS. ACCURATE SGPA WILL COME. CALCULATE SGPA : FIRST SUBJECT Grade points    Credits   SECOND SUBJECT Grade points    credits   THIRD SUBJECT Grade points     credits   FOURTH SUBJECT Grade points    credits   FIFTH SUBJECT Grade points    credits   SIXTH SUBJECT Grade points    credits   SEVENTH SUBJECT Grade points     c...