C Programming Tutorial: The Basics you Need to Master C

Last updated on Apr 29,2024 42.5K Views

Ravi Kiran
Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning... Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning more about Data Science and Big-Data Hadoop.
C Programming Tutorial: The Basics you Need to Master C

C Programming Language was Developed in the mid-1970s, but still, it is considered as the Mother of all Programming Languages. It supports multiple functionalities and also powerful enough to directly interact with hardware units and the kernel. This C Programming Tutorial deals with,

 

Brief History of C Programming Language

C-Programming-Tutorial-Founder-of-C-Edureka

C is developed by Dennis Ritchie in the year 1972 at Bell Laboratories(USA). It is a General-purpose, Structured, Machine Independent, Simple and Flexible programming language. It was mainly developed as a system programming language to write an operating system.

Features of C Programming Language

  • High-Level Language

C provides strong abstraction in case of its libraries and built-in features that make it machine-independent. It is capable enough to develop system applications such as the kernel, driver, etc.

  • Structured Language

C Language supports structured programming which includes the use of functions. Functions reduce the code complexity and are totally reusable.

  • Rich Library

Unlike its predecessors, C language incorporates multiple built-in arithmetics and logical functions along with many built-in libraries which make development faster and convenient.

  • Extensible

C Language is a High-level language and is also open for upgrades. Hence, the programming language is considered to be extensible like any other high-level languages.

 

Features-of-C-Edureka

 

  • Recursion

C Language supports function back-tracking which involves recursion. In the process of recursion, a function is called within another function for multiple numbers of times.

  • Pointers

C enables users to directly interact with memory using the pointers. We use pointers in memory, structure, functions, arrays, stack and many more.

  • Faster

C Language comes with a minimal number of libraries and built-in functions which makes the compile and execution-times to be less and the system faces low overhead.

  • Memory Management

C provides the best in class memory management. It can both allocate and deallocate memory dynamically. the malloc(), calloc(), realloc() functions are used to allocate memory dynamically and free() function is used to deallocate the used memory at any instance of time.

Related Learning: How to Run a C Program in Command Prompt?

Datatypes and Variables

Datatypes in C are broadly classified into four categories as follows.

C-Programming-Tutorial-datatypes-of-C-Edureka

 

Basic Datatypes

Basic Datatypes are considered as the most fundamental and primary datatypes that C has to offer. The Datatypes that come under Basic Datatypes are as follows.

Datatype NameDatatype SizeDatatype Range
short1 byte-128 to 127
unsigned short1 byte0 to 255
char1 byte-128 to 127
unsigned char1 byte0 to 255
int2 bytes-32,768 to 32,767
unsigned int2 bytes0 to 65,535
long4 bytes-2,147,483,648 to 2,147,483,647
unsigned long4 bytes0 to 4,294,967,295
float4 bytes3.4E-38 to 3.4E+38
double8 bytes1.7E-308 to 1.7E+308
long double10 bytes3.4E-4932 to 1.1E+4932

 

Derived Datatypes

A derived type is formed by using one or more basic types in combination. They are the object types whose functionalities are predefined in the C libraries.

  • Function types
  • Pointer types
  • Array types
  • Structure types
  • Union types

Enumeration Datatypes

Enumerated Datatypes are used to declare Integral constants in C programming language so that the integral constant names are easy to remember and maintain. The keyword enum is used to declare enumerated datatypes.

example:  enum plug{on = 1, off = 0}; 

Void Datatypes

The void data type is an empty data type that is used as a return type for the functions that return no value in C.

example:

void  function(int n)
int function(void)

 

Variables in C

Variable is defined as the reserved memory space which stores a value of a definite datatype. The value of the Variable is not constant, instead, it allows changes. There are mainly five types of variables supported in C.

  • local variable
  • global variable
  • static variable
  • automatic variable
  • external variable

Local Variables

Any variable that is declared at the inside a code block or a function and has the scope confined to that particular block of code or function is called to be a local variable.

