Monday, August 26, 2019

C Language


C Language


History of C Language

History of C language is interesting to know. Here we are going to discuss a brief history of the c language.
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T (American Telephone & Telegraph), located in the U.S.A.
Dennis Ritchie is known as the founder of the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many features of previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
LanguageYearDeveloped By
Algol1960International Group
BCPL1967Martin Richard
B1970Ken Thompson
Traditional C1972Dennis Ritchie
K & R C1978Kernighan & Dennis Ritchie
ANSI C1989ANSI Committee
ANSI/ISO C1990ISO Committee
C991999Standardization Committee



Features of C Language



C is the widely used language. It provides many featuresthat are given below.
  1. Simple
  2. Machine Independent or Portable
  3. Mid-level programming language
  4. structured programming language
  5. Rich Library
  6. Memory Management
  7. Fast Speed
  8. Pointers
  9. Recursion
  10. Extensible


1) Simple

C is a simple language in the sense that it provides a structured approach (to break the problem into parts), the rich set of library functionsdata types, etc.

2) Machine Independent or Portable

Unlike assembly language, c programs can be executed on different machines with some machine specific changes. Therefore, C is a machine independent language.


3) Mid-level programming language

Although, C is intended to do low-level programming. It is used to develop system applications such as kernel, driver, etc. It also supports the features of a high-level language. That is why it is known as mid-level language.

4) Structured programming language

C is a structured programming language in the sense that we can break the program into parts using functions. So, it is easy to understand and modify. Functions also provide code reusability.

5) Rich Library

provides a lot of inbuilt functions that make the development fast.

6) Memory Management

It supports the feature of dynamic memory allocation. In C language, we can free the allocated memory at any time by calling the free() function.

7) Speed

The compilation and execution time of C language is fast since there are lesser inbuilt functions and hence the lesser overhead.

8) Pointer

C provides the feature of pointers. We can directly interact with the memory by using the pointers. We can use pointers for memory, structures, functions, array, etc.

9) Recursion

In C, we can call the function within the function. It provides code reusability for every function. Recursion enables us to use the approach of backtracking.

10) Extensible

C language is extensible because it can easily adopt new features.


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.
  1. Download Turbo C++
  2. Create turboc directory inside c drive and extract the tc3.zip inside c:\turboc
  3. Double click on install.exe file
  4. Click on the tc application file located inside c:\TC\BIN to write the c program

1) Download Turbo C++ software

You can download turbo c++ from many sites. download Turbo c++

2) Create turboc directory in c drive and extract the tc3.zip

Now, you need to create a new directory turboc inside the c: drive. Now extract the tc3.zip file in c:\truboc directory.

3) Double click on the install.exe file and follow steps

Now, click on the install icon located inside the c:\turboc




It will ask you to install c or not, press enter to install.

First C Program

Before starting the abcd of C language, you need to learn how to write, compile and run the first c program.
To write the first c program, open the C console and write the following code:
  1. #include <stdio.h>    
  2. int main(){    
  3. printf("Hello C Language");    
  4. return 0;   
  5. }  
#include <stdio.h> includes the standard input output library functions. The printf() function is defined in stdio.h .


int main() The main() function is the entry point of every program in c language.
printf() The printf() function is used to print data on the console.
return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for successful execution and 1 for unsuccessful execution.

How to compile and run the c program

There are 2 ways to compile and run the c program, by menu and by shortcut.

By menu

Now click on the compile menu then compile sub menu to compile the c program.
Then click on the run menu then run sub menu to run the c program.

By shortcut

Or, press ctrl+f9 keys compile and run the program directly.
You will see the following output on user screen.



Flow of C Program

The C program follows many steps in execution. To understand the flow of C program well, let us see a simple program first.
File: simple.c
  1. #include <stdio.h>    
  2. int main(){    
  3. printf("Hello C Language");    
  4. return 0;   
  5. }  

Execution Flow





Let's try to understand the flow of above program by the figure given below.



1) C program (source code) is sent to preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates an expanded source code.
2) Expanded source code is sent to compiler which compiles the code and converts it into assembly code.
3) The assembly code is sent to assembler which assembles the code and converts it into object code. Now a simple.obj file is generated.
4) The object code is sent to linker which links it to the library such as header files. Then it is converted into executable code. A simple.exe file is generated.
5) The executable code is sent to loader which loads it into memory and then it is executed. After execution, output is sent to console.

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:
  1. 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.
  1. scanf("format string",argument_list);  

Program to print cube of given number

Let's see a simple example of c language that gets input from the user and prints the cube of the given number.
  1. #include<stdio.h>    
  2. int main(){    
  3. int number;    
  4. printf("enter a number:");    
  5. scanf("%d",&number);    
  6. printf("cube of number is:%d ",number*number*number);    
  7. return 0;  
  8. }    

Output

enter a number:5
cube of number is:125
The scanf("%d",&number) statement reads integer number from the console and stores the given value in number variable.
The printf("cube of number is:%d ",number*number*number) statement prints the cube of number on the console.

Program to print sum of 2 numbers

Let's see a simple example of input and output in C language that prints addition of 2 numbers.
  1. #include<stdio.h>    
  2. int main(){    
  3. int x=0,y=0,result=0;  
  4.   
  5. printf("enter first number:");  
  6. scanf("%d",&x);  
  7. printf("enter second number:");  
  8. scanf("%d",&y);  
  9.   
  10. result=x+y;  
  11. printf("sum of 2 numbers:%d ",result);  
  12.   
  13. return 0;  
  14. }    

Output

enter first number:15
enter second number:5
sum of 2 numbers:20


Variables in C

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:
  1. type variable_list;  
The example of declaring the variable is given below:
  1. int a;  
  2. float b;  
  3. char c;  
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
  1. int a=10,b=20;//declaring 2 variable of integer type  
  2. float f=20.8;  
  3. 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.
