Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is C Programming?
3.
Why Learn C?
4.
What are Constants and Variables?
4.1.
Constants in C
4.1.1.
Syntax to declare a constant in C:
4.2.
Variables in C:
4.2.1.
Syntax to declare a variable in C:
5.
Keywords and identifiers in C
5.1.
Keywords in C
5.2.
Identifiers in C
6.
Data Types and Initialization in C
6.1.
Data Types in C
6.2.
Initialization in C
7.
Comments and header files in C
7.1.
Comments in C
7.2.
Header Files in C
8.
The Basic Structure of the C program
8.1.
Components of a C Program
8.2.
Basic Structure of a C Program
8.3.
C
9.
Operators and Expressions in C Language
9.1.
Arithmetic Operators
9.2.
Relational Operators
9.3.
Logical Operators
9.4.
Bitwise Operators
9.5.
Assignment Operators
9.6.
Conditional Operator
9.7.
Precedence and Order of Evaluation
10.
Input and Output
10.1.
Step 1: Include Header Files
10.2.
Step 2: Declare Variables
10.3.
Step 3: Take User Input
10.4.
Step 4: Display Output
10.5.
C
11.
Statements in C
11.1.
Conditional Statements
11.2.
Loop Statements
11.3.
Jump Statements
12.
Pointers in C
12.1.
Declaring a Pointer:
12.2.
Assigning a Value to a Pointer:
12.3.
Accessing the Value of a Pointer:
12.4.
Pointer Arithmetic:
12.5.
Passing Pointers to Functions:
12.6.
C
13.
Functions in C
13.1.
Syntax of a Function:
13.2.
Declaring and Calling a Function:
13.3.
C
13.4.
Parameters in a Function:
13.5.
Types of Functions
14.
Arrays in C
14.1.
1D Array in C
14.2.
2D Array in C
15.
Memory Allocation
15.1.
Static Memory allocation
15.1.1.
Advantages of Static Memory allocation
15.1.2.
Disadvantages of Static Memory allocation
15.2.
Dynamic Memory allocation
15.2.1.
Advantages of Dynamic Memory allocation
15.2.2.
Disadvantages of Dynamic Memory allocation
16.
Struct
16.1.
C
17.
Union
17.1.
C
17.2.
Advantages of Union:
17.3.
Limitations of Union:
18.
Enumeration
18.1.
Using an Enumeration: 
18.2.
C
18.3.
Advantages of Enumeration:
19.
File Handling
19.1.
Buffers:
19.2.
Streams:
19.3.
Input/Output functions:
19.4.
Random Access Files:
20.
C Programs for Practice
21.
Advantages of C
22.
Disadvantages of C
23.
Frequently Asked Questions
23.1.
What are the applications of C programming?
23.2.
What C programming is used for?
23.3.
What is C vs C++ programming?
23.4.
What is data type in C?
24.
Conclusion
Last Updated: Aug 25, 2024
Easy

Introduction to C Programming

Author Sinki Kumari
6 upvotes

Introduction

C programming is a general-purpose programming language that was developed in the early 1970s by Dennis Ritchie at Bell Labs as a successor to the B programming language. Initially, C was used for developing the UNIX operating system, which is still widely used today. Over time, C has become a popular language for developing system-level software, embedded systems, and other applications. 

Introduction to C programming

C is a compiled language, which means that the source code is first compiled into machine code, which can then be executed directly by the computer. This makes C programs fast and efficient, which is one of the reasons it is still popular today.

C is also a low-level language, which means that it provides low-level access to the computer's hardware, such as memory management and system resources. This makes it a powerful language for writing system-level code and is why it is used to develop operating systems and other low-level applications.

Also see, Short int in C Programming

What is C Programming?

The C programming language is a procedural, general-purpose language that is independent of the operating system and facilitates structured programming. It also offers low-level access to the system memory. The C programming language was created by Dennis Ritchie in 1972 at AT&T (then known as Bell Laboratory), where it was used with the UNIX operating system on a DEC PDP II. Additionally, it was Ken Thompson's B programming language's successor. C was created to address the issues that BASIC, B, and BPCL programming languages had. C surpassed all other programming languages for mainframes, microcomputers, and minicomputers by 1980. 

Why Learn C?

The primary benefit of learning C over assembly is the ease and speed with which one can develop code for a particular programming task. Compared to writing it in assembly, using C will require significantly fewer lines of code, finish the task much faster, and require far less mental work. Additionally, executable files created using today's modern compilers will often execute faster than those created "by hand" using assembly language.

The portability of C is another great benefit. The instruction sets of different processors vary. It is a difficult task to have to rewrite and maintain assembly code for every computer architecture you desire to run your code on. As a result, one of C's key advantages is that it combines portability and universality across different computer architectures.

What are Constants and Variables?

C is a programming language that allows the use of constants and variables. Constants are values that cannot be changed during program execution, while variables are values that can be changed during program execution. Let's know more about them.