//Example

void Edureka()
{
       int Local_variable=10;
}

 

Global Variables

Any variable that is declared at the outside a code block or a function and has the scope across the entire program and allows any function to change it’s value is known as Global Variable.

//Example

int Global_variable=10;
void Edureka()
{
      int Local_variable=20;
} 

 

Static Variables

Any variable that is declared using the keyword static is known as a Static Variable. Static Variables retain the declared value throughout the entire execution of the program and will not be changed between multiple function calls.

//Example

void Edureka()
{
     int Local_variable =10;//
     static int Static_variable =10;
     Local_variable=Local_variable+1;
     Static_variable =Static_variable+1;
     printf("%d,%d",x,y);
} 

 

Automatic Variables

Automatic Variables can be declared by using the keyword auto. By default, all the variables declared in C language are Automatic Variables.

//Example

void main()
{
      int Local_variable=10;  //(automatic default)
      auto int auto=20;   //(automatic variable)
};

 

External Variables

External Variables are declared by using the extern keyword. We can share a variable in multiple C source files by using an external variable.

//Example

extern external=10; 

Let us execute our first C Program.

 

First C Program

In this C Programming Tutorial, we will understand the basic structure of a C Program. Any basic C program consists of the following sections

Structure

 

  • Preprocessor Directives

Preprocessor Directives are declared at the beginning of every C Program with a special character #. They are defined as predefined functions or Macro programs that are invoked and compiled by the C Compiler during the compilation process.

  • Functions

Functions in C Program are defined as the subdivided program of the main program. Functions provide code reusability and decrease code complexity.

  • Variables

Variable is defined as a name declared to a store the values in a C Program. Every variable used in C has a specific data type that determines the size and layout of the variable’s memory.

  • Statements & Expressions

Statements are nothing but the instructions we provide to the computer to compile and the expressions, on the other hand, are considered to be the mathematical or the logical statements which yield into a resultant value.

  • Comments

Comments are the messages written by the developer in the code for easy understanding of the logic of the code used while programming. The comments will not be compiled by the compiler. the comments are written within // or /* */.

Let us now execute our first Hello World Program.

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

//Output

Hello World

 

Loops in C Programming

Loops in C are defined as a programming statement that is designed to execute a particular code segment for a specific number of times or until a particular condition provided is satisfied. There are mainly three-loop statements available in C.

For loop

For loop in C Programming is a Control Flow Statement which allows you to execute a specific code segment for a finite number iterations. A for loop has three arguments, namely, initialization variable, Counter variable, and increment/decrement variable.

The flow chart for the for loop is as follows:

//Example

#include<stdio.h>
int main()
{
     int i;
     for (i=1; i<=5; i++)
     {
           printf("%dn", i);
     }
     return 0;
}

//Output

1
2
3
4
5

 

While Loop

While loop in C Programming is a Contol Flow Statement that executes itself repeatedly until a given boolean condition is satisfied. While loop can be considered as a repeating If statement.

The flow chart for the for loop is as follows:

//Example

#include<stdio.h>
int main()
{
      int count=1;
      while (count<= 5)
      {
            printf("%d ", count);
            count++;
      }
      return 0;
}

//Output

1 2 3 4 5

 

Do-While Loop

Do While loop in C Programming is considered to be a conditional statement completely similar to a normal While loop. The only difference is that the Do While loop has the boolean/conditional statement is placed at the end of the loop. This makes the Do While loop to execute at least for once.

The flow chart for the for loop is as follows:

//Example

#include<stdio.h>
int main()
{
	int j=0;
	do
	{
		printf("Value of the variable j is: %dn", j);
		j++;
	}while (j<=5);
	return 0;
}

//Output

Value of the variable j is: 0
Value of the variable j is: 1
Value of the variable j is: 2
Value of the variable j is: 3
Value of the variable j is: 4
Value of the variable j is: 5

 