Valid variable names:
  1. int a;  
  2. int _ab;  
  3. int a30;  
Invalid variable names:
  1. int 2;  
  2. int a b;  
  3. int long;  

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

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.
  1. void function1(){  
  2. int x=10;//local variable  
  3. }  
You must have to initialize the local variable before it is used.

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.
  1. int value=20;//global variable  
  2. void function1(){  
  3. int x=10;//local variable  
  4. }  

Static Variable

A variable that is declared with the static keyword is called static variable.
It retains its value between multiple function calls.
  1. void function1(){  
  2. int x=10;//local variable  
  3. static int y=10;//static variable  
  4. x=x+1;  
  5. y=y+1;  
  6. printf("%d,%d",x,y);  
  7. }  
If you call this function many times, the local variable will print the same value for each function call, e.g, 11,11,11 and so on. But the static variable will print the incremented value in each function call, e.g. 11, 12, 13 and so on.

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.
  1. void main(){  
  2. int x=10;//local variable (also automatic)  
  3. auto int y=20;//automatic variable  
  4. }  

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
  1. extern int x=10;//external variable (also global)  
program1.c
  1. #include "myfile.h"  
  2. #include <stdio.h>  
  3. void printValue(){  
  4.     printf("Global variable: %d", global_variable);  
  5. }  


Data Types in C

A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
C Data Types
There are the following data types in C language.
TypesData Types
Basic Data Typeint, char, float, double
Derived Data Typearray, pointer, structure, union
Enumeration Data Typeenum
Void Data Typevoid

Data Types in C

A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
C Data TypesThere are the following data types in C language.
TypesData Types
Basic Data Typeint, char, float, double
Derived Data Typearray, pointer, structure, union
Enumeration Data Typeenum
Void Data Typevoid


Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both signed and unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
Data TypesMemory SizeRange
char1 byte−128 to 127
signed char1 byte−128 to 127
unsigned char1 byte0 to 255
short2 byte−32,768 to 32,767
signed short2 byte−32,768 to 32,767
unsigned short2 byte0 to 65,535
int2 byte−32,768 to 32,767
signed int2 byte−32,768 to 32,767
unsigned int2 byte0 to 65,535
short int2 byte−32,768 to 32,767
signed short int2 byte−32,768 to 32,767
unsigned short int2 byte0 to 65,535
long int4 byte-2,147,483,648 to 2,147,483,647
signed long int4 byte-2,147,483,648 to 2,147,483,647
unsigned long int4 byte0 to 4,294,967,295
float4 byte
double8 byte
long double10 byte


Keywords in C

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.
A list of 32 keywords in the c language is given below:
autobreakcasecharconstcontinuedefaultdo
doubleelseenumexternfloatforgotoif
intlongregisterreturnshortsignedsizeofstatic
structswitchtypedefunionunsignedvoidvolatilewhile
We will learn about all the C language keywords later.

Keywords in C

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.
A list of 32 keywords in the c language is given below:
autobreakcasecharconstcontinuedefaultdo
doubleelseenumexternfloatforgotoif
intlongregisterreturnshortsignedsizeofstatic
structswitchtypedefunionunsignedvoidvolatilewhile
We will learn about all the C language keywords later.

C Operators

An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C language.
  • Arithmetic Operators
  • Relational Operators
  • Shift Operators
  • Logical Operators
  • Bitwise Operators
  • Ternary or Conditional Operators
  • Assignment Operator
  • Misc Operator
  • Precedence of Operators in C

    The precedence of operator species that which operator will be evaluated first and next. The associativity specifies the operator direction to be evaluated; it may be left to right or right to left.
  • Let's understand the precedence by the example given below:
    1. int value=10+20*10;  
    The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive operator).
    The precedence and associativity of C operators is given below:
    CategoryOperatorAssociativity
    Postfix() [] -> . ++ - -Left to right
    Unary+ - ! ~ ++ - - (type)* & sizeofRight to left
    Multiplicative* / %Left to right
    Additive+ -Left to right
    Shift<< >>Left to right
    Relational< <= > >=Left to right
    Equality== !=Left to right
    Bitwise AND&Left to right
    Bitwise XOR^Left to right
    Bitwise OR|Left to right
    Logical AND&&Left to right
    Logical OR||Left to right
    Conditional?:Right to left
    Assignment= += -= *= /= %=>>= <<= &= ^= |=Right to left
    Comma,Left to right

Comments in C

Comments in C language are used to provide information about lines of code. It is widely used for documenting code. There are 2 types of comments in the C language.
  1. Single Line Comments
  2. Multi-Line Comments

Single Line Comments

Single line comments are represented by double slash \\. Let's see an example of a single line comment in C.
  1. #include<stdio.h>    
  2. int main(){    
  3.     //printing information    
  4.     printf("Hello C");    
  5. return 0;  
  6. }      
Output:
Hello C
Even you can place the comment after the statement. For example:
  1. printf("Hello C");//printing information  

Mult Line Comments

Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code, but it can't be nested. Syntax:
  1. /*  
  2. code 
  3. to be commented 
  4. */  
Let's see an example of a multi-Line comment in C.
  1. #include<stdio.h>    
  2. int main(){    
  3.     /*printing information   
  4.       Multi-Line Comment*/  
  5.     printf("Hello C");    
  6. return 0;  
  7. }       
Output:
Hello C

Escape Sequence in C

An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.
It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape SequenceMeaning
\aAlarm or Beep
\bBackspace
\fForm Feed
\nNew Line
\rCarriage Return
\tTab (Horizontal)
\vVertical Tab
\\Backslash
\'Single Quote
\"Double Quote
\?Question Mark
\nnnoctal number
\xhhhexadecimal number
\0Null


