Despite the emergence of newer languages, C programming will remain significant in 2025 and beyond due to its special skills in low-level programming and performance-critical applications. Gaining knowledge of C gives doors to a variety of specialized and in-demand areas such as IoT, while also providing a solid foundation in computer science principles. Go through this experiment-based C programming tutorial for beginners and get started with our C Programming Course Syllabus.
Introduction to C Language
C is a popular choice for programming microcontrollers and embedded systems that drive industrial automation, automotive systems, medical equipment, and Internet of Things devices. In this introduction to C language, you will also learn through some C programming language projects.
What is C Programming Language?
One of the most popular and potent procedural programming languages is C. It was created by Dennis Ritchie at Bell Laboratories in the early 1970s, and it has had a significant influence on computer science. The following are some essential traits:
- Procedural: C is concerned with decomposing a program into a series of actions or operations.
- Mid-level: It serves as a link between high-level (more abstract) and low-level (machine code) languages. This makes it possible to design applications and program systems efficiently.
- Compiled: Before C code can be run, it must be compiled into machine code.
- Portable: C programs frequently require little modification to build and execute on various operating systems.
- Powerful: As C has low-level memory manipulation capabilities, it can be used for jobs like embedded devices, operating system development, and applications that require high performance.
Why Learn C Even in the 21st Century?
C is still relevant even after all this time for a number of reasons:
- Foundation for other languages: C provides the syntax and ideas for several other well-known languages, including C++, Java, Python, and C#. These languages can be easier to learn if you understand C.
- System programming: C is the preferred language for creating embedded systems, device drivers, and operating systems (such as Unix and Linux) that require direct hardware contact.
- Performance: Because C enables fine-grained control over memory and system resources, it frequently produces programs that are incredibly quick and efficient.
- Understanding computer architecture: Working with C can help you gain a deeper understanding of the lower-level operations of computers.
Basic Structure of a C Program
A simple C program typically looks like this:
#include <stdio.h>
int main() {
printf(“Hello, World!\n”);
return 0;
}
Code Explanation:
#include <stdio.h>: This is a preprocessor directive. It instructs the standard input/output library (stdio.h) to be included by the compiler. Functions like printf (for printing output to the console) are included in this library.
int main() {… }: This is the primary purpose. This is where a C program starts to run.
- int: Indicates that the operating system will get an integer value from the main function.
- main: The function’s name.
- (): Shows that main is a function that may accept arguments, albeit in this straightforward example it doesn’t.
- {… }: The body of the main function, which contains the instructions to be carried out, is enclosed by curly braces.
printf(“Hello, World!\n”);: This is a statement.
- printf: The stdio.h library’s function for printing formatted output.
- “Hello, World!\n”: Printing “Hello, World!” is the string literal. A newline character is represented by the escape sequence \n.
- ;: In C, a semicolon must come at the end of each statement.
return 0;: The main function has successfully run, according to this sentence. Usually, success is indicated with a return value of 0.
Compilation and Execution Process in C
Source Code → Preprocessor → Compiler → Assembler → Linker → Executable.
- Preprocessing: Your source code is altered by the preprocessor (which is guided by lines that begin with #) (e.g., includes header files, substitutes macros).
- Compilation: The preprocessed code is converted into assembly language by the compiler.
- Assembly: The assembly language is transformed into object code (machine code that isn’t yet fully linked) by the assembler.
- Linking: To produce the final executable file, the linker integrates your object code with any required library code.
- Execution: The executable file is loaded and run by the operating system.
Suggested: C Programming Online Course.
Data Types, Variables, and Operators in C
Let’s explore C’s operators, variables, and data types. These are essential components needed to write any C program.
Data Types in C
A variable’s data types define the types of values it can hold. Some of the basic data types in C are as follows:
Data Type | Description | Typical Size (bytes) | Range (typical) | Format Specifier (for printf/scanf) |
int | Integer (whole numbers) | 4 | -2 billion to +2 billion ~ | %d |
float | Single-precision floating-point numbers | 4 | pm1.4times10−45 to pm3.4times1038 ~ | %f |
double | Double-precision floating-point numbers | 8 | ~ pm4.9times10−324 to pm1.8times10308 | %lf |
char | Single character | 1 | Typically -128 to 127 or 0 to 255 (ASCII) | %c |
void | Represents the absence of a type or no value | – | N/A | N/A |
Modifiers: The following qualifiers can be used to change some of the fundamental data types:
- signed: Capable of storing both positive and negative numbers (char and int are the default values).
- unsigned: Only non-negative values can be stored.
- short: It decreases the storage space allotted to an int.
- long: Doubles or expands the storage space allotted to an int.
Example:
- unsigned int age; – will only hold integers that are not negative
- long int count; – may store a wider range of integers than a typical int
- long double pi; – offers much greater accuracy than a standard double
Variables in C
A specified storage space in the computer’s memory that contains a value of a certain data type is called a variable.
Declaration: A variable must be declared before it may be used. This entails defining its name and data type.
int age;
float price;
char initial;
Initialization: By allocating an initial value at the time of declaration, you can also initialize a variable.
int count = 0;
float pi = 3.14159;
char grade = ‘A’;
Naming Variables: In C, variables must follow certain guidelines.
- Letters (a-z, A-Z), numbers (0-9), and the underscore character (_) can all be found in a variable name.
- Either a letter or an underscore must be the first character.
- Age and Age are two distinct variables, and variable names are case-sensitive.
- It is not possible to utilize reserved words (such as int, float, if, for, etc.) as variable names.
Operators in C
Symbols known as operators apply operations to operands, which are variables and values. C offers a wide variety of operators. These are a few typical categories:
Arithmetic Operators:
Operator | Description | Example |
+ | Addition | a + b |
– | Subtraction | a – b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus (remainder) | a % b |
++ | Increment | i++ (post), ++i (pre) |
— | Decrement | j– (post), –j (pre) |
Assignment Operators:
Operator | Description | Example | Equivalent to |
= | Simple assignment | a = 10; | |
+= | Add and assign | a += 5; | a = a + 5; |
-= | Subtract and assign | a -= 3; | a = a – 3; |
*= | Multiply and assign | a *= 2; | a = a * 2; |
/= | Divide and assign | a /= 4; | a = a / 4; |
%= | Modulus and assign | a %= 3; | a = a % 3; |
Comparison Operators:
Operator | Description | Example | Result |
== | Equal to | a == b | 1 (true) or 0 (false) |
!= | Not equal to | a != b | 1 or 0 |
> | Greater than | a > b | 1 or 0 |
< | Less than | a < b | 1 or 0 |
>= | Greater than or equal to | a >= b | 1 or 0 |
<= | Less than or equal to | a <= b | 1 or 0 |
Logical Operators:
Operator | Description | Example | Result (1 for true, 0 for false) |
&& | Logical AND | (a > 0) && (b < 10) | True only if both conditions are true |
` | ` | Logical OR | `(a == 0) |
! | Logical NOT | !(a == b) | True if a is not equal to b |
This provides you with a basic understanding of variables, operations, and data types in C.
Related: Java Programming Training in Chennai.
Input and Output in C
Let’s discuss C’s input and output, or I/O. Functions for communicating with the user (input) and presenting results (output) are available in the standard C library (stdio.h).
Standard Output: printf()
The main method for displaying output to the console (standard output) is to use the printf() function. You can print prepared text, including variable values, with it.
printf(“format string”, argument1, argument2, …);
- format string: A string with optional format specifiers and text to be printed.
- arguments: Values or variables that you wish to add to the format string.
Common Format Specifiers:
Specifier | Output | Example |
%d | Signed decimal integer | printf(“%d”, age); |
%f | Floating-point number (decimal notation) | printf(“%f”, price); |
%lf | Double-precision floating-point number | printf(“%lf”, pi); |
%c | Single character | printf(“%c”, initial); |
%s | String (null-terminated character array) | printf(“%s”, name); |
%% | Prints a literal percent sign (%) | printf(“Discount: %d%%”, discount); |
\n | Newline character | printf(“Hello\nWorld”); |
Standard Input: scanf()
To read formatted input from the user (typical input, typically the keyboard), the scanf() function is frequently utilized.
scanf(“format string”, &variable1, &variable2, …);
- format string: It has format specifiers that specify the kind of input that will be read, just like printf().
- &variable: The address-of operator (&) is essential. It gives scanf() the variable’s memory address where the input value ought to be kept.
Common Format Specifiers (for scanf()):
Specifier | Expected Input | Argument Type (must use &) |
%d | Integer | int * |
%f | Floating-point number | float * |
%lf | Double-precision float | double * |
%c | Single character | char * |
%s | String (up to whitespace) | char array (no & needed) |
Important Notes for scanf():
- With the exception of reading strings into a character array, all format specifiers require the & operator to come before the variable name.
- When scanf() comes across whitespace (space, tab, newline) or a character that doesn’t fit the intended format, it stops processing input for the specified format specifier.
- Verifying the return value of scanf(), which shows how many items were properly read, is best practice.
Other I/O Functions:
- getchar(): It reads a single character from standard input.
- putchar(): It writes a single character to standard output.
- gets(): It reads a line from standard input into a string (generally discouraged due to potential buffer overflows).
- fgets(): It reads a line from standard input into a string with a specified buffer size (safer than gets()).
- sprintf(): It writes formatted output to a string.
- sscanf(): It reads formatted input from a string.
Recommended: Embedded Training in Chennai.
Control Flow in C Programming
Let’s explore C’s Control Flow. You can specify the sequence in which the statements in your program are performed by using control flow statements. This is crucial for developing programs with decision-making and action-repetition capabilities.
Two main categories of control flow statements exist:
- Conditional Statements: With conditional statements, you can run distinct code sections according to whether a certain condition is true or not.
- Looping Statements: They let you run a block of code repeatedly until a predetermined condition is satisfied.
Conditional Statement:
if statement: If a certain condition is true, the if statement runs a block of code.
if (condition) {
// Code to be executed if the condition is true
}
if-else statement: If the condition is true, the if-else statement runs one piece of code; if it is false, it runs another chunk of code.
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
switch statement: Depending on the value of an expression, you may use the switch statement to choose which of multiple code blocks to run.
switch (expression) {
case constant1:
break;
case constant2:
break;
default:
}
Looping Statements
You can run a section of code repeatedly by using looping statements.
for loop: When you know ahead of time how many times you want to iterate, you’ll frequently utilize the for loop.
for (initialization; condition; increment/decrement) {
// Code to be executed repeatedly
}
while loop: As long as a given condition is true, the while loop keeps running a block of code. Before every repetition, the condition is examined.
while (condition) {
// Code to be executed while the condition is true
}
do-while loop: Similar to the while loop, the do-while loop checks the condition at the end of each iteration. This ensures that the body of the loop will run at least once.
do {
// Code to be executed
} while (condition);
break and continue statements
- break: Instantaneously ends the switch statement or the innermost loop (for, while, or do-while).
- continue: Moves on to the following iteration of a loop, skipping the remainder of the current one.
The creation of logic in your C applications requires the use of these control flow statements.
Recommended: IoT Course in Chennai.
Functions in C
Self-contained chunks of code that carry out a particular purpose are called functions. They enable you to:
- Organize your code: Divide complicated programs into smaller, more manageable components.
- Reuse code: Make repeated calls to the same function without changing the code.
return_type function_name(parameter1_type parameter1_name, parameter2_type parameter2_name, …) {
// Function body: code that performs the task
// Optional: return a value using the ‘return’ statement
}
- return_type: The value’s data type, which may be void if the function returns nothing.
- function_name: The function’s callable identifier.
- parameters: Optional input values given to the function. Every parameter is named and has a type.
- function body: The statements that are carried out when the function is invoked are known as the function body.
- return statement: If the return type is not void, this statement is used to return a value to the caller from the function.
Arrays in C
A fixed-size sequential collection of elements of the same data type is stored in arrays. Imagine it as a row of boxes, each of which is capable of storing a value of the same kind.
data_type array_name[size];
- data_type: The kind of elements (char, float, or int) that the array will contain.
- array_name: The reference to the array that you will utilize.
- size: How many items the array can hold. This integer must be constant.
Example:
int numbers[5] = {10, 20, 30, 40, 50};
char vowels[5] = {‘a’, ‘e’, ‘i’, ‘o’, ‘u’};
Pointers in C
A variable that holds the memory address of another variable is called a pointer. It “points to” the place in memory where a value is stored rather than actually retaining the data.
Declaration of Pointers:
int *ptr_to_int; // Declares a pointer that can store the address of an integer variable
float *ptr_to_float; // Declares a pointer that can store the address of a float variable
char *ptr_to_char; // Declares a pointer that can store the address of a character variable
Strings in C
A string in C is just a null-terminated array of characters. The special character \0 (ASCII value 0) that indicates the end of a string is known as the null terminator.
char message[20];
char greeting[] = “Hello”;
char name[6] = {‘J’, ‘o’, ‘h’, ‘n’, ‘\0’};
Functions from string.h are frequently used to work with strings, which are character arrays in C that are terminated by a null character.
Related: CompTIA N+ Training in Chennai.
Structures and Unions in C
Structures: They are user-defined data types that allow variables of various data kinds to be grouped together under a common name. Consider using them to build your own composite data types.
- Key word: struct
- Memory: Every member of a structure is allotted a certain amount of memory. Although padding may occur, a structure’s overall size is typically the sum of the sizes of its parts.
- Use: Displaying documents and multi-attribute objects.
struct Point {
int x;
int y;
};
struct Person {
char name[50];
int age;
float height;
};
Unions: Although only one member can carry a value at a time, unions are user-defined data types that can hold variables of various data types.
- Key word: union
- Memory: A union’s memory location is shared by all of its members. The size of the union’s largest member determines the union’s size.
- Use: When you need to conserve space by storing several kinds of data in the same memory region at different periods.
union Data {
int i;
float f;
char str[20];
};
File Handling in C
Your C applications can read and write data to and from files on your system thanks to file handling.
Opening a File: You need to open a file before you can read from or write to it. The fopen() method is used for this.
FILE *fptr;
fptr = fopen(“filename.txt”, “mode”);
- fptr: A file pointer that will direct the user to the opened file (of type FILE*).
- “filename.txt”: The file name that you wish to access.
- “mode”: A string that indicates how you would like the file to be opened (for example, “r” for read, “w” for write, and “a” for append).
Reading or Writing: After opening the file, you can utilize features such as
- fprintf(fptr, “format string”, …): Writes formatted output to the file (similar to printf).
- fscanf(fptr, “format string”, …): Reads formatted input from the file (similar to scanf).
- fgetc(fptr): Reads a single character from the file.
- fputc(char, fptr): Writes a single character to the file.
- fgets(str, n, fptr): Reads at most n-1 characters from the file into the string str.
- fputs(str, fptr): Writes a string to the file.
Closing the File: Use fclose() to close a file once you’re finished working with it. As a result, the file’s resources are released.
fclose(fptr);
Recommended: Hardware and Networking Course in Chennai.
Advanced C Programming Concepts
Dynamic Memory Allocation in C: Dynamic memory allocation allows you to allocate memory during the runtime of your program, as opposed to static allocation where the size is fixed at compile time. This is useful when you don’t know beforehand how much memory you’ll need.
- malloc(size): Distributes a block of uninitialized memory of size bytes.
- calloc(nitems, size) function: Memory is allocated for an array of nitems elements, each of size bytes.
- realloc(): A previously allocated block of memory pointed to by ptr is resized to new_size bytes.
- free(ptr): Deallocates the memory block that was previously allocated by realloc, calloc, or malloc and that is pointed to by ptr.
Preprocessor Directives in C: Instructions that start with the hash symbol (#) are known as preprocessor directives, and the preprocessor processes them before your C code is really compiled. There is no semicolon at the conclusion of them.
- #include: Contains information from another file, usually a header file containing declarations.
- #define: Defines a macro or symbolic constant.
- Conditional Compilation: You can conditionally build sections of your code depending on whether specific criteria are met by using conditional compilation (#if, #ifdef, #ifndef, #else, #elif, and #endif).
- #undef: Reverses a macro that has already been defined.
Introduction to Data Structures in C
Data structures are methods for effectively arranging and storing data so that it may be accessed and modified. Your programs’ performance can be greatly impacted by the data structure you choose.
Common Basic Data Structures (often implemented in C):
- Arrays are a contiguous, ordered grouping of identically typed elements. Index-based element access is quick (O(1)). Typically, size is set.
- Linked lists are collections of nodes, or items, where each node has a pointer to the node after it as well as data. Accessing an element by index can be slower (O(n)), but dynamic size makes insertion and deletion simpler than arrays (O(1) if you have the reference).
- LIFO (Last-In, First-Out) data structures are used in stacks. Push (adding) and pop (removing) are examples of operations that take place at the “top.”
- FIFO (First-In, First-Out) data structures are used in queues. Additions are made to the “rear” while deletions are made to the “front.”
- Trees are a type of hierarchical data structure made up of nodes with edges connecting them. Binary trees and binary search trees are two examples. In many situations, it is effective for insertion, deletion, and searching.
Suggested: All Software Training Courses.
Conclusion
This C programming tutorial for beginners is now complete. From basic grammar to more complex subjects like pointers and memory management, we have gone over the essential ideas. Keep in mind that the secret to retaining what you’ve learned is constant practice. Enroll in our C Programming training in Chennai.