Conditional Statements in C Programming

Conditional Statements in C language can be defined as the programming statements that are designed to decide the execution flow of the statements of the program over the specified mathematical or logical condition. The important conditional statements in this C Programming tutorial are as follows.

if

If Statement in C language is a programming conditional statement that executes a code segment over a condition, provided if it is true and valid. Below is the flowchart for if condition.

//Example

#include<stdio.h>
int main()
{
      int number=0;
      printf("Enter a number:");
      scanf("%d",&number);
      if(number%2==0){
            printf("your number is %d and it is an even number",number);
      }
      return 0;
}

//Output

Enter a number:4
your number is 4 and it is an even number

 

else-if

Else If Conditional Statement in C language is used to execute one statement out of the two. The Conditional Statement executes the code segment provided is true and valid. Below is the flowchart for the else-if condition.

//Example

#include<stdio.h>
int main()
{
     int number=0;
     printf("enter a number:");
     scanf("%d",&number);
     if(number%2==0)
     {
            printf("your number is %d and it is an even number",number);
     }
     else
     {
            printf("your number is %d and it is an odd number",number);
     }
     return 0;
}

//Output

Enter a number:5
your number is 5 and it is an odd number

 

else-if ladder

Else if Ladder in C language is set of consecutive Else-If statements which are used to execute one true and valid statement out of a collection of given statements. Below is the flowchart for the else-if ladder condition.

C-Programming-Tutorial-else-if-ladder-C-Edureka.jpg

 

#include<stdio.h>
int main()
{
      int number=0;
      printf("enter a number:");
      scanf("%d",&number);
      if(number==10)
      {
            printf("your inputted number is equals to 10");
      }
      else if(number==50)
     {
            printf("your inputted number is equal to 50");
     }
     else if(number==100)
     {
            printf("your inputted number is equal to 100");
     }
     else
    {
            printf("your inputted number is not equal to 10, 50 or 100");
    }
    return 0;
}

//Output

enter a number:5
your inputted number is not equal to 10, 50 or 100

 

Nested if

Nested-If in C language is a conditional statement where one Else-If statement is embedded into another If statement. Below is the flowchart for the nested-if condition.

C-Programming-Tutorial-nested-if-C-Edureka.jpg

//Example

#include<stdio.h>
int main()
{
      int v1, v2;
      printf("Enter the value of First variable :");
      scanf("%d",&v1);
      printf("Enter the value of Second variable :");
      scanf("%d",&v2);
      if (v1 != v2)
      {
             printf("First variable is not equal to Second variablen");
             if (v1<v2)
             {
                    printf("First variable is not equal to Second variablen");
             }
             else
             {
                    printf("Second variable is greater than First variablen");
              }
       }
       else
      {
              printf("First variable is equal to Second variablen");
      }
      return 0;
}

//Output:

Enter the value of First variable :12
Enter the value of Second variable :21
First variable is not equal to Second variable
Second variable is greater than First variable

 

Data Structures in C Programming

Data structure can be defined as a collection of data values, the relationships among them, and the functions that are applied on to the data. They are broadly classified as follows.

  • Primitive Data Structures / Built-in Data Structures
  • Abstract Data Structures / User-Defined Data Structures

 

C-Programming-Tutorial-data-structures-C-Edureka.jpg

Arrays

An array is defined as the collection of similar type of data items stored at contiguous memory locations. The array is the simplest data structure where each data element can be randomly accessed by using its index number.

There are three different types of Arrays, namely:

  • One-Dimensional Array
  • Two-Dimensional Array
  • Multi-Dimensional Array

One-Dimensional Array

The One-dimensional array can be defined as an array with a single row and multiple columns. The elements in the 1D array are accessed using their index numbers.

 

int arrayone[10];

 

Two-Dimensional Array

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. The elements of the array are accessed using their intersection coordinates.

 

int arraytwo[10][5];

 

Multi-Dimensional Array