Escape Sequence Example

  1. #include<stdio.h>    
  2. int main(){    
  3.      int number=50;  
  4.     printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");     
  5. return 0;  
  6. }     
Output:You
are
learning
'c' language
"Do you know C language"

Constants in C

A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc.
There are different types of constants in C programming.

List of Constants in C

ConstantExample
Decimal Constant10, 20, 450 etc.
Real or Floating-point Constant10.3, 20.2, 450.6 etc.
Octal Constant021, 033, 046 etc.
Hexadecimal Constant0x2a, 0x7b, 0xaa etc.
Character Constant'a', 'b', 'x' etc.
String Constant"c", "c program", "c in javatpoint" etc.

Constants in C

A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc.
There are different types of constants in C programming.

List of Constants in C

ConstantExample
Decimal Constant10, 20, 450 etc.
Real or Floating-point Constant10.3, 20.2, 450.6 etc.
Octal Constant021, 033, 046 etc.
Hexadecimal Constant0x2a, 0x7b, 0xaa etc.
Character Constant'a', 'b', 'x' etc.
String Constant"c", "c program", "c in javatpoint" etc.
2 ways to define constant in C
There are two ways to define constant in C programming.
  1. const keyword
  2. #define preprocessor

1) C const keyword

The const keyword is used to define constant in C programming.
  1. const float PI=3.14;  
Now, the value of PI variable can't be changed.
  1. #include<stdio.h>    
  2. int main(){    
  3.     const float PI=3.14;    
  4.     printf("The value of PI is: %f",PI);    
  5.     return 0;  
  6. }     
Output:
The value of PI is: 3.140000
If you try to change the the value of PI, it will render compile time error.
  1. #include<stdio.h>    
  2. int main(){    
  3. const float PI=3.14;     
  4. PI=4.5;    
  5. printf("The value of PI is: %f",PI);    
  6.     return 0;  
  7. }     
Output:
Compile Time Error: Cannot modify a const object

2) C #define preprocessor

The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive later.

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.
  • If statement
  • If-else statement
  • If else-if ladder
  • 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.
  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

if statement in c
Let's see a simple example of C language if statement.
  1. #include<stdio.h>    
  2. int main(){    
  3. int number=0;    
  4. printf("Enter a number:");    
  5. scanf("%d",&number);    
  6. if(number%2==0){    
  7. printf("%d is even number",number);    
  8. }    
  9. return 0;  
  10. }    

Output

Enter a number:4
4 is even number
enter a number:5

Program to find the largest number of the three.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int a, b, c;   
  5.      printf("Enter three numbers?");  
  6.     scanf("%d %d %d",&a,&b,&c);  
  7.     if(a>b && a>c)  
  8.     {  
  9.         printf("%d is largest",a);  
  10.     }  
  11.     if(b>a  && b > c)  
  12.     {  
  13.         printf("%d is largest",b);  
  14.     }  
  15.     if(c>a && c>b)  
  16.     {  
  17.         printf("%d is largest",c);  
  18.     }  
  19.     if(a == b && a == c)   
  20.     {  
  21.         printf("All are equal");   
  22.     }  
  23. }  
Output
Enter three numbers?
12 23 34
34 is largest 

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.
  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of the if-else statement in C

if-else statement in c
Let's see the simple example to check whether a number is even or odd using if-else statement in C language.
  1. #include<stdio.h>    
  2. int main(){    
  3. int number=0;    
  4. printf("enter a number:");    
  5. scanf("%d",&number);     
  6. if(number%2==0){    
  7. printf("%d is even number",number);    
  8. }    
  9. else{    
  10. printf("%d is odd number",number);    
  11. }     
  12. return 0;  
  13. }    

Output

enter a number:4
4 is even number
enter a number:5
5 is odd number

Program to check whether a person is eligible to vote or not.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int age;   
  5.     printf("Enter your age?");   
  6.     scanf("%d",&age);  
  7.     if(age>=18)  
  8.     {  
  9.         printf("You are eligible to vote...");   
  10.     }  
  11.     else   
  12.     {  
  13.         printf("Sorry ... you can't vote");   
  14.     }  
  15. }  
Output
Enter your age?18
You are eligible to vote...
Enter your age?13
Sorry ... you can't vote

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.
  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

if-else-if ladder statement in c
The example of an if-else-if statement in C language is given below.
  1. #include<stdio.h>    
  2. int main(){    
  3. int number=0;    
  4. printf("enter a number:");    
  5. scanf("%d",&number);     
  6. if(number==10){    
  7. printf("number is equals to 10");    
  8. }    
  9. else if(number==50){    
  10. printf("number is equal to 50");    
  11. }    
  12. else if(number==100){    
  13. printf("number is equal to 100");    
  14. }    
  15. else{    
  16. printf("number is not equal to 10, 50 or 100");    
  17. }    
  18. return 0;  
  19. }    

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

Program to calculate the grade of the student according to the specified marks.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int marks;   
  5.     printf("Enter your marks?");  
  6.     scanf("%d",&marks);   
  7.     if(marks > 85 && marks <= 100)  
  8.     {  
  9.         printf("Congrats ! you scored grade A ...");   
  10.     }  
  11.     else if (marks > 60 && marks <= 85)   
  12.     {  
  13.         printf("You scored grade B + ...");  
  14.     }  
  15.     else if (marks > 40 && marks <= 60)   
  16.     {  
  17.         printf("You scored grade B ...");  
  18.     }  
  19.     else if (marks > 30 && marks <= 40)   
  20.     {  
  21.         printf("You scored grade C ...");   
  22.     }  
  23.     else   
  24.     {  
  25.         printf("Sorry you are fail ...");   
  26.     }  
  27. }  
