The C programming is a computer programming language

'C' language is widely used in embedded systems. It is used for developing system applications. It is widely used for developing desktop applications. The main features of C language include low-level access to memory, a simple set of keywords, and clean style, these features make C language suitable for system programmings like an operating system or compiler development. Many later languages have borrowed syntax/features directly or indirectly from C language.

C Language

C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. C is the most widely used computer language. It keeps fluctuating at number one scale of popularity along with Java programming language, which is also equally popular and most widely used among modern software programmers.

The C Language is developed for creating system applications that directly interact with the hardware devices such as drivers, kernels, etc.C programming is considered as the base for other programming languages, that is why it is known as mother language.

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.
  • 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.

Why to Learn C Programming?

C programming language is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Software Development Domain. I will list down some of the key advantages of learning C Programming:

  • Easy to learn
  • Structured language
  • It produces efficient programs
  • It can handle low-level activities
  • It can be compiled on a variety of computer platforms

First C Program:

Any basic C program consists of the following sections:

  • 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

How to install C?

There are many compilers available for c and c++. You need to download any one. Here, we are going to use Turbo C++. It will work for both C and C++. To install the Turbo C software, you need to follow following steps.

  • Download Turbo C++
  • Create turboc directory inside c drive and extract the tc3.zip inside c:\turboc
  • Double click on install.exe file
  • Click on the tc application file located inside c:\TC\BIN to write the c program

C Environmet Setup:

Text Editor:

This will be used to type your program. Examples of few a editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.The name and version of text editors can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as on Linux or UNIX.The files you create with your editor are called the source files and they contain the program source codes. The source files for C programs are typically named with the extension ".c". Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it.

C Compiler:

The source code written in source file is the human readable source for your program. It needs to be "compiled", into machine language so that your CPU can actually execute the program as per the instructions given.The compiler compiles the source codes into final executable programs. The most frequently used and free available compiler is the GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the respective operating systems. The following section explains how to install GNU C/C++ compiler on various OS. We keep mentioning C/C++ together because GNU gcc compiler works for both C and C++ programming languages.

Installation on UNIX/Linux:

If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the following command from the command line −$ gcc -v.

If you have GNU compiler installed on your machine, then it should print a message as follows −

Using built-in specs.

Target: i386-redhat-linux

Configured with: ../configure --prefix=/usr .......

Thread model: posix

gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)

Installation on Mac OS:

If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Once you have Xcode setup, you will be able to use GNU compiler for C/C++.

Xcode is currently available at developer.apple.com/technologies/tools/.

Installation on Windows:

To install GCC on Windows, you need to install MinGW. To install MinGW, go to the MinGW homepage and follow the link to the MinGW download page. Download the latest version of the MinGW installation program, which should be named MinGW-<version>.exe. While installing Min GW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more.Add the bin subdirectory of your MinGW installation to your PATH environment variable, so that you can specify these tools on the command line by their simple names.After the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line.

printf() and scanf() in C:

The printf() and scanf() functions are used for input and output in C language. Both functions are inbuilt library functions, defined in stdio.h (header file).

printf() function:

The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

                          printf("format string",argument_list); 

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function:

The scanf() function is used for input. It reads the input data from the console.

                        scanf("format string",argument_list); 

C Tokens:

C Supports Six Types of Tokens:

  1. Keywords
  2. Identifiers
  3. Constants
  4. Strings
  5. Operators
  6. Special Symbols

C Keywords:

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in the C language. Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example: int money;

Here, int is a keyword that indicates money is a variable of type int (integer).

As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all keywords allowed in ANSI C.

C Identifiers:

C identifiers represent the name in the C program, for example, variables, functions, arrays, structures, unions, labels, etc. An identifier can be composed of letters such as uppercase, lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an underscore. If the identifier is not used in the external linkage, then it is called as an internal identifier. If the identifier is used in the external linkage, then it is called as an external identifier.

Identifiers are names given to different names given to entities such as constants, variables, structures, functions etc. Identifiers must be unique. They are created to give a unique name to an entity to identify it during the execution of the program.

 For example:

                          int money;

                          double accountBalance;

Here, money and accountBalance are identifiers.

Also remember, identifier names must be different from keywords. You cannot use int as an identifier because int is a keyword.

Rules for naming identifiers:

An identifier can only have alphanumeric characters (a-z , A-Z , 0-9) (i.e. letters & digits) and underscore( _ ) symbol.

  • Identifier names must be unique
  • The first character must be an alphabet or underscore.
  • You cannot use a keyword as identifiers.
  • Only first thirty-one (31) characters are significant.
  • Must not contain white spaces.
  • Identifiers are case-sensitive.

Types of identifiers:

1.Internal Identifier

If the identifier is not used in the external linkage, then it is known as an internal identifier. The internal identifiers can be local variables.

2. External Identifier

If the identifier is used in the external linkage, then it is known as an external identifier. The external identifiers can be function names, global variables.

C Constants:

Constants are like a variable, except that their value never changes during execution once defined.C Constants is the most fundamental and essential part of the C programming language. Constants in C are the fixed values that are used in a program, and its value remains the same during the entire execution of the program.

  • Constants are also called literals.
  • Constants can be any of the data types.
  • It is considered best practice to define constants using only upper-case names.