The multi-dimensional array can be defined as an array of arrays. The 3D array is organized as 3D matrix which can be represented as the collection of multiple rows and columns. The elements of the array are accessed using their 3D intersection coordinates.

int arraythree[10][10][10];

 

Linked Lists

Linked lists are linear data structures similar to that of arrays, but, the only difference is that the elements are not saved in the sequential memory locations, instead, they are stored in random addresses and connected using pointers.

  • Singly Linked Lists
  • Doubly Linked Lists
  • Circular Linked Lists

Singly Linked List

A singly linked list is an alternate for a one-dimensional array. The elements in the singly-linked list are stored in sequential format but at different memory locations which are interconnected with each other through pointers. Singly-linked lists are traversable only in one direction

 

Data-Structures-in-c-singly-linked-list-edureka

Code for Singly Linked List can be found here

 

Doubly Linked List

A doubly-linked list is an alternate for a two-dimensional array. The elements in the doubly-linked list are stored in sequential format but at different memory locations which are interconnected with each other through pointers. Doubly-linked lists are traversable in both the directions.

 

Data-Structures-in-c-doubly-linked-list-edureka

 

Code for Doubly Linked List can be found here

 

Circular Linked List

A circular Linked list is similar to that of a singly-linked list. But, the only difference is that the pointer of the tail of the circular linked list points back to the head.

 

Data-Structures-in-c-circular-linked-list-edureka

 

Code for Circular Linked List can be found here

 

Files

Basic File Handling Techniques in C, provide the basic functionalities that user can perform against files in the system.

 

FunctionOperation
fopen()To Open a file
fclose()To Close a file
fgets()To Read a file
fprint()To Write into a file

 

  • “r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returnsNULL.
  • “w” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
  • “a” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open a file.
  • r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.
  • “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns NULL, if unable to open the file.
  • “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.

Stack

The stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).

 

Data-Structures-in-C-Stack-Edureka

Code for Stack can be found here

 

Queue

A Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). Also, C includes Circular Queue.

 

Data-Structures-in-C-Queue-Edureka

Code for Queue can be found here

 

Graph

The graph is defined as a data structure that is represented in graphical format using nodes and edges. There are three types of graphs, namely.

  • Undirected Graphs

 

  • Directed Graphs

 

C-Programming-Tutorial-directed-graph-C-Edureka

  • Directed Weighted Graphs

 

C-Programming-Tutorial-directed-weighted-graph-C-Edureka

 

A graph in C language is commonly represented in two formats as follows:

For Example:

 

  • Adjacency Matrix

 

  • Adjacency List

 

 

 

Strings

The string is defined as a one-dimensional array of characters terminated by a null character. The character array or the string is used to store text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0.

Two types of strings are:

  • char array
  • string literal

The String functions available in C language are as follows

FunctionFunctionality
strlen()Returns the length of the String
strcpy()Copies String from Source to Destination
strcat()Joins two Strings and stores result in first
strcmp()Compares the given two Strings
strrev()Reverses the String
strlwr()Converts String to Lower case
strupr()Converts String to Upper case
strchr()String scanning function
strncat()Concatenates String with the part of another
srtncmp()Compares the parts of two Strings
strncpy()Copies a part of the String

 

//Example

#include<stdio.h>
#include<string.h>
int main( )
{
      int len;
      char text[10]="Edureka" ;
      length = strlen(array) ;
      printf ( "string length is = %d n" , length ) ;
      return 0;
}

//Output

string length is = 7

 

Functions

A Function can be defined as a subdivided program of the main program enclosed within flower brackets. Functions can be called by the main program to implement its functionality. This procedure provides Code Re-usability and Modularity.

Two types of Functions are:

  • Library Functions
  • User-Defined Functions

Advantages of Functions

  • Writing the same code repeatedly in a program will be avoided.
  • Functions can be called any number of times in a program.
  • Tracking a C program easily when it is divided into multiple functions.
  • Reusability is the main achievement of C functions.