Output
Enter your marks?10
Sorry you are fail ...
Enter your marks?40
You scored grade C ...
Enter your marks?90
Congrats ! you scored grade A ...

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:
  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    
  13. Rules for switch statement in C language

    1) The switch expression must be of an integer or character type.
  14. 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.
    1. int x,y,z;  
    2. char a,b;  
    3. float f;  
    Valid SwitchInvalid SwitchValid CaseInvalid Case
    switch(x)switch(f)case 3;case 2.5;
    switch(x>y)switch(x+2.5)case 'a';case x;
    switch(a+b-2)case 1+2;case x+2;
    switch(func(x,y))case 'x'>'y';case 1,2,3;

    Flowchart of switch statement in C

    flow of switch statement in c

    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.
    Let's see a simple example of c language switch statement.
    1. #include<stdio.h>  
    2. int main(){    
    3. int number=0;     
    4. printf("enter a number:");    
    5. scanf("%d",&number);    
    6. switch(number){    
    7. case 10:    
    8. printf("number is equals to 10");    
    9. break;    
    10. case 50:    
    11. printf("number is equal to 50");    
    12. break;    
    13. case 100:    
    14. printf("number is equal to 100");    
    15. break;    
    16. default:    
    17. printf("number is not equal to 10, 50 or 100");    
    18. }    
    19. return 0;  
    20. }    

    Output

    enter a number:4
    number is not equal to 10, 50 or 100
    
    enter a number:50
    number is equal to 50
    

    Switch case example 2

    1. #include <stdio.h>  
    2. int main()  
    3. {  
    4.     int x = 10, y = 5;   
    5.     switch(x>y && x+y>0)  
    6.     {  
    7.         case 1:   
    8.         printf("hi");  
    9.         break;   
    10.         case 0:   
    11.         printf("bye");  
    12.         break;  
    13.         default:   
    14.         printf(" Hello bye ");  
    15.     }   
    16.           
    17. }  
    Output
    hi 
    

    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.
    Let's try to understand the fall through state of switch statement by the example given below.
    1. #include<stdio.h>  
    2. int main(){    
    3. int number=0;    
    4.   
    5. printf("enter a number:");  
    6. scanf("%d",&number);  
    7.   
    8. switch(number){  
    9. case 10:  
    10. printf("number is equal to 10\n");  
    11. case 50:  
    12. printf("number is equal to 50\n");  
    13. case 100:  
    14. printf("number is equal to 100\n");  
    15. default:  
    16. printf("number is not equal to 10, 50 or 100");  
    17. }  
    18. return 0;  
    19. }    

    Output

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

    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. Consider the following example.
    1. #include <stdio.h>  
    2. int main () {  
    3.   
    4.    int i = 10;  
    5.    int j = 20;  
    6.    
    7.    switch(i) {  
    8.      
    9.       case 10:   
    10.          printf("the value of i evaluated in outer switch: %d\n",i);  
    11.       case 20:  
    12.          switch(j) {  
    13.             case 20:  
    14.                printf("The value of j evaluated in nested switch: %d\n",j);  
    15.          }  
    16.    }  
    17.      
    18.    printf("Exact value of i is : %d\n", i );  
    19.    printf("Exact value of j is : %d\n", j );  
    20.    
    21.    return 0;  
    22. }  
    Output
    the value of i evaluated in outer switch: 10
    The value of j evaluated in nested switch: 20
    Exact value of i is : 10
    Exact value of j is : 20 

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.
2) 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:
  1. do{  
  2. //code to be executed  
  3. }while(condition);  

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:
  1. while(condition){  
  2. //code to be executed  
  3. }  

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:
  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

do while loop in C

The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least once. The do-while loop is mostly used in menu-driven programs where the termination condition depends upon the end user.

do while loop syntax

The syntax of the C language do-while loop is given below:
  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Example 1

  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. void main ()  
  4. {  
  5.     char c;  
  6.     int choice,dummy;    
  7.     do{  
  8.     printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");  
  9.     scanf("%d",&choice);  
  10.     switch(choice)  
  11.     {  
  12.         case 1 :   
  13.         printf("Hello");   
  14.         break;  
  15.         case 2:    
  16.         printf("Javatpoint");  
  17.         break;  
  18.         case 3:  
  19.         exit(0);   
  20.         break;  
  21.         default:   
  22.         printf("please enter valid choice");      
  23.     }  
  24.     printf("do you want to enter more?");   
  25.     scanf("%d",&dummy);  
  26.     scanf("%c",&c);  
  27.     }while(c=='y');  
  28. }  

Output

1. Print Hello
2. Print Javatpoint
3. Exit
1
Hello
do you want to enter more?
y

1. Print Hello
2. Print Javatpoint
3. Exit
2
Javatpoint
do you want to enter more?
n

Flowchart of do while loop

flowchart of do while loop in c language

do while loop in C

The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least once. The do-while loop is mostly used in menu-driven programs where the termination condition depends upon the end user.

do while loop syntax

The syntax of the C language do-while loop is given below:
  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Example 1

  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. void main ()  
  4. {  
  5.     char c;  
  6.     int choice,dummy;    
  7.     do{  
  8.     printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");  
  9.     scanf("%d",&choice);  
  10.     switch(choice)  
  11.     {  
  12.         case 1 :   
  13.         printf("Hello");   
  14.         break;  
  15.         case 2:    
  16.         printf("Javatpoint");  
  17.         break;  
  18.         case 3:  
  19.         exit(0);   
  20.         break;  
  21.         default:   
  22.         printf("please enter valid choice");      
  23.     }  
  24.     printf("do you want to enter more?");   
  25.     scanf("%d",&dummy);  
  26.     scanf("%c",&c);  
  27.     }while(c=='y');  
  28. }  

Output

1. Print Hello
2. Print Javatpoint
3. Exit
1
Hello
do you want to enter more?
y