Syntax:

const type constant_name;

//const keyword defines a constant in C.

C operators:

C operators are symbols that are used to perform mathematical or logical manipulations. The C programming language is rich with built-in operators. Operators take part in a program for manipulating data and variables and form a part of the mathematical or logical expressions.

Types of Operators in C:

C programming language offers various types of operators having different functioning capabilities.

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operators

5. Increment and Decrement Operators

6. Conditional Operator

7. Bitwise Operators

8. Special Operators

Arithmetic Operators: Arithmetic Operators are used to performing mathematical calculations like addition (+), subtraction (-), multiplication (*), division (/) and modulus (%).

Increment and Decrement Operators: Increment and Decrement Operators are useful operators generally used to minimize the calculation, i.e. ++x and x++ means x=x+1 or -x and x−−means x=x-1. But there is a slight difference between ++ or −− written before or after the operand. Applying the pre-increment first add one to the operand and then the result is assigned to the variable on the left whereas post-increment first assigns the value to the variable on the left and then increment the operand.

Relational operators: Relational operators are used to comparing two quantities or values.

logical operators: C provides three logical operators when we test more than one condition to make decisions. These are: && (meaning logical AND), || (meaning logical OR) and ! (meaning logical NOT).

1. && And operator. It performs logical conjunction of two expressions. (if both expressions evaluate to True, result is True. If either expression evaluates to False, the result is False)

2. || Or operator. It performs a logical disjunction on two expressions. (if either or both expressions evaluate to True, the result is True).

3. ! Not operator. It performs logical negation on an expression.

Bitwise operation: C provides a special operator for bit operation between two variables.

<<        Binary Left Shift Operator

>>        Binary Right Shift Operator

~          Binary Ones Complement Operator

&         Binary AND Operator

^          Binary XOR Operator

|           Binary OR Operator

Assignment operators: Assignment operators applied to assign the result of an expression to a variable. C has a collection of shorthand assignment operators.They are

=          Assign

+=        Increments then assign

-=         Decrements then assign

*=        Multiplies then assign

/=         Divides then assign

%=       Modulus then assign

<<=      Left shift and assign

>>=      Right shift and assign

&=       Bitwise AND assign

^=        Bitwise exclusive OR and assign

|=         Bitwise inclusive OR and assign

conditional operator: C offers a ternary operator which is the conditional operator (?: in combination) to construct conditional expressions.

 special operators: C supports some special operators.They are

sizeof()            Returns the size of a memory location.

&         Returns the address of a memory location.

*          Pointer to a variable.

Variables in C:

A variable is a name of the memory location. It is used to store data. Its value can be changed, and it can be reused many times.It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable: type variable_list; 

The example of declaring the variable is given below:

int a;  float b;  char c; 

We can also provide values while declaring the variables as given below:

int a=10,b=20;//declaring 2 variable of integer type 

float f=20.8; 

char c='A'; 

Rules for defining variables:

  • A variable can have alphabets, digits, and underscore.
  • A variable name can start with the alphabet, and underscore only. It can't start with a digit.
  • No whitespace is allowed within the variable name.
  • A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Types of Variables in C:

There are many types of variables in c:

  1. local variable
  2. global variable
  3. static variable
  4. automatic variable
  5. external variable

1. Local Variable:

A variable that is declared inside the function or block is called a local variable.It must be declared at the start of the block.