Rules to be followed to use functions:

  • Function Declaration

A function is required to declared as Global and the name of the function, parameters of the function and return type of the function are required to be clearly specified.

  • Function Call

While calling the function from anywhere in the program, care should be taken that the datatype in the argument list and the number of elements in the argument list are matching.

  • Function Definition

After the function is declared, it is important that the function includes parameters declared, code segment, and the return value.

  • Four Aspects of using Functions in C Programming
    • Function without arguments and without return value
    • Function without arguments and with the return value
    • Function with arguments and without return value
    • Function with arguments and with the return value

 

Structure and Union

Structure

A Structure is a user-defined datatype available in C that allows to combining data items of different data types together. Structures are used to represent a record. struct is the keyword used to declare Structures.

//Example

#include<stdio.h>
struct Distance
{
       int feet;
       float inch;
} dist1, dist2, sum;

int main()
{
      printf("1st distancen");
      printf("Enter feet: ");
      scanf("%d",&dist1.feet);
      printf("Enter inch: ");
      scanf("%f",&dist1.inch);
      printf("2nd distancen");
      printf("Enter feet: ");
      scanf("%d",&dist2.feet);
      printf("Enter inch: ");
      scanf("%f",&dist2.inch);
      sum.feet = dist1.feet + dist2.feet;
      sum.inch = dist1.inch + dist2.inch; 
      while (sum.inch!= 12)
      {
             ++sum.feet;
             sum.inch = sum.inch - 12;
       }
       printf("Sum of distances = %d'-%.1f\"", sum.feet, sum.inch);
       return 0;
}

//Output

1st distance
Enter feet: 12
Enter inch: 7.9
2nd distance
Enter feet: 2
Enter inch: 9.8
Sum of distances = 15'-5.7"

 

Union

union is a special data type available in C that allows storing different data types in the same memory location. union is the keyword used to declare Union.

//Example

#include<stdio.h>
union Employee
{
      int Id;
      char Name[25];
      int Age;
      long Salary;
};
void main()
{
      union Employee E;
      printf("nEnter Employee Id : ");
      scanf("%d",&E.Id);
      printf("nEnter Employee Name : ");
      scanf("%s",&E.Name);
      printf("nEnter Employee Age : ");
      scanf("%d",&E.Age);
      printf("nEnter Employee Salary : ");
      scanf("%ld",&E.Salary);
      printf("nnEmployee Id : %d",E.Id);
      printf("nEmployee Name : %s",E.Name);
      printf("nEmployee Age : %d",E.Age);
      printf("nEmployee Salary : %ld",E.Salary);
}

//Output

Enter Employee Id : 102191
Enter Employee Name : Karan
Enter Employee Age : 29
Enter Employee Salary : 45000

Employee Id : 102011
Employee Name : Ajay
Employee Age : 26
Employee Salary : 45000

 

Difference between Structure and Union

ParameterStructureUnion
Keywordstructunion
MemoryEach member has a unique MemoryAll members share allocated Memory
InitializationAll members are initialized togetherOnly first member can be initialized
Data AccessAll members is accessed togetherOne member is accessed at a time
Value ChangeChanging the value of one member will not affect othersChanging the value of one member will affect others

 

Important Interview Questions

  1. Binary Search
  2. Bubble Sort
  3. Merge Sort
  4. Round Robin Scheduling
  5. Fibonacci Series
  6. Roots of Quadratic Equation
  7. LCM of two numbers

 

With this, we come to an end of this “C Programming Tutorial” article. I hope you have understood the importance of Data Structures, Syntax, functionality, and operations performed using them.

Now that you have understood the basics of Programming in C, check out the Java training provided by Edureka on many technologies like Java, Spring and  many more, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe

Got a question for us? Mention it in the comments section of this “C Programming Tutorial” blog and we will get back to you as soon as possible.

Comments
0 Comments

Join the discussion

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.