1. Print Hello
2. Print Javatpoint
3. Exit
2
Javatpoint
do you want to enter more?
n

Flowchart of do while loop

flowchart of do while loop in c language


do while example

There is given the simple program of c language do while loop where we are printing the table of 1.
  1. #include<stdio.h>  
  2. int main(){    
  3. int i=1;      
  4. do{    
  5. printf("%d \n",i);    
  6. i++;    
  7. }while(i<=10);   
  8. return 0;  
  9. }     

Output

1
2
3
4
5
6
7
8
9
10

Program to print table for the given number using do while loop

  1. #include<stdio.h>  
  2. int main(){    
  3. int i=1,number=0;    
  4. printf("Enter a number: ");    
  5. scanf("%d",&number);    
  6. do{    
  7. printf("%d \n",(number*i));    
  8. i++;    
  9. }while(i<=10);    
  10. return 0;  
  11. }    

Output

Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100

Infinitive do while loop

The do-while loop will run infinite times if we pass any non-zero value as the conditional expression.
  1. do{  
  2. //statement  
  3. }while(1);  

while loop in C

While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance.

Syntax of while loop in C language

The syntax of while loop in c language is given below:
  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart of while loop in C

flowchart of c while loop

Example of the while loop in C language

Let's see the simple program of while loop that prints table of 1.
  1. #include<stdio.h>  
  2. int main(){    
  3. int i=1;      
  4. while(i<=10){      
  5. printf("%d \n",i);      
  6. i++;      
  7. }  
  8. return 0;  
  9. }    

Output

1
2
3
4
5
6
7
8
9
10

Program to print table for the given number using while loop in C

  1. #include<stdio.h>  
  2. int main(){    
  3. int i=1,number=0,b=9;    
  4. printf("Enter a number: ");    
  5. scanf("%d",&number);    
  6. while(i<=10){    
  7. printf("%d \n",(number*i));    
  8. i++;    
  9. }    
  10. return 0;  
  11. }   

Output

Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
500
600
700
800
900
1000

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.

Example 1

  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     int j = 1;  
  5.     while(j+=2,j<=10)  
  6.     {  
  7.         printf("%d ",j);   
  8.     }  
  9.     printf("%d",j);  
  10. }  

Output

3 5 7 9 11

Example 2

  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     while()  
  5.     {  
  6.         printf("hello Javatpoint");   
  7.     }  
  8. }  

Output

compile time error: while loop can't be empty 

Example 3

  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     int x = 10, y = 2;  
  5.     while(x+y-1)  
  6.     {  
  7.         printf("%d %d",x--,y--);  
  8.     }  
  9. }  

Output

infinite loop 

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.
  1. while(1){  
  2. //statement  
  3. }  

for loop in C

The for loop in C language is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like the array and linked list.

Syntax of for loop in C

The syntax of for loop in c language is given below:
  1. for(Expression 1; Expression 2; Expression 3){  
  2. //code to be executed  
  3. }  

Flowchart of for loop in C

for loop in c language flowchart

C for loop Examples

Let's see the simple program of for loop that prints table of 1.
  1. #include<stdio.h>  
  2. int main(){  
  3. int i=0;        
  4. for(i=1;i<=10;i++){      
  5. printf("%d \n",i);      
  6. }     
  7. return 0;  
  8. }     

Output

1
2
3
4
5
6
7
8
9
10

C Program: Print table for the given number using C for loop

  1. #include<stdio.h>  
  2. int main(){  
  3. int i=1,number=0;      
  4. printf("Enter a number: ");    
  5. scanf("%d",&number);    
  6. for(i=1;i<=10;i++){      
  7. printf("%d \n",(number*i));    
  8. }    
  9. return 0;  
  10. }    

Output

Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Enter a number: 1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

Properties of Expression 1

  • The expression represents the initialization of the loop variable.
  • We can initialize more than one variable in Expression 1.
  • Expression 1 is optional.
  • In C, we can not declare the variables in Expression 1. However, It can be an exception in some compilers.
Example 1
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int a,b,c;  
  5.     for(a=0,b=12,c=23;a<2;a++)  
  6.     {  
  7.         printf("%d ",a+b+c);  
  8.     }  
  9. }  
Output
35 36
Example 2
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int i=1;  
  5.     for(;i<5;i++)  
  6.     {  
  7.         printf("%d ",i);  
  8.     }  
  9. }  
Output
1 2 3 4

Properties of Expression 2

  • Expression 2 is a conditional expression. It checks for a specific condition to be satisfied. If it is not, the loop is terminated.
  • Expression 2 can have more than one condition. However, the loop will iterate until the last condition becomes false. Other conditions will be treated as statements.
  • Expression 2 is optional.
  • Expression 2 can perform the task of expression 1 and expression 3. That is, we can initialize the variable as well as update the loop variable in expression 2 itself.
  • We can pass zero or non-zero value in expression 2. However, in C, any non-zero value is true, and zero is false by default.
Example 1
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int i;  
  5.     for(i=0;i<=4;i++)  
  6.     {  
  7.         printf("%d ",i);  
  8.     }  
  9. }  
output
0 1 2 3 4
Example 2
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int i,j,k;  
  5.     for(i=0,j=0,k=0;i<4,k<8,j<10;i++)  
  6.     {  
  7.         printf("%d %d %d\n",i,j,k);  
  8.         j+=2;  
  9.         k+=3;  
  10.     }  
  11. }  
Output
0 0 0
1 2 3
2 4 6
3 6 9
4 8 12  
Example 3
  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int i;  
  5.     for(i=0;;i++)  
  6.     {  
  7.         printf("%d",i);  
  8.     }  
  9. }  
Output
infinite loop