void function1(){ 

int x=10;//local variable 

You must have to initialize the local variable before it is used.

2. Global Variable:

A variable that is declared outside the function or block is called a global variable. Any function can change the value of the global variable. It is available to all the functions.It must be declared at the start of the block.

int value=20;//global variable 

void function1(){ 

int x=10;//local variable 

}

3. Static Variable:

A variable that is declared with the static keyword is called static variable. It retains its value between multiple function calls.

void function1(){ 

int x=10;//local variable 

static int y=10;//static variable 

x=x+1; 

y=y+1; 

printf("%d,%d",x,y); 

4. Automatic Variable:

All variables in C that are declared inside the block, are automatic variables by default. We can explicitly declare an automatic variable using auto keyword.

void main(){ 

int x=10;//local variable (also automatic) 

auto int y=20;//automatic variable 

5. External Variable:

We can share a variable in multiple C source files by using an external variable. To declare an external variable, you need to use extern keyword.

myfile.h

extern int x=10;//external variable (also global) 

program1.c

#include "myfile.h" 

#include <stdio.h> 

void printValue(){ 

    printf("Global variable: %d", global_variable); 

Data Types in C:

A data type specifies the type of data that a variable can store such as integer, floating, character, etc. Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

The data-type in a programming language is the collection of data with values having fixed meaning as well as characteristics. Some of them are an integer, floating point, character, etc. Usually, programming languages specify the range values for given data-type.

C Data Types are used to:

  1. Identify the type of a variable when it declared.
  2. Identify the type of the return value of a function.
  3. Identify the type of a parameter expected by a function.

A data-type in C programming is a set of values and is determined to act on those values. C provides various types of data-types which allow the programmer to select the appropriate type for the variable to set its value. The types in C can be classified as follows −

ANSI C provides three types of data types:

  1. Primary(Built-in) Data Types: void, int, char, double and float.
  2. Derived Data Types: Array, References, and Pointers.
  3. User Defined Data Types: Structure, Union, and Enumeration.

1. Declaring Primary(Built-in) Data Types with Variabe Names:

After taking suitable variable names, they need to be assigned with a data type.

int: integers are whole numbers that can have both zero, positive and negative values but no decimal values. For example, 0, -5, 10

We can use int for declaring an integer variable. For Example:  int age;

Char: Keyword char is used for declaring character type variables.

For example: char test = 'h';

The size of the character variable is 1 byte.

float and double: float and double are used to hold real numbers.For Example:

float salary;

double price;

In C, floating-point numbers can also be represented in exponential.

void : void is an incomplete type. It means "nothing" or "no type". You can think of void as absent.For example, if a function is not returning anything, its return type should be void.Note that, you cannot create variables of void type.

short and long : If you need to use a large number, you can use a type specifier long. Here's how:

long a;

long long b;

long double c;

Here variables a and b can store integer values. And, c can store a floating-point number. If you are sure, only a small integer ([−32,767, +32,767] range) will be used, you can use short.

short d;

signed and unsigned: In C, signed and unsigned are type modifiers. You can alter the data storage of a data type by using them. For example,

unsigned int x;

int y;

Here, the variable x can hold only zero and positive values because we have used the unsigned modifier.

2. Derived Data Types:

Data types that are derived from fundamental data types are derived types. For example: arrays, pointers, function types, structures, etc.

C supports three derived data types:

  1. Arrays: Arrays are sequences of data items having homogeneous values. They have adjacent memory locations to store values.
  2. References: Function pointers allow referencing functions with a particular signature.
  3. Pointers: These are powerful C features which are used to access the memory and deal with their addresses.

3. User Defined Data Types:

C allows the feature called type definition which allows programmers to define their identifier that would represent an existing data type. There are three such types:

1. Structure: It is a package of variables of different types under a single name. This is done to handle data efficiently. "struct" keyword is used to define a structure.

2. Union: These allow storing various data types in the same memory location. Programmers can define a union with different members, but only a single member can contain a value at a given time. It is used for

3. Enum: Enumeration is a special data type that consists of integral constants, and each of them is assigned with a specific name. "enum" keyword is used to define the enumerated data type.

C Control Statements:

C if else Statement:

The if-else statement in C is used to perform the operations based on some specific condition. The operations specified in if block are executed if and only if the given condition is true.

There are the following variants of if statement in C language.

  1. If statement
  2. If-else statement
  3. If else-if ladder
  4. Nested if

If Statement

The if statement is used to check some given condition and perform some operations depending upon the correctness of that condition. It is mostly used in the scenario where we need to perform the different operations for the different conditions. The syntax of the if statement is given below.

if(expression){ 

//code to be executed 

}

If-else Statement

The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition. The syntax of the if-else statement is given below.

if(expression){ 

//code to be executed if condition is true 

}else{ 

//code to be executed if condition is false 

If else-if ladder Statement

The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario where there are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition is true then the statements defined in the if block will be executed, otherwise if some other condition is true then the statements defined in the else-if block will be executed, at the last if none of the condition is true then the statements defined in the else block will be executed. There are multiple else-if blocks possible. It is similar to the switch case statement where the default is executed instead of else block if none of the cases is matched.

if(condition1){ 

//code to be executed if condition1 is true 

}else if(condition2){ 

//code to be executed if condition2 is true 

else if(condition3){ 

//code to be executed if condition3 is true 

... 

else{ 

//code to be executed if all the conditions are false 

C Switch Statement

The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable.

The syntax of switch statement in c language is given below:

switch(expression){   

case value1:   

 //code to be executed;   

 break;  //optional 

case value2:   

 //code to be executed;   

 break;  //optional 

......    

default:    

 code to be executed if all cases are not matched;   

}

Rules for switch statement in C language

1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no break statement found in the case, all the cases will be executed present after the matched case. It is known as fall through the state of C switch statement.

Let's try to understand it by the examples. We are assuming that there are following variables.

int x,y,z; 

char a,b; 

float f;

Functioning of switch case statement

First, the integer expression specified in the switch statement is evaluated. This value is then matched one by one with the constant values given in the different cases. If a match is found, then all the statements specified in that case are executed along with the all the cases present after that case including the default statement. No two cases can have similar values. If the matched case contains a break statement, then all the cases present after that will be skipped, and the control comes out of the switch. Otherwise, all the cases following the matched case will be executed.

C Switch statement is fall-through: In C language, the switch statement is fall through; it means if you don't use a break statement in the switch case, all the cases after the matching case will be executed.

Nested switch case statement: We can use as many switch statement as we want inside a switch statement. Such type of statements is called nested switch case statements.

C Loops:

The looping can be defined as repeating the same process multiple times until a specific condition satisfies. There are three types of loops used in the C language. In this part of the tutorial, we are going to learn all the aspects of C loops.

Why use loops in C language?

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of writing the same code again and again, we can repeat the same code for a finite number of times. For example, if we need to print the first 10 natural numbers then, instead of using the printf statement 10 times, we can print inside a loop which runs up to 10 iterations.

Advantage of loops in C

1) It provides code reusability.

2) Using loops, we do not need to write the same code again and again.

3) Using loops, we can traverse over the elements of data structures (array or linked lists).

Types of C Loops:

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C:

The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when it is necessary to execute the loop at least once (mostly menu driven programs).

The syntax of do-while loop in c language is given below:

do{ 

//code to be executed 

}while(condition); 

Infinitive do while loop

The do-while loop will run infinite times if we pass any non-zero value as the conditional expression.

do{ 

//statement 

}while(1);

while loop in C:

The while loop in c is to be used in the scenario where we don't know the number of iterations in advance. The block of statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called a pre-tested loop.

The syntax of while loop in c language is given below:

while(condition){ 

//code to be executed 

Infinitive while loop in C

If the expression passed in while loop results in any non-zero value then the loop will run the infinite number of times.

while(1){ 

//statement 

Properties of while loop

A conditional expression is used to check the condition. The statements defined inside the while loop will repeatedly execute until the given condition fails.

The condition will be true if it returns 0. The condition will be false if it returns any non-zero number.

In while loop, the condition expression is compulsory.

Running a while loop without a body is possible.

We can have more than one conditional expression in while loop.

If the loop body contains only one statement, then the braces are optional.

for loop in C:

The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance.

The syntax of for loop in c language is given below:

for(initialization;condition;incr/decr){ 

//code to be executed 

}

Loop body

The braces {} are used to define the scope of the loop. However, if the loop contains only one statement, then we don't need to use braces. A loop without a body is possible. The braces work as a block separator, i.e., the value variable declared inside for loop is valid only for that block and not outside.

 Infinitive for loop in C

To make a for loop infinite, we need not give any expression in the syntax. Instead of that, we need to provide two semicolons to validate the syntax of the for loop. This will work as an infinite for loop.

#include<stdio.h> 

void main () 

    for(;;) 

    { 

        printf("welcome to javatpoint"); 

    } 

C break statement:

The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops. The break statement in C can be used in the following two scenarios:

  1. With switch case
  2. With loop

Syntax:

//loop or switch case  

break; 

C continue statement:

The continue statement in C language is used to bring the program control to the beginning of the loop. The continue statement skips some lines of code inside the loop and continues with the next iteration. It is mainly used for a condition so that we can skip some code for a particular condition.

Syntax:

//loop statements 

continue; 

//some lines of the code which is to be skipped 

C goto statement:

The goto statement is known as jump statement in C. As the name suggests, goto is used to transfer the program control to a predefined label. The goto statment can be used to repeat some part of the code for a particular condition. It can also be used to break the multiple loops which can't be done by using a single break statement. However, using goto is avoided these days since it makes the program less readable and complecated.

Syntax:

label:  

//some part of the code;  

goto label;

When should we use goto?

The only condition in which using goto is preferable is when we need to break the multiple loops using a single statement at the same time.

Type Casting in C:

Typecasting allows us to convert one data type into other. In C language, we use cast operator for typecasting which is denoted by (type).

Syntax:

(type)value;

C Functions:  

C Functions

In c, we can divide a large program into the basic building blocks known as function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the C program. In other words, we can say that the collection of functions creates a program. The function is also known as procedure or subroutine in other programming languages.

Advantage of functions in C

There are the following advantages of C functions.

  • By using functions, we can avoid rewriting same logic/code again and again in a program.
  • We can call C functions any number of times in a program and from any place in a program.
  • We can track a large C program easily when it is divided into multiple functions.
  • Reusability is the main achievement of C functions.
  • However, Function calling is always a overhead in a C program.
  • next →← prev
  • C Functions
  • In c, we can divide a large program into the basic building blocks known as function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the C program. In other words, we can say that the collection of functions creates a program. The function is also known as procedure or subroutine in other programming languages.
  •  
  • Advantage of functions in C
  • There are the following advantages of C functions.
  •  
  • By using functions, we can avoid rewriting same logic/code again and again in a program.
  • We can call C functions any number of times in a program and from any place in a program.
  • We can track a large C program easily when it is divided into multiple functions.
  • Reusability is the main achievement of C functions.
  • However, Function calling is always a overhead in a C program.

C Functions:

In c, we can divide a large program into the basic building blocks known as function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the C program. In other words, we can say that the collection of functions creates a program. The function is also known as procedure or subroutine in other programming languages.

Advantage of functions in C

There are the following advantages of C functions.

  • By using functions, we can avoid rewriting same logic/code again and again in a program.
  • We can call C functions any number of times in a program and from any place in a program.
  • We can track a large C program easily when it is divided into multiple functions.
  • Reusability is the main achievement of C functions.
  • However, Function calling is always a overhead in a C program.

Function Aspects:

There are three aspects of a C function.

  • Function declaration A function must be declared globally in a c program to tell the compiler about the function name, function parameters, and return type.
  • Function call Function can be called from anywhere in the program. The parameter list must not differ in function calling and function declaration. We must pass the same number of functions as it is declared in the function declaration.
  • Function definition It contains the actual statements which are to be executed. It is the most important aspect to which the control comes when the function is called. Here, we must notice that only one value can be returned from the function.

The syntax of creating function in c language is given below:

return_type function_name(data_type parameter...){ 

//code to be executed 

Types of Functions:

There are two types of functions in C programming:

  1. Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
  2. User-defined functions: are the functions which are created by the C programmer, so that he/she can use it many times. It reduces the complexity of a big program and optimizes the code.

Return Value:

A C function may or may not return a value from the function. If you don't have to return any value from the function, use void for the return type.

Example without return value:

void hello(){ 

printf("hello c"); 

If you want to return any value from the function, you need to use any data type such as int, long, char, etc. The return type depends on the value to be returned from the function.

Let's see a simple example of C function that returns int value from the function.

Example with return value:

int get(){ 

return 10; 

Different aspects of function calling

A function may or may not accept any argument. It may or may not return any value. Based on these facts, There are four different aspects of function calls.

  • function without arguments and without return value
  • function without arguments and with return value
  • function with arguments and without return value
  • function with arguments and with return value

C Library Functions

Library functions are the inbuilt function in C that are grouped and placed at a common place called the library. Such functions are used to perform some specific operations. For example, printf is a library function used to print on the console. The library functions are created by the designers of compilers.

All C standard library functions are defined inside the different header files saved with the extension .h. We need to include these header files in our program to make use of the library functions defined in such header files. For example, To use the library functions such as printf/scanf we need to include stdio.h in our program which is a header file that contains all the library functions regarding standard input/output.

Call by value and Call by reference in C:

There are two methods to pass the data into the function in C language, i.e., call by value and call by reference.

Call by value in C

  • In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we can say that the value of the variable is used in the function call in the call by value method.
  • In call by value method, we can not modify the value of the actual parameter by the formal parameter.
  • In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter.
  • The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in the function definition.

Call by reference in C

  • In call by reference, the address of the variable is passed into the function call as the actual parameter.
  • The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed.
  • In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.

Recursion in C

Recursion is the process which comes into existence when a function calls a copy of itself to work on a smaller problem. Any function which calls itself is called recursive function, and such function calls are called recursive calls. Recursion involves several numbers of recursive calls. However, it is important to impose a termination condition of recursion. Recursion code is shorter than iterative code however it is difficult to understand.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal problems.

Generally, iterative solutions are more efficient than recursion since function call is always overhead. Any problem that can be solved recursively, can also be solved iteratively. However, some problems are best suited to be solved by the recursion, for example, tower of Hanoi, Fibonacci series, factorial finding, etc.

Recursive Function

A recursive function performs the tasks by dividing it into the subtasks. There is a termination condition defined in the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is returned from the function.

The case at which the function doesn't recur is called the base case whereas the instances where the function keeps calling itself to perform a subtask, is called the recursive case. All the recursive functions can be written using this format.

Memory allocation of Recursive method

Each recursive call creates a new copy of that method in the memory. Once some data is returned by the method, the copy is removed from the memory. Since all the variables and other stuff declared inside function get stored in the stack, therefore a separate stack is maintained at each recursive call. Once the value is returned from the corresponding function, the stack gets destroyed. Recursion involves so much complexity in resolving and tracking the values at each recursive call. Therefore we need to maintain the stack and track the values of the variables defined in the stack.

C Array:

An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.

Properties of Array

The array contains the following properties.

  • Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
  • Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.
  • Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.

Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.

Declaration of C Array

We can declare an array in the c language in the following way.

          data_type array_name[array_size];

Initialization of C Array

The simplest way to initialize an array is by using the index of each element. We can initialize each element of the array by using the index.

 Consider the following example.

marks[0]=80;//initialization of array 

marks[1]=60; 

marks[2]=70; 

marks[3]=85; 

marks[4]=75;

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60}; 

In such case, there is no requirement to define the size. So it may also be written as the following code.

int marks[]={20,30,40,50,60};  

Two Dimensional Array in C:

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. However, 2D arrays are created to implement a relational database lookalike data structure. It provides ease of holding the bulk of data at once which can be passed to any number of functions wherever required.

Declaration of two dimensional Array in C

The syntax to declare the 2D array is given below.

     data_type array_name[rows][columns]; 

Initialization of 2D Array in C

In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being done simultaneously. However, this will not work with 2D arrays. We will have to define at least the second dimension of the array. The two-dimensional array can be declared and defined in the following way.

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

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];

Passing Array to Function in C:

In C, there are various general problems which requires passing more than one variable of the same type to a function. For example, consider a function which sorts the 10 elements in ascending order. Such a function requires 10 numbers to be passed as the actual parameters from the main function. Here, instead of declaring 10 different numbers and then passing into the function, we can declare and initialize an array and pass that into the function. This will resolve all the complexity since the function will now work for any number of values.

As we know that the array_name contains the address of the first element. Here, we must notice that we need to pass only the name of the array in the function which is intended to accept an array. The array defined as the formal parameter will automatically refer to the array specified by the array name defined as an actual parameter.

Consider the following syntax to pass an array to the function.

unctionname(arrayname);//passing array 

Methods to declare a function that receives an array as an argument

There are 3 ways to declare the function which is intended to receive an array as an argument.

First way:

return_type function(type arrayname[]) 

Declaring blank subscript notation [] is the widely used technique.

Second way:

return_type function(type arrayname[SIZE]) 

Optionally, we can define size in subscript notation [].

Third way:

return_type function(type *arrayname) 

Returning array from the function

As we know that, a function can not return more than one value. However, if we try to write the return statement as return a, b, c; to return three values (a,b,c), the function will return the last mentioned value which is c in our case. In some problems, we may need to return multiple values from a function. In such cases, an array is returned from the function.

Returning an array is similar to passing the array into the function. The name of the array is returned from the function. To make a function returning an array, the following syntax is used.

int * Function_name() { 

//some statements;  

return array_type; 

}

To store the array returned from the function, we can define a pointer which points to that array. We can traverse the array by increasing that pointer since pointer initially points to the base address of the array. Consider the following example that contains a function returning the sorted array.

C Pointers:

The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte

Consider the following example to define a pointer which stores the address of an integer.

int n = 10;  

int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type integer.  

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer used to dereference a pointer.

int *a;//pointer to int 

char *c;//pointer to char

Pointer to array

int arr[10]; 

int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array arr. 

Pointer to a function

void show (int); 

void(*p)(int) = &display; // Pointer p is pointing to the address of a function 

Pointer to structure

struct st { 

    int i; 

    float f; 

}ref; 

struct st *p = &ref; 

Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and used with arrays, structures, and functions.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.

Address Of (&) Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

NULL Pointer

A pointer that is not assigned any value but NULL is known as the NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will provide a better approach.

Reading complex pointers

There are several things which must be taken into the consideration while reading the complex pointers in C. Lets see the precedence and associativity of the operators which are used regarding pointers.

(): This operator is a bracket operator used to declare and define the function.

[]: This operator is an array subscript operator

* : This operator is a pointer operator.

Identifier: It is the name of the pointer. The priority will always be assigned to this.

Data type: Data type is the type of the variable to which the pointer is intended to point. It also includes the modifier like signed int, long, etc).

How to read the pointer: int (*p)[10].

To read the pointer, we must see that () and [] have the equal precedence. Therefore, their associativity must be considered here. The associativity is left to right, so the priority goes to ().

Inside the bracket (), pointer operator * and pointer name (identifier) p have the same precedence. Therefore, their associativity must be considered here which is right to left, so the priority goes to p, and the second priority goes to *.

Assign the 3rd priority to [] since the data type has the last precedence. Therefore the pointer will look like following.

char -> 4

* -> 2

p -> 1

[10] -> 3

The pointer will be read as p is a pointer to an array of integers of size 10.

C Double Pointer (Pointer to Pointer)

As we know that, a pointer is used to store the address of a variable in C. Pointer reduces the access time of a variable. However, In C, we can also define a pointer to store the address of another pointer. Such pointer is known as a double pointer (pointer to pointer). The first pointer is used to store the address of a variable whereas the second pointer is used to store the address of the first pointer. Let's understand it by the diagram given below.

pointer to pointer in c

The syntax of declaring a double pointer is given below.

int **p; // pointer to a pointer which is pointing to an integer.

Pointer Arithmetic in C

We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the result will be an integer value. Following arithmetic operations are possible on the pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is somewhat different from the general arithmetic since the value of the pointer will get increased by the size of the data type to which the pointer is pointing.

We can traverse an array by using the increment operation on a pointer which will keep pointing to every element of the array, perform some operation on that, and update itself in a loop.

The Rule to increment the pointer is given below:

new_address= current_address + i * size_of(data type) 

Where i is the number by which the pointer get increased.

32-bit

For 32-bit int variable, it will be incremented by 2 bytes.

64-bit

For 64-bit int variable, it will be incremented by 4 bytes.

Pointer Arithmetic in C

We can perform arithmetic operations on the pointers like addition, subtraction, etc. However, as we know that pointer contains the address, the result of an arithmetic operation performed on the pointer will also be a pointer if the other operand is of type integer. In pointer-from-pointer subtraction, the result will be an integer value. Following arithmetic operations are possible on the pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is somewhat different from the general arithmetic since the value of the pointer will get increased by the size of the data type to which the pointer is pointing.

We can traverse an array by using the increment operation on a pointer which will keep pointing to every element of the array, perform some operation on that, and update itself in a loop.

The Rule to increment the pointer is given below:

new_address= current_address + i * size_of(data type) 

Where i is the number by which the pointer get increased.

32-bit

For 32-bit int variable, it will be incremented by 2 bytes.

 

64-bit

For 64-bit int variable, it will be incremented by 4 bytes.

 

Let's see the example of incrementing pointer variable on 64-bit architecture.

 

#include<stdio.h> 

int main(){ 

int number=50;       

int *p;//pointer to int     

p=&number;//stores the address of number variable       

printf("Address of p variable is %u \n",p);       

p=p+1;       

printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented by 4 bytes.     

return 0; 

}   

Output

Address of p variable is 3214864300

After increment: Address of p variable is 3214864304

Traversing an array by using pointer

#include<stdio.h> 

void main () 

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

    int *p = arr; 

    int i; 

    printf("printing array elements...\n"); 

    for(i = 0; i< 5; i++) 

    { 

        printf("%d  ",*(p+i)); 

    } 

Output

printing array elements...

1  2  3  4  5

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start pointing to the previous location. The formula of decrementing the pointer is given below:

new_address= current_address - i * size_of(data type) 

32-bit

For 32-bit int variable, it will be decremented by 2 bytes.

64-bit

For 64-bit int variable, it will be decremented by 4 bytes.

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

new_address= current_address + (number * size_of(data type)) 

32-bit

For 32-bit int variable, it will add 2 * number.

64-bit

For 64-bit int variable, it will add 4 * number.

C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number from a pointer will give an address. The formula of subtracting value from the pointer variable is given below:

new_address= current_address - (number * size_of(data type)) 

32-bit

For 32-bit int variable, it will subtract 2 * number.

64-bit

For 64-bit int variable, it will subtract 4 * number.

Illegal arithmetic with pointers

There are various operations which can not be performed on pointers. Since, pointer stores address hence we must ignore the operations which may lead to an illegal address, for example, addition, and multiplication. A list of such operations is given below.

  • Address + Address = illegal
  • Address * Address = illegal
  • Address % Address = illegal
  • Address / Address = illegal
  • Address & Address = illegal
  • Address ^ Address = illegal
  • Address | Address = illegal
  • ~Address = illegal

Pointer to function in C

As we discussed in the previous chapter, a pointer can point to a function in C. However, the declaration of the pointer variable must be the same as the function.

Pointer to Array of functions in C

To understand the concept of an array of functions, we must understand the array of function. Basically, an array of the function is an array which contains the addresses of functions. In other words, the pointer to an array of functions is a pointer pointing to an array which contains the pointers to the functions.

Dynamic memory allocation in C:

The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

  1. malloc()
  2. calloc()
  3. realloc()
  4. free()

malloc() function in C

It doesn't initialize memory at execution time, so it has garbage value initially. It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

ptr=(cast-type*)malloc(byte-size)

calloc() function in C

The calloc() function allocates multiple block of requested memory. It initially initialize all bytes to zero. It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below: 

ptr=(cast-type*)calloc(number, byte-size)

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

 ptr=realloc(ptr, new-size) 

free() function in C:

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

free(ptr) 

C Structure:

Why use structure?

In C, there are cases where we need to store multiple attributes of an entity. It is not necessary that an entity has all the information of one type only. It can have different attributes of different data types. For example, an entity Student may have its name (string), roll number (int), marks (float). To store such type of information regarding an entity student, we have the following approaches:

Construct individual arrays for storing names, roll numbers, and marks.

Use a special data structure to store the collection of different data types.

Structure:

Structure in c is a user-defined data type that enables us to store the collection of different data types. Each element of a structure is called a member. Structures ca; simulate the use of classes and templates as it can store various information

The ,struct keyword is used to define the structure. Let's see the syntax to define the structure in c.

struct structure_name  

{

data_type member1; 

data_type member2;

.

.

data_type memeberN; 

}; 

Why use structure?

In C, there are cases where we need to store multiple attributes of an entity. It is not necessary that an entity has all the information of one type only. It can have different attributes of different data types. For example, an entity Student may have its name (string), roll number (int), marks (float). To store such type of information regarding an entity student, we have the following approaches:

Construct individual arrays for storing names, roll numbers, and marks.

Use a special data structure to store the collection of different data types.

Let's look at the first approach in detail.

#include<stdio.h> 

void main () 

char names[2][10],dummy; // 2-dimensioanal character array names is used to store the names of the students  

int roll_numbers[2],i; 

 float marks[2]; 

for (i=0;i<3;i++) 

     

printf("Enter the name, roll number, and marks of the student %d",i+1); 

scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]); 

scanf("%c",&dummy); // enter will be stored into dummy character at each iteration 

printf("Printing the Student details ...\n"); 

for (i=0;i<3;i++) 

 { 

printf("%s %d %f\n",names[i],roll_numbers[i],marks[i]); 

 }

Outpu:

Enter the name, roll number, and marks of the student 1Arun 90 91       

Enter the name, roll number, and marks of the student 2Varun 91 56     

Enter the name, roll number, and marks of the student 3Sham 89 

Printing the Student details...

Arun 90 91.000000                                                                     

Varun 91 56.000000 

Sham 89 69.000000

The above program may fulfill our requirement of storing the information of an entity student. However, the program is very complex, and the complexity increase with the amount of the input. The elements of each of the array are stored contiguously, but all the arrays may not be stored contiguously in the memory. C provides you with an additional and simpler approach where you can use a special data structure, i.e., structure, in which, you can group all the information of different data type regarding an entity.

What is Structure?

Structure in c is a user-defined data type that enables us to store the collection of different data types. Each element of a structure is called a member. Structures ca; simulate the use of classes and templates as it can store various information

The ,struct keyword is used to define the structure. Let's see the syntax to define the structure in c

struct structure_name  

{  

data_type member1; 

data_type member2; 

.

.

data_type memeberN;

}; 

Let's see the example to define a structure for an entity employee in c.

struct employee 

{   int id; 

char name[20]; 

float salary; 

}; 

The following image shows the memory allocation of the structure employee that is defined in the above example.

c structure memory allocation

Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the members or fields of the structure. Let's understand it by the diagram given below:

c structure 

Declaring structure variable

We can declare a variable for the structure so that we can access the member of the structure easily. There are two ways to declare structure variable:

By struct keyword within main() function

By declaring a variable at the time of defining the structure.

1st way:

Let's see the example to declare the structure variable by struct keyword. It should be declared within the main function.

struct employee 

{   int id; 

char name[50]; 

float salary;

}; 

Now write given code inside the main() function.

struct employee e1, e2; 

The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2 can be treated in the same way as the objects in C++ and Java.

2nd way:

Let's see another way to declare variable at the time of defining the structure.

struct employee 

{   int id; 

char name[50]; 

float salary; 

}e1,e2; 

Which approach is good?

If number of variables are not fixed, use the 1st approach. It provides you the flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare a variable in main() function.

Accessing members of the structure

There are two ways to access structure members:

1. By . (member or dot operator)

2. By -> (structure pointer operator)

Array of Structures in C:
An array of structres in C can be defined as the collection of multiple structures variables where each variable contains information about different entities. The array of structures in C are used to store information about multiple entities of different data types. The array of structures is also known as the collection of structure.

C String:

The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0. The termination character ('\0') is important in a string since it is the only way to identify where the string ends. When we define a string as char s[10], the character s[10] is implicitly initialized with the null in the memory.

There are two ways to declare a string in c language.

1. By char array

2. By string literal

Difference between char array and string literal:

There are two main differences between char array and literal.

  • We need to add the null character '\0' at the end of the array by ourself whereas, it is appended internally by the compiler in the case of the character array.
  • The string literal cannot be reassigned to another set of characters whereas, we can reassign the characters of the array.

Traversing String

Traversing the string is one of the most important aspects in any of the programming languages. We may need to manipulate a very large text which can be done by traversing the text. Traversing string is somewhat different from the traversing an integer array. We need to know the length of the array to traverse an integer array, whereas we may use the null character in the case of string to identify the end the string and terminate the loop.

Hence, there are two ways to traverse a string.

  • By using the length of string
  • By using the null character.

C gets() and puts() functions:

The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in the input/output operations of the strings.

C gets() function:

The gets() function enables the user to enter some characters followed by the enter key. All the characters entered by the user get stored in a character array. The null character is added to the array to make it a string. The gets() allows the user to enter the space-separated strings. It returns the string entered by the user.

Declaration: char[] gets(char[]); 

C puts() function:

The puts() function is very much similar to printf() function. The puts() function is used to print the string on the console which is previously read by using gets() or scanf() function. The puts() function returns an integer value representing the number of characters being printed on the console. Since, it prints an additional newline character with the string, which moves the cursor to the new line on the console, the integer value returned by puts() will always be equal to the number of characters present in the string plus 1.

Declaration: int puts(char[]) 

C String Functions:

C String Length: strlen() function: The strlen() function returns the length of the given string. It doesn't count null character '\0'.

C Copy String: strcpy(): The strcpy(destination, source) function copies the source string in destination.

C String Concatenation: strcat(): The strcat(first_string, second_string) function concatenates two strings and result is returned to first_string.

C Compare String: strcmp(): The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are equal. Here, we are using gets() function which reads string from the console.

C Reverse String: strrev(): The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev() function.

C String Lowercase: strlwr(): The strlwr(string) function returns string characters in lowercase. Let's see a simple example of strlwr() function.

C String Uppercase: strupr(): The strupr(string) function returns string characters in uppercase. Let's see a simple example of strupr() function.

C String strstr(): The strstr() function returns pointer to the first occurrence of the matched string in the given string. It is used to return substring from first match till the last character.

Syntax:

char *strstr(const char *string, const char *match) 

String strstr() parameters

string: It represents the full string from where substring will be searched.

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.

1. Singly Linked Lists

2. Doubly Linked Lists

3. 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.

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.

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.

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).

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.

Command Line Arguments in C

The arguments passed from command line are called command line arguments. These arguments are handled by main() function.

To support command line argument, you need to change the structure of main() function as given below.

int main(int argc, char *argv[] ) 

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Advantages of C Programming Language:

1. C language is a building block for many other currently known languages. C language has variety of data types and powerful operators. Due to this, programs written in C language are efficient, fast and easy to understand.

2. C is highly portable language. This means that C programs written for one computer can easily run on another computer without any change or by doing a little change.

3. There are only 32 keywords in ANSI C and its strength lies in its built-in functions. Several standard functions are available which can be used for developing programs.

4. Another important advantage of C is its ability to extend itself. A C program is basically a collection of functions that are supported by the C library this makes us easier to add our own functions to C library. Due to the availability of large number of functions, the programming task becomes simple.

5. C language is a structured programming language. This makes user to think of a problem in terms of function modules or blocks. Collection of these modules makes a complete program. This modular structure makes program debugging, testing and maintenance easier.

Disadvantages of C Programming language:

1.C does not have concept of OOPs, that’s why C++ is developed.

2. There is no runtime checking in C language.

3. There is no strict type checking. For example, we can pass an integer value.

4. for the floating data type.

5. C doesn’t have the concept of namespace.

6. C doesn’t have the concept of constructor or destructor.