Constants and variables

Constants in C

Constants are values that are fixed and cannot be changed during program execution. In C, constants can be of different types, including integer, floating-point, and character constants. We use the “const” keyword to declare constants in C

There are two types of constants in C:

  • Numeric Constants: Numeric constants represent a fixed value and can be either integers or floating-point numbers.
     
  • Character Constants: Character constants represent a single character enclosed within single quotes (' ').
     

Syntax to declare a constant in C:

const data_type constant_name = value;

Variables in C:

Variables are values that can be changed during program execution. In C, variables can be of different types, including integers, floating-point numbers, characters, and arrays.

Syntax to declare a variable in C:

Variables in C are declared using a data type keyword, followed by the variable name.

data_type variable_name;

 

Variables in C can also be initialized with a value at the time of declaration. To assign value to a variable, we use the assignment operator (=).

 

data_type variable_name = value;

Keywords and identifiers in C

C is a programming language that uses keywords and identifiers. Keywords are reserved words that have a specific meaning and are used by the compiler to understand the structure of the program. Identifiers, on the other hand, are names given to variables, functions, and other program elements. Let's know more about them.

Keywords and identifiers

Keywords in C

Keywords are reserved words in C that have a specific meaning and cannot be used as identifiers. C has a set of predefined keywords, and these keywords are reserved for specific purposes in the program.

The following table contains some important and widely used keywords in C.

auto     

double  

int    

struct

break   

else    

long   

switch

case    

enum   

register  

typedef

char    

extern  

return 

union

const    

float   

short  

unsigned

continue 

for     

signed 

void

default  

goto   

sizeof

volatile

do      

if      

static 

while

Identifiers in C

Identifiers are names given to variables, functions, and other program elements.

We use letters, digits, and underscore (_) to compose identifiers.
 

Note: Identifiers must begin with either a letter or an underscore and cannot be a reserved keyword.
 

There are some standard rules to name an identifier. The rules are as follows,

  • Identifiers must begin with either a letter or an underscore (_)
     
  • Identifiers can contain letters, digits, and underscores (_)
     
  • Identifiers are case-sensitive
     
  • Identifiers cannot be a reserved keywords
     
  • Identifiers should be descriptive and meaningful
     

Example:

 int age;
float average_grade;
void print_student_info();

Data Types and Initialization in C

C is a programming language that supports different data types, which are used to specify the type of data that a variable can hold. Initialization is the process of assigning an initial value to a variable when it is declared. Let's know more about them.

Data Types in C

Data types in C specify the type of data that a variable can hold. C supports several data types, including integers, floating-point numbers, characters, and arrays. Here we have given a table of data types and their usage.

Datatype

Usage

int

Used to represent integers.

float

Used to represent floating-point numbers.

char

Used to represent characters.

double

Used to represent double-precision floating-point numbers.

long

Used to represent long integers.

short

Used to represent short integers.

unsigned

Used to represent positive integers.

void

Used to indicate no type.

Note: Each data type has a range of values that it can hold. For example, the int data type can hold values from -2147483648 to 2147483647.

Initialization in C

Initialization is the process of assigning an initial value to a variable when it is declared. We can do initialization in two ways. They are as follows,
 

  • Using an assignment operator:
     
int num=10;

 

Here, we initialized the num variable with a value of 10.

 

  • Using a compound literal:
     
int arr[3] = {1, 2, 3};

 

Here, we initialized the arr variable with three values using a compound literal.

Note: It is also possible to initialize variables with default values. When a variable is declared without an initial value, it is automatically initialized with a default value.

Comments and header files in C

C is a programming language that supports comments and header files. Comments are used to add information to a program, while header files are used to include external code in a program. Let's know more about them.

Comments in C

Comments in C are used to add information to a program that is not executed by the compiler. We use comments, 

  • to explain the purpose of the code, 
     
  • provide documentation, 
     
  • or disable parts of the code temporarily.

There are two types of comments in the C programming language. They are as follows,

  • Single-line comments:
     