Properties of Expression 3

  • Expression 3 is used to update the loop variable.
  • We can update more than one variable at the same time.
  • Expression 3 is optional.
Example 1
  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     int i=0,j=2;  
  5.     for(i = 0;i<5;i++,j=j+2)  
  6.     {  
  7.         printf("%d %d\n",i,j);  
  8.     }  
  9. }  
Output
0 2
1 4
2 6
3 8
4 10    

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. Consider the following example.
  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     int i;  
  5.     for(i=0;i<10;i++)  
  6.     {  
  7.         int i = 20;  
  8.         printf("%d ",i);  
  9.     }  
  10. }  
Output
20 20 20 20 20 20 20 20 20 20   

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.
  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     for(;;)  
  5.     {  
  6.         printf("welcome to javatpoint");  
  7.     }  
  8. }  
If you run this program, you will see above statement infinite times.

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:

  1. //loop or switch case   
  2. break;  

Flowchart of break in c

c language break statement flowchart

Example

  1. #include<stdio.h>  
  2. #include<stdlib.h>  
  3. void main ()  
  4. {  
  5.     int i;  
  6.     for(i = 0; i<10; i++)  
  7.     {  
  8.         printf("%d ",i);  
  9.         if(i == 5)  
  10.         break;  
  11.     }  
  12.     printf("came outside of loop i = %d",i);  
  13.       
  14. }  

Output

0 1 2 3 4 5 came outside of loop i = 5

Example of C break statement with switch case

Click here to see the example of C break with the switch statement.

C break statement with the nested loop

In such case, it breaks only the inner loop, but not outer loop.
  1. #include<stdio.h>  
  2. int main(){  
  3. int i=1,j=1;//initializing a local variable    
  4. for(i=1;i<=3;i++){      
  5. for(j=1;j<=3;j++){    
  6. printf("%d &d\n",i,j);    
  7. if(i==2 && j==2){    
  8. break;//will break loop of j only    
  9. }    
  10. }//end of for loop    
  11. return 0;  
  12. }    

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
As you can see the output on the console, 2 3 is not printed because there is a break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 are printed because the break statement is used to break the inner loop only.

break statement with while loop

Consider the following example to use break statement inside while loop.
  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     int i = 0;  
  5.     while(1)  
  6.     {  
  7.         printf("%d  ",i);  
  8.         i++;  
  9.         if(i == 10)  
  10.         break;   
  11.     }  
  12.     printf("came out of while loop");  
  13. }  
Output
0  1  2  3  4  5  6  7  8  9  came out of while loop 

break statement with do-while loop

Consider the following example to use the break statement with a do-while loop.
  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.    int n=2,i,choice;  
  5.    do  
  6.    {  
  7.        i=1;  
  8.        while(i<=10)  
  9.        {  
  10.            printf("%d X %d = %d\n",n,i,n*i);  
  11.            i++;  
  12.        }  
  13.        printf("do you want to continue with the table of %d , enter any non-zero value to continue.",n+1);  
  14.        scanf("%d",&choice);  
  15.     if(choice == 0)  
  16.        {  
  17.            break;  
  18.        }  
  19.        n++;  
  20.    }while(1);  
  21. }  
Output
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
do you want to continue with the table of 3 , enter any non-zero value to continue.1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
do you want to continue with the table of 4 , enter any non-zero value to continue.0

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:

  1. //loop statements  
  2. continue;  
  3. //some lines of the code which is to be skipped  

Continue statement example 1

  1. #include<stdio.h>  
  2. void main ()  
  3. {  
  4.     int i = 0;   
  5.     while(i!=10)  
  6.     {  
  7.         printf("%d", i);   
  8.         continue;   
  9.         i++;  
  10.     }  
  11. }  

Output

 infinite loop

Continue statement example 2

  1. #include<stdio.h>  
  2. int main(){  
  3. int i=1;//initializing a local variable       
  4. //starting a loop from 1 to 10    
  5. for(i=1;i<=10;i++){      
  6. if(i==5){//if value of i is equal to 5, it will continue the loop    
  7. continue;    
  8. }    
  9. printf("%d \n",i);    
  10. }//end of for loop    
  11. return 0;  
  12. }    

Output

1
2
3
4
6
7
8
9
10
As you can see, 5 is not printed on the console because loop is continued at i==5.

C continue statement with inner loop

In such case, C continue statement continues only inner loop, but not outer loop.
  1. #include<stdio.h>  
  2. int main(){  
  3. int i=1,j=1;//initializing a local variable    
  4. for(i=1;i<=3;i++){      
  5. for(j=1;j<=3;j++){    
  6. if(i==2 && j==2){    
  7. continue;//will continue loop of j only    
  8. }    
  9. printf("%d %d\n",i,j);    
  10. }    
  11. }//end of for loop    
  12. return 0;  
  13. }    

Output

1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3

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:
  1. label:   
  2. //some part of the code;   
  3. goto label;  

goto example

Let's see a simple example to use goto statement in C language.
  1. #include <stdio.h>  
  2. int main()   
  3. {  
  4.   int num,i=1;   
  5.   printf("Enter the number whose table you want to print?");   
  6.   scanf("%d",&num);  
  7.   table:   
  8.   printf("%d x %d = %d\n",num,i,num*i);  
  9.   i++;  
  10.   if(i<=10)  
  11.   goto table;    
  12. }  
Output:
Enter the number whose table you want to print?10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

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. Consider the following example.
  1. #include <stdio.h>  
  2. int main()   
  3. {  
  4.   int i, j, k;    
  5.   for(i=0;i<10;i++)  
  6.   {  
  7.     for(j=0;j<5;j++)  
  8.     {  
  9.       for(k=0;k<3;k++)  
  10.       {  
  11.         printf("%d %d %d\n",i,j,k);  
  12.         if(j == 3)  
  13.         {  
  14.           goto out;   
  15.         }  
  16.       }  
  17.     }  
  18.   }  
  19.   out:   
  20.   printf("came out of the loop");   
  21. }  
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
0 3 0
came out of the loop

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:
  1. (type)value;      

Note: It is always recommended to convert the lower value to higher for avoiding data loss.

Without Type Casting:
  1. int f= 9/4;  
  2. printf("f : %d\n", f );//Output: 2  
With Type Casting:
  1. float f=(float) 9/4;  
  2. printf("f : %f\n", f );//Output: 2.250000  

Type Casting example

Let's see a simple example to cast int value into the float.
  1. #include<stdio.h>  
  2. int main(){  
  3. float f= (float)9/4;    
  4. printf("f : %f\n", f );    
  5. return 0;  
  6. }      
Output:
f : 2.250000

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.

    SNC function aspectsSyntax
    1Function declarationreturn_type function_name (argument list);
    2Function callfunction_name (argument_list)
    3Function definitionreturn_type function_name (argument list) {function body;}
    The syntax of creating function in c language is given below:
    1. return_type function_name(data_type parameter...){  
    2. //code to be executed  
    3. }  

    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.
    C Function

    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.
    Let's see a simple example of C function that doesn't return any value from the function.
    Example without return value:
    1. void hello(){  
    2. printf("hello c");  
    3. }  
    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:
    1. int get(){  
    2. return 10;  
    3. }  
    In the above example, we have to return 10 as a value, so the return type is int. If you want to return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of the method.
    1. float get(){  
    2. return 10.2;  
    3. }  
    Now, you need to call the function, to get the value of the function.

    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

    Example for Function without argument and return value

    Example 1

    1. #include<stdio.h>  
    2. void printName();  
    3. void main ()  
    4. {  
    5.     printf("Hello ");  
    6.     printName();  
    7. }  
    8. void printName()  
    9. {  
    10.     printf("Javatpoint");  
    11. }  
    Output
    Hello Javatpoint
    

    Example 2

    1. #include<stdio.h>  
    2. void sum();  
    3. void main()  
    4. {  
    5.     printf("\nGoing to calculate the sum of two numbers:");  
    6.     sum();  
    7. }  
    8. void sum()  
    9. {  
    10.     int a,b;   
    11.     printf("\nEnter two numbers");  
    12.     scanf("%d %d",&a,&b);   
    13.     printf("The sum is %d",a+b);  
    14. }  
    Output
    Going to calculate the sum of two numbers:
    
    Enter two numbers 10 
    24 
    
    The sum is 34
    

    Example for Function without argument and with return value

    Example 1

    1. #include<stdio.h>  
    2. int sum();  
    3. void main()  
    4. {  
    5.     int result;   
    6.     printf("\nGoing to calculate the sum of two numbers:");  
    7.     result = sum();  
    8.     printf("%d",result);  
    9. }  
    10. int sum()  
    11. {  
    12.     int a,b;   
    13.     printf("\nEnter two numbers");  
    14.     scanf("%d %d",&a,&b);  
    15.     return a+b;   
    16. }  
    Output
    Going to calculate the sum of two numbers:
    
    Enter two numbers 10 
    24 
    
    The sum is 34
    

    Example 2: program to calculate the area of the square

    1. #include<stdio.h>  
    2. int sum();  
    3. void main()  
    4. {  
    5.     printf("Going to calculate the area of the square\n");  
    6.     float area = square();  
    7.     printf("The area of the square: %f\n",area);  
    8. }  
    9. int square()  
    10. {  
    11.     float side;  
    12.     printf("Enter the length of the side in meters: ");  
    13.     scanf("%f",&side);  
    14.     return side * side;  
    15. }  
    Output
    Going to calculate the area of the square 
    Enter the length of the side in meters: 10 
    The area of the square: 100.000000
    

    Example for Function with argument and without return value

    Example 1

    1. #include<stdio.h>  
    2. void sum(intint);  
    3. void main()  
    4. {  
    5.     int a,b,result;   
    6.     printf("\nGoing to calculate the sum of two numbers:");  
    7.     printf("\nEnter two numbers:");  
    8.     scanf("%d %d",&a,&b);  
    9.     sum(a,b);  
    10. }  
    11. void sum(int a, int b)  
    12. {  
    13.     printf("\nThe sum is %d",a+b);      
    14. }  
    Output
    Going to calculate the sum of two numbers:
    
    Enter two numbers 10 
    24 
    
    The sum is 34
    

    Example 2: program to calculate the average of five numbers.

    1. #include<stdio.h>  
    2. void average(intintintintint);  
    3. void main()  
    4. {  
    5.     int a,b,c,d,e;   
    6.     printf("\nGoing to calculate the average of five numbers:");  
    7.     printf("\nEnter five numbers:");  
    8.     scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);  
    9.     average(a,b,c,d,e);  
    10. }  
    11. void average(int a, int b, int c, int d, int e)  
    12. {  
    13.     float avg;   
    14.     avg = (a+b+c+d+e)/5;   
    15.     printf("The average of given five numbers : %f",avg);  
    16. }  
    Output
    Going to calculate the average of five numbers:
    Enter five numbers:10 
    20
    30
    40
    50
    The average of given five numbers : 30.000000
    

    Example for Function with argument and with return value

    Example 1

    1. #include<stdio.h>  
    2. int sum(intint);  
    3. void main()  
    4. {  
    5.     int a,b,result;   
    6.     printf("\nGoing to calculate the sum of two numbers:");  
    7.     printf("\nEnter two numbers:");  
    8.     scanf("%d %d",&a,&b);  
    9.     result = sum(a,b);  
    10.     printf("\nThe sum is : %d",result);  
    11. }  
    12. int sum(int a, int b)  
    13. {  
    14.     return a+b;  
    15. }  
    Output
    Going to calculate the sum of two numbers:
    Enter two numbers:10
    20 
    The sum is : 30   
    

    Example 2: Program to check whether a number is even or odd

    1. #include<stdio.h>  
    2. int even_odd(int);  
    3. void main()  
    4. {  
    5.  int n,flag=0;  
    6.  printf("\nGoing to check whether a number is even or odd");  
    7.  printf("\nEnter the number: ");  
    8.  scanf("%d",&n);  
    9.  flag = even_odd(n);  
    10.  if(flag == 0)  
    11.  {  
    12.     printf("\nThe number is odd");  
    13.  }  
    14.  else   
    15.  {  
    16.     printf("\nThe number is even");  
    17.  }  
    18. }  
    19. int even_odd(int n)  
    20. {  
    21.     if(n%2 == 0)  
    22.     {  
    23.         return 1;  
    24.     }  
    25.     else   
    26.     {  
    27.         return 0;  
    28.     }  
    29. }  
    Output
    Going to check whether a number is even or odd
    Enter the number: 100
    The number is even
    

    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.
    The list of mostly used header files is given in the following table.
    SNHeader fileDescription
    1stdio.hThis is a standard input/output header file. It contains all the library functions regarding standard input/output.
    2conio.hThis is a console input/output header file.
    3string.hIt contains all string related library functions like gets(), puts(),etc.
    4stdlib.hThis header file contains all the general library functions like malloc(), calloc(), exit(), etc.
    5math.hThis header file contains all the math operations related functions like sqrt(), pow(), etc.
    6time.hThis header file contains all the time-related functions.
    7ctype.hThis header file contains all character handling functions.
    8stdarg.hVariable argument functions are defined in this header file.
    9signal.hAll the signal handling functions are defined in this header file.
    10setjmp.hThis file contains all the jump functions.
    11locale.hThis file contains locale functions.
    12errno.hThis file contains error handling functions.
    13assert.hThis file contains diagnostics functions.


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 and call by reference in c
Let's understand call by value and call by reference in c language one by one.

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.
Let's try to understand the concept of call by value in c language by the example given below:
  1. #include<stdio.h>  
  2. void change(int num) {    
  3.     printf("Before adding value inside function num=%d \n",num);    
  4.     num=num+100;    
  5.     printf("After adding value inside function num=%d \n", num);    
  6. }    
  7. int main() {    
  8.     int x=100;    
  9.     printf("Before function call x=%d \n", x);    
  10.     change(x);//passing value in function    
  11.     printf("After function call x=%d \n", x);    
  12. return 0;  
  13. }    

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by Value Example: Swapping the values of the two variables

  1. #include <stdio.h>  
  2. void swap(int , int); //prototype of the function   
  3. int main()  
  4. {  
  5.     int a = 10;  
  6.     int b = 20;   
  7.     printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main  
  8.     swap(a,b);  
  9.     printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not change by changing the formal parameters in call by value, a = 10, b = 20  
  10. }  
  11. void swap (int a, int b)  
  12. {  
  13.     int temp;   
  14.     temp = a;  
  15.     a=b;  
  16.     b=temp;  
  17.     printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 10   
  18. }  