Single-line comments start with two forward slashes (//) and extend to the end of the line. 

Let's see an example.

// This is a single-line comment

 

  • Multi-line comments:
     

Multi-line comments start with /* and end with */. They can span multiple lines.

Let's see an example.

/*
This is a
multi-line
comment
*/

 

Note: Comments are an important tool for programmers because they allow them to communicate with other developers and explain the purpose and functionality of the code.

Header Files in C

Header files in C are used to include external code in a program. They contain function prototypes, variable declarations, and other definitions that can be used in the program. 

To include a header file in a C program, we use the “#include” directive.

C provides several built-in header files, including stdio.h, math.h, and string.h. Lets see an example of a header file.

#include <stdio.h>

 
int main() {
    printf("Hello, world!");
    return 0;
}

 

Here is the stdio.h header file is included using the #include directive. This allows the program to use the “printf” function, which is defined in the “stdio.h” header file. In this way, to use predefined functions, we need to use header files as per our needs.

Note: You can also create your own header files and include them in your programs. This helps to reuse code and make programs more modular.

The Basic Structure of the C program

C is a programming language that follows a specific structure. A C program is made up of different components that work together to produce the desired output. C programing language also has a syntax to write code similar to other programming languages. Let's discuss it more.

Components of a C Program

We construct a C program using different components. The components are discussed below.

ComponentDescription
Preprocessor directives

It is used to provide instructions to the preprocessor. They start with a pound sign (#) and are not terminated by a semicolon.

Example: “ #include”, “#define”.

Function declaration

A function declaration specifies the function's name, return type, and parameter list.

Function declarations are usually placed at the beginning of a program.
 

Note: It is not required to declare functions in C, but it is good practice to do so.

Main function

The main function is the entry point of a C program. It is the first function that is executed when the program is run. The main function is required in all C programs.

Note: The main function must return an integer value.

Function definition 

A function definition provides the implementation of a function. It specifies the function's name, return type, parameter list, and body.

Note: Functions can be defined either before or after the main function.

Basic Structure of a C Program

Here, we have given an example code. Refer to this to understand the basic structure of a C program.

  • C

C

#include <stdio.h>

// Function declaration
int add(int a, int b);

// Main function
int main() {
   // Function call
   int result = add(2, 3);
  
   // Output
   printf("The result is %d\n", result);
  
   return 0;
}

// Function definition
int add(int a, int b) {
   return a + b;

}
You can also try this code with Online C Compiler
Run Code

 

Output: 

The result is 5.

 

In this example,

  • we have included the “stdio.h” header file using a preprocessor directive.
     
  • We have also declared a function called “add”, which takes two integer parameters and returns an integer. 
     
  • The main function calls the add function with two parameters, 2 and 3, and stores the result in a variable called “result”. The result is then printed to the console using the “printf” function. 
     

Finally, the program returns 0, indicating that it has been executed successfully.

Operators and Expressions in C Language

Operators in C are symbols that represent a specific operation. There are several types of operators in C, including arithmetic, relational, logical, bitwise, assignment, and conditional operators. Let's know more about them.

Arithmetic Operators

We use arithmetic operators to perform basic arithmetic operations such as addition, subtraction, multiplication, and division.

Operator

Description

Example

+

Addition

a + b

-

Subtraction

a - b

*

Multiplication

a * b

/

Division

a / b

%

Modulus (remainder of division)

a % b

Relational Operators

We use relational Operators to compare values.

Operator

Description

Example

==

Equal to

a == b

!=

Not equal to

a != b

>

Greater than

a > b

<

Less than

a < b

>=

Greater than or equal to

a >= b

<=

Less than or equal to

a <= b

Logical Operators

We use logical operators to combine two or more conditions.

Operator

Description

Example

&&

Logical AND

a && b

||

Logical OR

a || b

!

Logical NOT

!a

Bitwise Operators

We use bitwise operators to manipulate bits.

Operator

Description

Example

&

Bitwise AND

a & b

|

Bitwise OR

a | b

^

Bitwise XOR (exclusive OR)

a ^ b

~

Bitwise NOT

~a

<<

Left shift

a << b

>>

Right shift

a >> b

Assignment Operators

We use assignment operators to assign values to variables.

Operator

Description

Example

=

Assignment

a = b

+=

Addition assignment

a += b

-=

Subtraction assignment

a -= b

*=

Multiplication assignment

a *= b

/=

Division assignment

a /= b

%=

Modulus assignment

a %= b

&=

Bitwise AND assignment

a &= b

|=

Bitwise OR assignment

a |= b

^=

Bitwise XOR assignment

a ^= b

<<=

Left shift assignment

a <<= b

>>=

Right shift assignment

a >>= b

Conditional Operator

We use conditional operator for decision making.

Note:  Conditional operator is also known as ternary operator

Operator

Description

Example

?:

Ternary operator

a > b ? x : y

Precedence and Order of Evaluation

The list of operators according to their precedence and order of evaluation from highest to lowest is as follows,

Precedence

Operator Name

Operator

Highest

 

To

 

Lowest

Postfix increment and decrement operators

++, –

Example: a++

Prefix increment and decrement operators

++, –

Example: ++a

Unary operators

+, -, !, ~, ++, --, *, &, sizeof, (type)

Multiplicative operators

*, /, %

Additive operators

+, -

Shift operators

<<, >>

Relational operators

<, <=, >, >=

Equality operators

==, !=

Bitwise AND operator

&

Bitwise XOR operator

^

Bitwise OR operator

|

Logical AND operator

&&

Logical OR operator

||

Conditional operator

?:

Assignment operators

=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=

Note: It is important to note that operators with higher precedence are evaluated before operators with lower precedence, and operators with the same precedence are evaluated from left to right.

Read about Bitwise Operators in C here.

Input and Output

In C programming, it is essential to take user input and display the output on the screen. We can use the standard input and output functions in C for this purpose. Let's see how to take user input and display output on the screen in C programming language.

Step 1: Include Header Files

The first step is to include the necessary header files. The standard input-output header file "stdio.h" is required for this purpose. It contains the necessary functions for taking user input and displaying output on the screen.

#include<stdio.h>

Step 2: Declare Variables

Next step is to declare the variables that are required to store the user input. The data type of the variables should be appropriate for the type of input you want to take. 

For example, if you want to take an integer input, declare an integer variable.

int number;

Step 3: Take User Input

We need to use the "scanf" function to take user input. The "scanf" function reads input from the user and stores it in the specified variable.

scanf("%d", &number);

Step 4: Display Output

We need to use the "printf" function to display output on the screen. The "printf" function takes the format specifier and the variable to be displayed as arguments.

printf("The number entered by the user is: %d", number);

 

Full Code:

  • C

C

#include<stdio.h>

int main(){
   int number;
  
   printf("Enter an integer: ");
   scanf("%d", &number);
  
   printf("The number entered by the user is: %d", number);
  
   return 0;
}
You can also try this code with Online C Compiler
Run Code


Also see, Tribonacci Series

Statements in C

In C programming, statements are used to perform a specific task or operation. There are different types of statements in the C programming language, such as conditional statements, loop statements, and jump statements. Let's know more about them.

Conditional Statements

Conditional statements are used to perform different actions based on different conditions. There are three types of conditional statements in C programming language:

Conditional Statements
  • If statement: The if statement is used to execute a block of code if a particular condition is true.
if (condition){
    // Code to execute if condition is true
}

 

  • If-else statement: The if-else statement is used to execute one block of code if a particular condition is true and another block of code if the condition is false.
if (condition){
    // Code to execute if condition is true
}
else{
    // Code to execute if condition is false
}

 

  • Nested if statement: The nested if statement is used to execute a block of code if multiple conditions are true.
if (condition1){
    if (condition2){
        // Code to execute if condition1 and condition2 are true
    }
}

 

  • Switch case statement: The switch case statement is used to perform different actions based on different values. It is a multi-way branch statement that evaluates an expression and executes the code associated with the matching case.
switch (expression){
    case value1:
        // Code to execute if expression is equal to value1
        break;
    case value2:
        // Code to execute if expression is equal to value2
        break;
    default:
        // Code to execute if expression does not match any case
        break;
}

Loop Statements

Loop statements are used to execute a block of code repeatedly until a particular condition is met. There are three types of loop statements in C programming language:

  • For loop: The for loop is used to execute a block of code a specified number of times.
for (initialization; condition; increment){
    // Code to execute repeatedly
}

 

  • While loop: The while loop is used to execute a block of code repeatedly as long as a particular condition is true.
while (condition){
    // Code to execute repeatedly
}

 

  • Do-while loop: The do-while loop is used to execute a block of code repeatedly as long as a particular condition is true. It is similar to the while loop, but the condition is checked at the end of the loop. In do-while loop the do expression will run atleast once. 
do {
    // Code to execute repeatedly
} while (condition);

Jump Statements

Jump statements are used to transfer control within a program. There are four types of jump statements in C programming language:

  • Break statement: The break statement is used to terminate the current loop or switch case statement.
while (condition){
    if (some_condition){
        break; // Terminates the while loop
    }
}

 

  • Continue statement: The continue statement is used to skip the current iteration of the loop and continue with the next iteration.
for (i = 0; i < 10; i++){
    if (i == 5){
        continue; // Skips the iteration where i equals 5
    }
}

 

  • Return statement: The return statement is used to exit a function and return a value.
int square(int x){
    return x * x; // Returns the square of x
}

Pointers in C

In C programming, a pointer is a variable that stores the memory address of another variable. Pointers are essential in C programming as they allow us to manipulate memory directly and access data in a more efficient way. Let's know more about them.

Declaring a Pointer:

To declare a pointer, we use an asterisk (*) before the variable name. The following example declares a pointer variable named "ptr" that can store the memory address of an integer variable:

int *ptr;

 

Assigning a Value to a Pointer:

To assign a value to a pointer, we use the address-of operator (&) before the variable name. The following example assigns the address of the "number" variable to the "ptr" pointer:

int number = 10;
int *ptr = &number;

 

Accessing the Value of a Pointer:

To access the value of a pointer, we use the dereference operator (*) before the pointer variable name. The following example accesses the value of the "number" variable using the "ptr" pointer:

int number = 10;
int *ptr = &number;
printf("The value of the number is %d\n", *ptr);

 

Output

The value of the number is 10

 

Pointer Arithmetic:

Pointer arithmetic refers to performing arithmetic operations on pointers to move them to different memory locations. The following are some examples of pointer arithmetic:

int numbers[5] = {1, 2, 3, 4, 5};
int *ptr = numbers;
printf("%d\n", *ptr); // Outputs 1
ptr++;
printf("%d\n", *ptr); // Outputs 2

 

Output:

1
2

 

The above example declares an integer array "numbers" and a pointer variable "ptr" that points to the first element of the array. The first printf statement outputs the value of the first element, which is 1. The ptr++ statement moves the pointer to the next element of the array, which is 2, and the second printf statement outputs its value.

Passing Pointers to Functions:

Pointers can also be passed as arguments to functions to allow the function to access and manipulate the data in the memory location pointed to by the pointer. The following example declares a function named "changeNumber" that takes a pointer to an integer variable and increments its value by 1:

  • C

C

void changeNumber(int *ptr){
   (*ptr)++;
}

int main(){
   int number = 10;
   int *ptr = &number;
   printf("The original value of the number is %d\n", number);
   changeNumber(ptr);
   printf("The new value of the number is %d\n", number);
   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output:

The original value of the number is 10
The new value of the number is 11

Functions in C

A function is a block of code in C programming that performs a specific task. Functions are essential in C programming because they help us to organize code into smaller, manageable pieces, and reuse code. Let's know more about them.

Syntax of a Function:

The syntax of a function in C programming is as follows:

return_type function_name(parameters){
    // Function body
    return value;
}

 

where "return_type" is the data type of the value returned by the function, "function_name" is the name of the function, "parameters" are the inputs to the function, and "value" is the value returned by the function.

Declaring and Calling a Function:

To use a function in C programming, we need to declare it first, and then we can call it. The following example declares a function named "add" that takes two integers as inputs and returns their sum:

  • C

C

int add(int num1, int num2);


int main(){
   int a = 10, b = 20, result;
   result = add(a, b);
   printf("The sum of %d and %d is %d\n", a, b, result);
   return 0;
}


int add(int num1, int num2){
   int sum = num1 + num2;
   return sum;
}
You can also try this code with Online C Compiler
Run Code

 

Output

The sum of 10 and 20 is 30

Also read, Bit stuffing program in c

Parameters in a Function:

Parameters are the inputs to a function that are used to perform some task. There are two types of parameters in C programming language:

  • Value Parameters: Value parameters are the inputs to a function that are passed by value, which means that the function receives a copy of the input value
     
  • Pointer Parameters: Pointer parameters are the inputs to a function that are passed by reference, which means that the function receives the memory address of the input value

Types of Functions

There are two types of functions in C programming language:

  • Library Functions: Library functions are the functions that are already defined in the standard C library, and we can use them in our program by including the appropriate header file. For example, the "printf" function is a library function that is used to print output to the console
     
  • User-defined Functions: User-defined functions are the functions that we define in our program to perform specific tasks

Arrays in C

An array is a collection of similar data types that are stored in contiguous memory locations. In C programming language, we can define arrays of different data types, such as integers, characters, floating-point numbers, etc.

1D Array in C

A 1D array in C programming language is a collection of elements of the same data type that are stored in a linear sequence. The following is an example of a 1D integer array:

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

 

In the above example, we have defined an integer array named "numbers" that can store up to 5 integer values. We have initialized the array with the values {1, 2, 3, 4, 5} using the array initialization syntax.

We can access individual elements of the array using their index, which starts from 0. For example, to access the third element of the array, we use the following syntax:

int third = numbers[2];

2D Array in C

A 2D array in C programming language is a collection of elements that are organized in rows and columns. The following is an example of a 2D integer array:

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

 

In the above example, we have defined a 2D integer array named "matrix" that can store up to 3 rows and 3 columns of integer values. We have initialized the array with the values {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} using the array initialization syntax.

We can access individual elements of the array using their row and column indices. For example, to access the element in the second row and third column of the array, we use the following syntax:

int element = matrix[1][2];

Memory Allocation

Memory allocation refers to assigning a particular space in a computer's memory for a computer program or code.

There are two types of memory allocations. 

  • Static Memory allocation
     
  • Dynamic Memory allocation 
     

The key difference between Static memory allocation and Dynamic memory allocation is that Static memory allocation allows fixed memory size after allocation while Dynamic memory allocation allows changes in the memory size after allocation. 

Static Memory allocation

Static memory allocation is also known as Compile-time memory allocation because the memory is allocated during compile time. In this type of memory allocation, the memory that the program can use is fixed i.e. we can not allocate or deallocate memory during the program's execution. In many applications, it is not possible to predict how much memory will be needed by the program at run time.

Example:

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

 

In the above example, the memory for the array "numbers" is allocated at compile time, and it remains fixed throughout the program's execution.

Advantages of Static Memory allocation

  1. The memory is allocated during compile time
     
  2. It is easy to use
     
  3. It uses a stack data structure
     
  4. The execution time is efficiently controlled
     

Disadvantages of Static Memory allocation

  1. This allocation method leads to memory wastage
     
  2. Memory cannot be changed while executing a program
     
  3. Exact memory requirements must be known
     
  4. If memory is not required, it cannot be freed

Dynamic Memory allocation

Dynamic memory allocation is also known as Runtime memory allocation because the memory is allocated during runtime or program execution. The allocation and release of the memory space can be done using the library functions of stdlib.h header file. These functions allocate memory from a memory area called heap and deallocate this memory whenever not required so that it can be used for some other purpose.

The library functions of the stdlib.h header file, which helps to allocate memory dynamically are.  

  • malloc()
  • calloc()
  • realloc()
  • free()

 

malloc()

This function is used to allocate the single block of requested memory. On Success, the malloc() function returns a pointer to the first byte of the allocated memory. The malloc() function gives a NULL output when the memory is not enough.

Syntax: 

ptr=(data_type *)malloc(specified_size)

 

Here in the above syntax, ptr is a pointer of type data_type, and specified_size is the size in bytes required to allocate. The cast (data_type *) typecast the pointer returned by the malloc() function.

Example: 

ptr = (int*)malloc(100);

 

In the above example, the statement allocates 100 bytes of memory space, and the pointer variable ptr stores the address of the first byte in the memory.

calloc():

The calloc() function is used to allocate the memory as a number of elements of a given size. The calloc() function is similar to malloc() function. The only difference is that it takes two argument values. The first argument specifies the number of data items for which space is required, and the second argument specifies the size of each data item.

Syntax: 

ptr=(data_type *)calloc(n, specified_size)

 

Here in the above syntax, ptr is a pointer of type data_type, n is the number of data items,  and specified_size is the size in bytes required to allocate. The cast (data_type *) typecast the pointer returned by the malloc() function.

Example: 

ptr = (int*)calloc(4, sizeof (int));

 

In the above example, the statement allocates four blocks of memory, each block contains 4 bytes, and the starting address is stored in the pointer variable ptr.

realloc()

The realloc() function is used to increase the memory allocated by malloc() or calloc() function. This function alters the size of the memory block without losing the old data. The realloc() function takes two argument values. The first argument is a pointer variable to the block of memory that was previously allocated by calloc() or malloc(), and the second argument is the new size for that memory block. 

Syntax: 

realloc(pointer_variable, n);

 

Here in the above syntax, pointer_variable is a pointer to the block of memory that was previously allocated by malloc() or calloc() function, and n is the new size for that memory block.

Example: 

int *ptr;
ptr = (int*)malloc(100);
ptr = (int*)realloc(ptr, 400);

 

Here in the above example, we increased memory size from 100 bytes to 400 bytes.

free()

When memory is allocated dynamically by the malloc() and calloc() function, it should always be released when it is no longer required. Otherwise, it will consume memory until the program exit. The free() function is used to release this allocated memory space.

Syntax:

free(pointer_variable);

Here in the above syntax, the memory block pointed by the pointer 'pointer_variable' would be released back to the system.

Advantages of Dynamic Memory allocation

  1. This allocation method has no memory wastage
     
  2. The memory allocation is done at run time
     
  3. Memory size can be changed based on the requirements of the dynamic memory allocation
     
  4. If memory is not required, it can be freed
     

Disadvantages of Dynamic Memory allocation

  1. It requires more execution time due to execution during runtime
     
  2. The compiler does not help with allocation and deallocation. The programmer needs to both allocate and deallocate the memory

Struct

Structure is another user-defined data type available in C that allows us to combine data items of different kinds. The structure is similar to an array; the only difference is array is used to store the same data types. But, on the other hand, the structure is used to store data of any type, which is practical more useful.

Defining a Struct:

A struct is defined using the struct keyword, followed by the name of the struct, and a set of braces that enclose the data elements of the struct. Each data element within the struct is called a member, and is defined using a data type followed by a member name. The general syntax for defining a struct in C is as follows:

struct struct_name {
    data_type member1_name;
    data_type member2_name;
    .
    .
    .
    data_type memberN_name;
};

 

Example:

  • C

C

#include<stdio.h>
#include<string.h>
struct student
{
   char name[20];
   int rollno;
   float marks;
};
int main()
{
   struct student stu1;
   stu1.rollno=12;
   strcpy(stu1.name, "Dheeraj");
   //displaying the stored values
   printf("Name of student 1: %s\n", stu1.name);
   printf("Roll number of student 1: %d\n", stu1.rollno);
   return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output: 

Name of student 1: Dheeraj
Roll number of student 1: 12

Advantages of using Struct:

Structures have several advantages, including:

  • Grouping related data together: Structures allow related data to be grouped together under a single name, making it easier to organize and manage large amounts of data
     
  • Passing multiple arguments to functions: Structures can be passed as arguments to functions, allowing multiple data items to be passed and processed together
     
  • Defining complex data types: Structures can be used to define complex data types that consist of multiple data elements of different types

Union

A union is a unique data type in C that allows keeping particular data types in the exact memory location. You may define a union with many members, but the only one member can include a value at any time. Unions provide an efficient manner of using identical memory locations for multiple motives.

To define a union, you should use the union statement in the same manner as you probably did, even when defining a structure. The union statement defines a new data kind with a couple of members in your program. The format of a union statement is as follows −

union [union tag] 
{
   member definition;
   member definition;
   ...
   member definition;
} [one or more union variables]; 

 

The union tag is optionally available, and every member definition is a normal variable definition, which includes int i; or float f; or every other valid variable definition. You could specify one or more union variables at the end of the union's definition; however, it is optional. right here is the way you would define a union type named data having three members i, f, and str −

union Data 
{
   int i;
   float f;
   char str[20];
} 
data;  

 

A data type variable can store an integer, a floating-point number, or a string of characters. It means a single variable, i.e., the same memory location, can be used to store multiple types of data. Depending on your need, you may use any built-in or user-defined data types inside a union.

The memory occupied using a union may be large sufficient to keep the largest member of the union. For example, inside the above example, the data type will occupy 20 bytes of memory space because this is the most space that may be occupied using a character string. 

 

Example:

  • C

C

#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size: %d\n", sizeof(data));
return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output: 

Memory size: 20.

 

Advantages of Union:

  • It saves memory as all members share the same memory location
     
  • It helps in interpreting the same memory location in different ways, providing flexibility to programmers

 

Limitations of Union:

  • Since only one member can be accessed at a time, it may lead to errors if we accidentally access the wrong member
     
  • It does not provide type safety
     

Enumeration

Enumeration is a user-defined data type in C that is used to assign names to a set of integral constants, making the program more readable and easier to maintain. It provides a way to group related constants and makes the code more organized.

An enumeration is defined using the enum keyword followed by a name for the enumeration and a list of constant values enclosed in curly braces {}. Each constant is assigned a value starting from 0 by default, and the subsequent constants are assigned values incrementing by 1.

Example:

enum days {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

In this example, we define an enumeration named days that contains the names of the days of the week. Since we did not specify any values, Monday is assigned 0, Tuesday is assigned 1, and so on.
 

We can also specify values for each constant explicitly.

Example:

enum months {January=1, February, March, April, May, June, July, August, September, October, November, December};

In this example, we define an enumeration named months that contains the names of the months of the year. We specify that January should be assigned 1, and the subsequent months are assigned values incrementing by 1.
 

Using an Enumeration:
 

Once an enumeration is defined, we can declare variables of that type and assign them a value from the enumeration.

  • C

C

#include<stdio.h>
enum days {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};

int main() {
 enum days today = Wednesday;
 printf("Today is %d\n", today);
 return 0;
}
You can also try this code with Online C Compiler
Run Code

 

Output: 

Today is 2

 

In this example, we declare a variable today of type enum days and assign it the value Wednesday (which has a value of 2). We then print the value of today.
 

Advantages of Enumeration:

  • It makes the code more readable and easier to maintain
     
  • It helps in avoiding errors due to mistyping constant values
     
  • It provides type safety

File Handling

In the C programming language, File handling refers to the task of storing data in the C program in the form of input or output produced by running C programs in data files, i.e., a binary file or a text file for future reference and analysis.
 

The operations that we can perform on a File in C are: 

  • Creation of the new file
     
  • Opening an existing file
     
  • Reading from the file
     
  • Writing to the file
     
  • Deleting the file
     

 In this process, the computer system manages the data using a combination of buffers and streams.
 

Buffers:

A buffer is an area of memory used to temporarily store data while it is being transferred from one place to another. 

In file handling, a buffer is used to temporarily store data while it is being read or written to a file.

Streams:

A stream is a sequence of data that is transferred from one place to another. A file stream is a sequence of data that is transferred between a file and the program.
 

Input/Output functions:

In C, file handling is performed through a set of input/output (I/O) functions that allow a program to read and write data from and to files. The most commonly used I/O functions in C are given below,

Many functions in the C library are used to open, store, read, search or close files. There are some file functions are given below:
 

  1. fopen(): We use this function to open a new or existing file. The syntax of the fopen() is:
    *fptr = FILE *fopen(const char *filename, const char *mode);
     
  2. fclose(): We use this function to close a file. The syntax of the fclose() is:
    int fclose( FILE *fptr);
     
  3. fgets(): We use this function to read characters from a file. The syntax of the fgets() is:
    char *fgets(char *str, int n, FILE *fptr) 
     
  4. fputs(): We use this function to write a string of characters to a file at the location indicated by the file pointer. The syntax of the fputs() is:
    Int fputs(const char *str, FILE *fptr) 
     
  5. fprintf(): We use this function to print formatted output into the file. The syntax of the fprintf() is:
    fprintf(FILE *fptr, const char *format[,arguments,...]);
     
  6. fscanf(): We use this function to print formatted output into the file. The syntax of the fscanf() is:
    fscanf(FILE *fptr, const char *format[,address,...]);
     

Random Access Files:

C also provides the ability to perform random access file handling. This means that a program can access any part of a file directly, without having to read or write the file sequentially. This feature is useful for handling large files where reading or writing the entire file may not be feasible or efficient. The most commonly used functions for random access file handling in C are as follows,

  • fseek(): We use this function to set the file pointer to the given position. The syntax of the fseek() is:

int fseek(FILE *fptr, long displacement, int origin);
 

  • ftell(): The ftell() function gives the current position of the file position pointer. The value is counted from the beginning of the file. The syntax of the ftell() is:

long ftell(FILE *fptr);

C Programs for Practice

Program TitleDescriptionObjective
1. Sum of Array ElementsWrite a program to calculate the sum of all elements in an array.Practice array traversal and summation.
2. Reverse an ArrayWrite a program to reverse the order of elements in an array.Understand array manipulation and element swapping.
3. Find the Largest ElementWrite a program to find the largest element in an array.Learn how to compare elements and find the maximum.
4. Search for an ElementWrite a program to search for a specific element in an array using linear search.Practice searching algorithms and index handling.
5. Sort an ArrayWrite a program to sort an array in ascending order using bubble sort.Learn sorting algorithms and array ordering.
6. Matrix MultiplicationWrite a program to multiply two matrices and display the result.Apply array operations to multi-dimensional arrays.
7. Merge Two ArraysWrite a program to merge two arrays into a single array while maintaining order.Practice combining and sorting arrays.
8. Find the Frequency of ElementsWrite a program to count the frequency of each element in an array.Develop skills in counting and frequency analysis.
9. Array RotationWrite a program to rotate the elements of an array to the right by a given number of positions.Understand array rotation and indexing.
10. Dynamic Array AllocationWrite a program to dynamically allocate an array and allow user input for its elements.Practice dynamic memory allocation and user input handling.

Advantages of C

The advantages of C programming language are as follows,

  • C is a middle-level language that has characteristics of both high-level and low-level languages. It may be used for low-level programs, such as driver and kernel scripting, and it can also support high-level programming languages, such as software application scripting
     
  • C efficiently integrates algorithms and data structures, allowing for speedier program execution. This has allowed C to be used in programs that need more complex computations, such as MATLAB and Mathematica
     
  • The C programming language comes with a large library of built-in functions. It also includes memory allocation that is dynamic
     
  • C is a general-purpose programming language that may be used to create corporate software, games, graphics, and mathematics, among other things
     
  • C is a highly portable programming language that is widely used in Windows, UNIX, and Linux operating systems for scripting system programs
     
  • Because the C programming language is case-sensitive, lowercase and uppercase characters are interpreted differently
     
  • C's properties, such as direct access to machine-level hardware APIs, the existence of C compilers, predictable resource consumption, and dynamic memory allocation, make it an ideal language for scripting embedded system programs and drivers
     
  • C is a structured programming language that allows you to break down a big program into smaller programs known as functions. It also permits data to flow freely between these functions.

Disadvantages of C

The disadvantages of C programming language are as follows:

  • C is a complex language that requires a significant amount of knowledge and expertise to use effectively
     
  • C does not provide automatic memory management, which means that developers must manually manage memory allocation and deallocation
     
  • C's use of pointers can lead to errors and bugs, such as segmentation faults and memory leaks
     
  • C does not provide high-level abstractions, which can make it more difficult to write and maintain large, complex programs
     
  • C programs can be platform-dependent, which means that they may not work on different systems or architectures without modification
     
  • C can be difficult to learn and requires a significant amount of time and effort to master
     
  • C's syntax is relatively limited compared to more modern programming languages, which can make it more difficult to write clean, readable code

Must Read, odd or even program in c

Frequently Asked Questions

What are the applications of C programming?

C programming language is used in many applications, including operating systems, device drivers, embedded systems, game development, scientific simulations, and database management systems. It is also widely used in creating software for desktop and mobile platforms.

What C programming is used for?

C is a general-purpose programming language that may be used to create apps for companies, games, visual effects, programs that require computations, etc. with ease. The large library of the C language offers a variety of built-in functions. Furthermore, it provides dynamic memory allocation.

What is C vs C++ programming?

C is a structural or procedural programming language used for system applications and low-level programming. C++, on the other hand, is an object-oriented programming language with additional features such as encapsulation, data hiding, data abstraction, inheritance, polymorphism, and so on.

What is data type in C?

A data type is the type of data that is stored in a C program. In C, data types are used for defining variables or functions. The compiler must understand the type of predefined data that will be encountered in the program.

Conclusion

In this article, we discussed Introduction to C Programming. Mastering C programming is a pivotal step in understanding fundamental concepts that form the backbone of many advanced programming languages. From its efficient memory management and low-level capabilities to its wide-ranging applications in system and application software, C offers a solid foundation for aspiring programmers.

Check out other related articles to learn more on our platform Coding Ninjas Studio

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Live masterclass