Output

Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20  

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.
Consider the following example for the call by reference.
  1. #include<stdio.h>  
  2. void change(int *num) {    
  3.     printf("Before adding value inside function num=%d \n",*num);    
  4.     (*num) += 100;    
  5.     printf("After adding value inside function num=%d \n", *num);    
  6. }      
  7. int main() {    
  8.     int x=100;    
  9.     printf("Before function call x=%d \n", x);    
  10.     change(&x);//passing reference in function    
  11.     printf("After function call x=%d \n", x);    
  12. return 0;  
  13. }    

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Call by reference Example: Swapping the values of the two variables

  1. #include <stdio.h>  
  2. void swap(int *, int *); //prototype of the function   
  3. int main()  
  4. {  
  5.     int a = 10;  
  6.     int b = 20;   
  7.     printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main  
  8.     swap(&a,&b);  
  9.     printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do change in call by reference, a = 10, b = 20  
  10. }  
  11. void swap (int *a, int *b)  
  12. {  
  13.     int temp;   
  14.     temp = *a;  
  15.     *a=*b;  
  16.     *b=temp;  
  17.     printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b = 10   
  18. }  

Output

Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10  

Difference between call by value and call by reference in c

No.Call by valueCall by reference
1A copy of the value is passed into the functionAn address of value is passed into the function
2Changes made inside the function is limited to the function only. The values of the actual parameters do not change by changing the formal parameters.Changes made inside the function validate outside of the function also. The values of the actual parameters do change by changing the formal parameters.
3Actual and formal arguments are created at the different memory locationActual and formal arguments are created at the same memory location

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, Fibacci , factorial findinong, etc.In the following example, recursion is used to calculate the factorial of a number.
  1. #include <stdio.h>  
  2. int fact (int);  
  3. int main()  
  4. {  
  5.     int n,f;  
  6.     printf("Enter the number whose factorial you want to calculate?");  
  7.     scanf("%d",&n);  
  8.     f = fact(n);  
  9.     printf("factorial = %d",f);  
  10. }  
  11. int fact(int n)  
  12. {  
  13.     if (n==0)  
  14.     {  
  15.         return 0;  
  16.     }  
  17.     else if ( n == 1)  
  18.     {  
  19.         return 1;  
  20.     }  
  21.     else   
  22.     {  
  23.         return n*fact(n-1);  
  24.     }  
  25. }  

Output

Enter the number whose factorial you want to calculate?5
factorial = 120 

We can understand the above program of the recursive method call by the figure given below:

C Language

C Language History of C Language History of C language  is interesting to know. Here we are going to discuss a brief history of th...