(PDF) C Programming Language Tutorial
(PDF) C Programming Language Tutorial
C language Tutorial with programming approach for beginners and professionals, helps you
to understand the C language tutorial easily. Our C tutorial explains each topic with
programs.
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.
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language
1) C as a mother language
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and
most of the programming languages follow C syntax, for example, C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that are
being used in many languages like C++, Java, C#, etc.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.
A procedural language breaks the program into functions, data structures, etc.
In the C language, we break the program into parts using functions. It makes the program
easier to understand and modify.
C Program
In this tutorial, all C programs are given with C compiler so that you can quickly change the
C program code.
File: main.c
1. #include <stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5. }
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.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Let's see the programming languages that were developed before C language.
Features of C Language
C is the widely used language. It provides many features that 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 functions, data types, etc.
5) Rich Library
C 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.
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.
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.
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 can view the user screen any time by pressing the alt+f5 keys.
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.
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() function
The printf() function is used for output. It prints the given statement to the console.
1. printf("format string",argument_list);
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.
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:9
enter second number:9
sum of 2 numbers:18
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.
1. type variable_list;
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;
2. int _ab;
3. int a30;
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.
1. void function1(){
2. int x=10;//local variable
3. }
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.
Static Variable
A variable that is declared with the static keyword is called static variable.
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.
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.
float 4 byte
double 8 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.
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.
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator
o 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.
1. int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before
+ (additive operator).
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. #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. /*
2. code
3. to be commented
4. */
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.
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\? Question Mark
\0 Null
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.
List of Constants in C
Constant Example
1. const keyword
2. #define preprocessor
1) C const keyword
The const keyword is used to define constant in C programming.
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:
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:
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.
o If statement
o If-else statement
o If else-if ladder
o 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
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
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
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
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
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
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.
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. }
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;
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
Output hi
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 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
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).
1. do{
2. //code to be executed
3. }while(condition);
Flowchart and Example of do-while loop
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.
1. while(condition){
2. //code to be executed
3. }
Flowchart and Example of while loop
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.
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.
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
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
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.
1. while(condition){
2. //code to be executed
3. }
Flowchart of while loop in C
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
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
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.
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
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
o Expression 2 is a conditional expression. It checks for a specific condition to be
satisfied. If it is not, the loop is terminated.
o 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.
o Expression 2 is optional.
o 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.
o 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
o Expression 3 is used to update the loop variable.
o We can update more than one variable at the same time.
o 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:
Syntax:
1. //loop or switch case
2. break;
Flowchart of break in c
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
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
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
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
As you can see, 2 2 is not printed on the console because inner loop is continued at i==2
and j==2.
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:
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
next →← prev
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.
1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2
With Type Casting:
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.250000C 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.
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
Function Aspects
There are three aspects of a C function.
o 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.
o 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.
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.
Let's see a simple example of C function that doesn't return any value from the function.
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.
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.
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
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
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
The sum is 34
Example 2: program to calculate the average of five numbers.
1. #include<stdio.h>
2. void average(int, int, int, int, int);
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
Output
Output
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.
SN Header Description
file
4 stdlib.h This header file contains all the general library functions like
malloc(), calloc(), exit(), etc.
5 math.h This header file contains all the math operations related
functions like sqrt(), pow(), etc.
6 time.h This header file contains all the time-related functions.
9 signal.h All the signal handling functions are defined in this header
file.
Call by value in C
o 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.
o In call by value method, we can not modify the value of the actual parameter by the
formal parameter.
o 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.
o 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 reference in C
o In call by reference, the address of the variable is passed into the function call as the
actual parameter.
o The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
o 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.
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 pa
rameters 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 paramete
rs, 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
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.
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:
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.
1. if (test_for_base)
2. {
3. return some_value;
4. }
5. else if (test_for_another_base)
6. {
7. return some_another_value;
8. }
9. else
10. {
11. // Statements;
12. recursive call;
13. }
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (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 fibonacci(n-1)+fibonacci(n-2);
24. }
25. }
Output
Enter the value of n?12
144
Let us consider the following example to understand the memory allocation of the recursive
functions.
Explanation
Let us examine this recursive function for n = 4. First, all the stacks are maintained which
prints the corresponding value of n until n becomes 0, Once the termination condition is
reached, the stacks get destroyed one by one by returning 0 to its calling stack. Consider
the following image for more information regarding the stack trace for the recursive
functions.
Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location, and
initial value of a variable. There are four types of storage classes in C
o Automatic
o External
o Static
o Register
extern RAM Zero Global Till the end of the main program Maybe d
anywhere in the program
static RAM Zero Local Till the end of the main program, Retains
between multiple functions call
Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they are
defined.
The scope of the automatic variables is limited to the block in which they are
defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
8. return 0;
9. }
Output:
Output:
11 20 20 20 11
Static
o The variables defined as static specifier can hold their value between the multiple
function calls.
o Static local variables are visible only to the function or the block in which they are
defined.
o A same static variable can be declared many times but can be assigned at only one
time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has declared.
o The keyword used to define static variable is static.
Example 1
1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }
Output:
0 0 0.000000 (null)
Example 2
1. #include<stdio.h>
2. void sum()
3. {
4. static int a = 10;
5. static int b = 24;
6. printf("%d %d \n",a,b);
7. a++;
8. b++;
9. }
10. void main()
11. {
12. int i;
13. for(i = 0; i< 3; i++)
14. {
15. sum(); // The static variables holds their value between multiple function calls.
16. }
17. }
Output:
10 24
11 25
12 26
Register
o The variables defined as the register is allocated the memory into the CPU registers
depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for the
register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU
register. However, it is compiler?s choice whether or not; the variables can be stored
in the register.
o We can store pointers into the register, i.e., a register can store the address of a
variable.
o Static variables can not be stored into the register since we can not use more than
one storage specifier for the same variable.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The initial default valu
e of a is 0.
5. printf("%d",a);
6. }
Output:
0
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. register int a = 0;
5. printf("%u",&a); // This will give a compile time error since we can not access the address o
f a register variable.
6. }
Output:
External
o The external storage class is used to tell the compiler that the variable defined as
extern is declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only declaration
and intended to specify that the variable is declared elsewhere in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
o An external variable can be declared many times but can be initialized at only once.
o If a variable is declared as external then the compiler searches for that variable to be
initialized somewhere in the program which may be extern or static. If it is not, then
the compiler will show an error.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }
Output
Output
0
Example 3
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a = 0; // this will show a compiler error since we can not use extern and initializ
er at same time
6. printf("%d",a);
7. }
Output
compile time error
main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
extern int a = 0;
Example 4
1. #include <stdio.h>
2. int main()
3. {
4. extern int a; // Compiler will search here for a variable a defined and initialized somewhere
in the pogram or not.
5. printf("%d",a);
6. }
7. int a = 20;
Output
20
Example 5
1. extern int a;
2. int a = 10;
3. #include <stdio.h>
4. int main()
5. {
6. printf("%d",a);
7. }
8. int a = 20; // compiler will show an error at this line
Output
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
o Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
o Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
o 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
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.
1. data_type array_name[array_size];
1. int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the 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.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
Output
80
60
70
85
75
1. 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.
1. int marks[]={20,30,40,50,60};
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output
20
30
40
50
60
1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }
Program to print the largest and second largest
element of the array.
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28. }
1. data_type array_name[rows][columns];
1. int twodimen[4][3];
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.
1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
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.
1. functionname(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:
Second way:
Third way:
You can also use the concept of a pointer. In pointer chapter, we will learn about it.
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.
1. int * Function_name() {
2. //some statements;
3. return array_type;
4. }
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.
1. #include<stdio.h>
2. int* Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. int *p = Bubble_Sort(arr), i;
7. printf("printing sorted elements ...\n");
8. for(i=0;i<10;i++)
9. {
10. printf("%d\n",*(p+i));
11. }
12. }
13. int* Bubble_Sort(int a[]) //array a[] points to arr.
14. {
15. int i, j,temp;
16. for(i = 0; i<10; i++)
17. {
18. for(j = i+1; j<10; j++)
19. {
20. if(a[j] < a[i])
21. {
22. temp = a[i];
23. a[i] = a[j];
24. a[j] = temp;
25. }
26. }
27. }
28. return a;
29. }
Output
Printing Sorted Element List ...
7
9
10
12
23
23
34
44
78
101
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.
1. int n = 10;
2. 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.
Pointer Example
An example of using pointers to print the address and value is given below.
As you can see in the above figure, pointer variable stores the address of number variable,
i.e., fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Let's see the pointer example as explained for the above figure.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %x \n",p); // p contains the address of the number therefore
printing p gives the address of number.
7. printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a poin
ter therefore if we print *p, we will get the value stored at the address contained by p.
8. return 0;
9. }
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Pointer to array
1. int arr[10];
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array
arr.
Pointer to a function
1. void show (int);
2. void(*p)(int) = &display; // Pointer p is pointing to the address of a function
Pointer to structure
1. struct st {
2. int i;
3. float f;
4. }ref;
5. 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.
Usage of pointer
There are many applications of pointers in c language.
In c language, we can dynamically allocate memory using malloc() and calloc() functions
where the pointer is used.
Pointers in c language are widely used in arrays, functions, and structures. It reduces the
code and improves the performance.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. printf("value of number is %d, address of number is %u",number,&number);
5. return 0;
6. }
Output
value of number is 50, address of number is fff4
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.
int *p=NULL;
In the most libraries, the value of the pointer is 0 (zero).
Operator Precedence
(), [] 1
*, identifier 2
Data type 3
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.
o char -> 4
o * -> 2
o p -> 1
o [10] -> 3
Example
1. #include<stdio.h>
2. void main ()
3. {
4. int a = 10;
5. int *p;
6. int **pp;
7. p = &a; // pointer p is pointing to the address of a
8. pp = &p; // pointer pp is a double pointer pointing to the address of pointer p
9. printf("address of a: %x\n",p); // Address of a will be printed
10. printf("address of p: %x\n",pp); // Address of p will be printed
11. printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 1
0 will be printed
12. printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the
pointer stoyred at pp
13. }
Output
address of a: d26a8734
address of p: d26a8738
value stored at p: 10
value stored at pp: 10
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. int **p2;//pointer to pointer
6. p=&number;//stores the address of number variable
7. p2=&p;
8. printf("Address of number variable is %x \n",&number);
9. printf("Address of p variable is %x \n",p);
10. printf("Value of *p variable is %d \n",*p);
11. printf("Address of p2 variable is %x \n",p2);
12. printf("Value of **p2 variable is %d \n",*p);
13. return 0;
14. }
Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50
In the above question, the pointer arithmetic is used with the double pointer. An array of 6
elements is defined which is pointed by an array of pointer p. The pointer array p is pointed
by a double pointer pp. However, the above image gives you a brief idea about how the
memory is being allocated to the array a and the pointer array p. The elements of p are the
pointers that are pointing to every element of the array a. Since we know that the array
name contains the base address of the array hence, it will work as a pointer and can the
value can be traversed by using *(a), *(a+1), etc. As shown in the image, a[0] can be
accessed in the following ways.
o a[0]: it is the simplest way to access the first element of the array
o *(a): since a store the address of the first element of the array, we can access its
value by using indirection pointer on it.
o *p[0]: if a[0] is to be accessed by using a pointer p to it, then we can use indirection
operator (*) on the first element of the pointer array p, i.e., *p[0].
o **(pp): as pp stores the base address of the pointer array, *pp will give the value of
the first element of the pointer array that is the address of the first element of the
integer array. **p will give the actual value of the first element of the integer array.
Coming to the program, Line 1 and 2 declare the integer and pointer array relatively. Line 3
initializes the double pointer to the pointer array p. As shown in the image, if the address of
the array starts from 200 and the size of the integer is 2, then the pointer array will contain
the values as 200, 202, 204, 206, 208, 210. Let us consider that the base address of the
pointer array is 300; the double pointer pp contains the address of pointer array, i.e., 300.
Line number 4 increases the value of pp by 1, i.e., pp will now point to address 302.
Line number 5 contains an expression which prints three values, i.e., pp - p, *pp - a, **pp.
Let's calculate them each one of them.
o pp = 302, p = 300 => pp-p = (302-300)/2 => pp-p = 1, i.e., 1 will be printed.
o pp = 302, *pp = 202, a = 200 => *pp - a = 202 - 200 = 2/2 = 1, i.e., 1 will be
printed.
o pp = 302, *pp = 202, *(*pp) = 206, i.e., 206 will be printed.
Therefore as the result of line 5, The output 1, 1, 206 will be printed on the console. On line
6, *pp++ is written. Here, we must notice that two unary operators * and ++ will have the
same precedence. Therefore, by the rule of associativity, it will be evaluated from right to
left. Therefore the expression *pp++ can be rewritten as (*(pp++)). Since, pp = 302 which
will now become, 304. *pp will give 204.
On line 7, again the expression is written which prints three values, i.e., pp-p, *pp-a, *pp.
Let's calculate each one of them.
o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
o pp = 304, *pp = 204, a = 200 => *pp-a = (204 - 200)/2 = 2, i.e., 2 will be printed.
o pp = 304, *pp = 204, *(*pp) = 300, i.e., 300 will be printed.
Therefore, as the result of line 7, The output 2, 2, 300 will be printed on the console. On
line 8, ++*pp is written. According to the rule of associativity, this can be rewritten as,
(++(*(pp))). Since, pp = 304, *pp = 204, the value of *pp = *(p[2]) = 206 which will now
point to a[3].
On line 9, again the expression is written which prints three values, i.e., pp-p, *pp-a, *pp.
Let's calculate each one of them.
o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
o pp = 304, *pp = 206, a = 200 => *pp-a = (206 - 200)/2 = 3, i.e., 3 will be printed.
o pp = 304, *pp = 206, *(*pp) = 409, i.e., 409 will be printed.
Therefore, as the result of line 9, the output 2, 3, 409 will be printed on the console. On line
10, ++**pp is writen. according to the rule of associativity, this can be rewritten as,
(++(*(*(pp)))). pp = 304, *pp = 206, **pp = 409, ++**pp => *pp = *pp + 1 = 410. In
other words, a[3] = 410.
On line 11, again the expression is written which prints three values, i.e., pp-p, *pp-a, *pp.
Let's calculate each one of them.
o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be printed.
o pp = 304, *pp = 206, a = 200 => *pp-a = (206 - 200)/2 = 3, i.e., 3 will be printed.
o On line 8, **pp = 410.
Therefore as the result of line 9, the output 2, 3, 410 will be printed on the console.
Output
1 1 206
2 2 300
2 3 409
2 3 410
next →← prev
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:
o Increment
o Decrement
o Addition
o Subtraction
o 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.
32-bit
64-bit
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p+1;
8. printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incre
mented by 4 bytes.
9. return 0;
10. }
Output
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304
Traversing an array by using pointer
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[5] = {1, 2, 3, 4, 5};
5. int *p = arr;
6. int i;
7. printf("printing array elements...\n");
8. for(i = 0; i< 5; i++)
9. {
10. printf("%d ",*(p+i));
11. }
12. }
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:
64-bit
1. #include <stdio.h>
2. void main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-1;
8. printf("After decrement: Address of p variable is %u \n",p); // P will now point to the im
midiate previous location.
9. }
Output
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is
given below:
64-bit
Let's see the example of adding value to pointer variable on 64-bit architecture.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p+3; //adding 3 to pointer variable
8. printf("After adding 3: Address of p variable is %u \n",p);
9. return 0;
10. }
Output
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
As you can see, the address of p is 3214864300. But after adding 3 with p variable, it is
3214864312, i.e., 4*3=12 increment. Since we are using 64-bit architecture, it
increments 12. But if we were using 32-bit architecture, it was incrementing to 6 only,
i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit OS.
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:
64-bit
Let's see the example of subtracting value from the pointer variable on 64-bit
architecture.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-3; //subtracting 3 from pointer variable
8. printf("After subtracting 3: Address of p variable is %u \n",p);
9. return 0;
10. }
Output
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the
previous address value.
However, instead of subtracting a number, we can also subtract an address from another
address (pointer). This will result in a number. It will not be a simple arithmetic
operation, but it will follow the following rule.
1. Address2 - Address1 = (Subtraction of two addresses)/size of data type which pointer poi
nts
1. #include<stdio.h>
2. void main ()
3. {
4. int i = 100;
5. int *p = &i;
6. int *temp;
7. temp = p;
8. p = p + 3;
9. printf("Pointer Subtraction: %d - %d = %d",p, temp, p-temp);
10. }
Output
Pointer Subtraction: 1030585080 - 1030585068 = 3
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. Consider the
following example to make a pointer pointing to the function.
1. #include<stdio.h>
2. int addition ();
3. int main ()
4. {
5. int result;
6. int (*ptr)();
7. ptr = &addition;
8. result = (*ptr)();
9. printf("The sum is %d",result);
10. }
11. int addition()
12. {
13. int a, b;
14. printf("Enter two numbers?");
15. scanf("%d %d",&a,&b);
16. return a+b;
17. }
Output
Enter two numbers?10 15
The sum is 25
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory
allocation and dynamic memory allocation.
Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() function in C
The malloc() function allocates single block of requested memory.
1. ptr=(cast-type*)malloc(byte-size)
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
Output:
calloc() function in C
The calloc() function allocates multiple block of requested memory.
1. ptr=(cast-type*)calloc(number, byte-size)
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
Output:
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.
1. 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.
1. free(ptr)
next →← prev
C Structure
o Construct individual arrays for storing names, roll numbers, and marks.
o Use a special data structure to store the collection of different data types.
1. #include<stdio.h>
2. void main ()
3. {
4. char names[2][10],dummy; // 2-
dimensioanal character array names is used to store the names of the students
5. int roll_numbers[2],i;
6. float marks[2];
7. for (i=0;i<3;i++)
8. {
9.
10. printf("Enter the name, roll number, and marks of the student %d",i+1);
11. scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]);
12. scanf("%c",&dummy); // enter will be stored into dummy character at each iteration
13. }
14. printf("Printing the Student details ...\n");
15. for (i=0;i<3;i++)
16. {
17. printf("%s %d %f\n",names[i],roll_numbers[i],marks[i]);
18. }
19. }
Output
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 69
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.
1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
Let's see the example to define a structure for an entity employee in c.
1. struct employee
2. { int id;
3. char name[20];
4. float salary;
5. };
The following image shows the memory allocation of the structure employee that is
defined in the above example.
C string
Here, struct is the keyword; employee is the name of the structure; id, name,
and salaryare the members or fields of the structure. Let's understand it by the diagram
given below:
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:
1st way:
Let's see the example to declare the structure variable by struct keyword. It should be
declared within the main function.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };
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.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. }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.
Let's see the code to access the id member of p1 variable by . (member) operator.
1. p1.id
C Structure example
Let's see a simple example of structure in C language.
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for structure
7. int main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
Let's see another example of the structure in C language to store many employees
information.
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. float salary;
7. }e1,e2; //declaring e1 and e2 variables for structure
8. int main( )
9. {
10. //store first employee information
11. e1.id=101;
12. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
13. e1.salary=56000;
14.
15. //store second employee information
16. e2.id=102;
17. strcpy(e2.name, "James Bond");
18. e2.salary=126000;
19.
20. //printing first employee information
21. printf( "employee 1 id : %d\n", e1.id);
22. printf( "employee 1 name : %s\n", e1.name);
23. printf( "employee 1 salary : %f\n", e1.salary);
24.
25. //printing second employee information
26. printf( "employee 2 id : %d\n", e2.id);
27. printf( "employee 2 name : %s\n", e2.name);
28. printf( "employee 2 salary : %f\n", e2.salary);
29. return 0;
30. }
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000next →← prev
C Array of Structures
1. #include<stdio.h>
2. struct student
3. {
4. char name[20];
5. int id;
6. float marks;
7. };
8. void main()
9. {
10. struct student s1,s2,s3;
11. int dummy;
12. printf("Enter the name, id, and marks of student 1 ");
13. scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
14. scanf("%c",&dummy);
15. printf("Enter the name, id, and marks of student 2 ");
16. scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
17. scanf("%c",&dummy);
18. printf("Enter the name, id, and marks of student 3 ");
19. scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
20. scanf("%c",&dummy);
21. printf("Printing the details....\n");
22. printf("%s %d %f\n",s1.name,s1.id,s1.marks);
23. printf("%s %d %f\n",s2.name,s2.id,s2.marks);
24. printf("%s %d %f\n",s3.name,s3.id,s3.marks);
25. }
Output
Enter the name, id, and marks of student 1 James 90 90
Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000
In the above program, we have stored data of 3 students in the structure. However, the
complexity of the program will be increased if there are 20 students. In that case, we will
have to declare 20 different structure variables and store them one by one. This will
always be tough since we will have to declare a variable every time we add a student.
Remembering the name of all the variables is also a very tricky task. However, c enables
us to declare an array of structures by using which, we can avoid declaring the different
structure variables; instead we can make a collection containing all the structures that
store the information of different entities.
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 structures.
Let's see an example of an array of structures that stores information of 5 students and
prints it.
1. #include<stdio.h>
2. #include <string.h>
3. struct student{
4. int rollno;
5. char name[10];
6. };
7. int main(){
8. int i;
9. struct student st[5];
10. printf("Enter Records of 5 students");
11. for(i=0;i<5;i++){
12. printf("\nEnter Rollno:");
13. scanf("%d",&st[i].rollno);
14. printf("\nEnter Name:");
15. scanf("%s",&st[i].name);
16. }
17. printf("\nStudent Information List:");
18. for(i=0;i<5;i++){
19. printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
20. }
21. return 0;
22. }
Output:
1. #include<stdio.h>
2. struct address
3. {
4. char city[20];
5. int pin;
6. char phone[14];
7. };
8. struct employee
9. {
10. char name[20];
11. struct address add;
12. };
13. void main ()
14. {
15. struct employee emp;
16. printf("Enter employee information?\n");
17. scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
18. printf("Printing the employee information....\n");
19. printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,emp.add.city,emp.a
dd.pin,emp.add.phone);
20. }
Output
Enter employee information?
Arun
Delhi
110001
1234567890
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
1. By separate structure
2. By Embedded structure
1) Separate structure
Here, we create two structures, but the dependent structure should be used inside the main
structure as a member. Consider the following example.
1. struct Date
2. {
3. int dd;
4. int mm;
5. int yyyy;
6. };
7. struct Employee
8. {
9. int id;
10. char name[20];
11. struct Date doj;
12. }emp1;
As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a
member in Employee structure. In this way, we can use Date structure in many structures.
2) Embedded structure
The embedded structure enables us to declare the structure inside the structure. Hence, it
requires less line of codes but it can not be used in multiple data structures. Consider the
following example.
1. struct Employee
2. {
3. int id;
4. char name[20];
5. struct Date
6. {
7. int dd;
8. int mm;
9. int yyyy;
10. }doj;
11. }emp1;
1. e1.doj.dd
2. e1.doj.mm
3. e1.doj.yyyy
C Nested Structure example
Let's see a simple example of the nested structure in C language.
1. #include <stdio.h>
2. #include <string.h>
3. struct Employee
4. {
5. int id;
6. char name[20];
7. struct Date
8. {
9. int dd;
10. int mm;
11. int yyyy;
12. }doj;
13. }e1;
14. int main( )
15. {
16. //storing employee information
17. e1.id=101;
18. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
19. e1.doj.dd=10;
20. e1.doj.mm=11;
21. e1.doj.yyyy=2014;
22.
23. //printing first employee information
24. printf( "employee id : %d\n", e1.id);
25. printf( "employee name : %s\n", e1.name);
26. printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e
1.doj.yyyy);
27. return 0;
28. }
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
Passing structure to function
Just like other variables, a structure can also be passed to a function. We may pass the
structure members into the function or pass the structure variable at once. Consider the
following example to pass the structure variable employee to a function display() which is
used to display the details of an employee.
1. #include<stdio.h>
2. struct address
3. {
4. char city[20];
5. int pin;
6. char phone[14];
7. };
8. struct employee
9. {
10. char name[20];
11. struct address add;
12. };
13. void display(struct employee);
14. void main ()
15. {
16. struct employee emp;
17. printf("Enter employee information?\n");
18. scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
19. display(emp);
20. }
21. void display(struct employee emp)
22. {
23. printf("Printing the details....\n");
24. printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
25. }
C Union
Like structure, Union in c language is a user-defined data type that is used to store the
different type of elements.
At once, only one member of the union can occupy the memory. In other words, we can say
that the size of the union in any instance is equal to the size of its largest element.
Advantage of union over structure
It occupies less memory because it occupies the size of the largest member only.
Defining union
The union keyword is used to define the union. Let's see the syntax to define union in c.
1. union union_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
1. union employee
2. { int id;
3. char name[50];
4. float salary;
5. };
C Union example
Let's see a simple example of union in C language.
1. #include <stdio.h>
2. #include <string.h>
3. union employee
4. { int id;
5. char name[50];
6. }e1; //declaring e1 variable for union
7. int main( )
8. {
9. //store first employee information
10. e1.id=101;
11. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
12. //printing first employee information
13. printf( "employee 1 id : %d\n", e1.id);
14. printf( "employee 1 name : %s\n", e1.name);
15. return 0;
16. }
Output:
employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal
As you can see, id gets garbage value because name has large memory size. So only name
will have actual value.
C Strings
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.
1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given below.
While declaring string, size is not mandatory. So we can write the above code as given
below:
1. char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
We can also define the string by the string literal in C language. For example:
1. char ch[]="javatpoint";
In such case, '\0' will be appended at the end of the string by the compiler.
o 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.
o The string literal cannot be reassigned to another set of characters whereas, we can
reassign the characters of the array.
String Example in C
Let's see a simple example where a string is declared and being printed. The '%s' is used as
a format specifier for the string in c language.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[11]="javatpoint";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10. }
Output:
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.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "javatpoint";
5. int i = 0;
6. int count = 0;
7. while(i<11)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }
Output
The number of vowels 4
Using the null character
Let's see the same example of counting the number of vowels by using the null character.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "javatpoint";
5. int i = 0;
6. int count = 0;
7. while(s[i] != NULL)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }
Output
The number of vowels 4
1. #include<stdio.h>
2. void main ()
3. {
4. char s[20];
5. printf("Enter the string?");
6. scanf("%s",s);
7. printf("You entered %s",s);
8. }
Enter the string?javatpoint is the best
You entered javatpoint
It is clear from the output that, the above code will not work for space separated strings. To
make this code working for the space separated strings, the minor changed required in the
scanf function, i.e., instead of writing scanf("%s",s), we must write: scanf("%[^\n]s",s)
which instructs the compiler to store the string s while the new line (\n) is encountered.
Let's consider the following example to store the space-separated strings.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[20];
5. printf("Enter the string?");
6. scanf("%[^\n]s",s);
7. printf("You entered %s",s);
8. }
Enter the string?javatpoint is the best
You entered javatpoint is the best
Here we must also notice that we do not need to use address of (&) operator in scanf to
store a string since string s is an array of characters and the name of the array, i.e., s
indicates the base address of the string (character array) therefore we need not use & with
it.
o The compiler doesn't perform bounds checking on the character array. Hence, there
can be a case where the length of the string can exceed the dimension of the
character array which may always overwrite some important data.
o Instead of using scanf, we may use gets() which is an inbuilt function defined in a
header file string.h. The gets() is capable of receiving only one string at a time.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "javatpoint";
5. char *p = s; // pointer p is pointing to string s.
6. printf("%s",p); // the string javatpoint is printed if we print p.
7. }
Output
javatpoint
As we know that string is an array of characters, the pointers can be used in the same way
they were used with arrays. In the above example, p is declared as a pointer to the array of
characters s. P affects similar to s since s is the base address of the string and treated as a
pointer internally. However, we can not change the content of s or copy the content of s into
another string directly. For this purpose, we need to use the pointers to store the strings. In
the following example, we have shown the use of pointers to copy the content of a string
into another.
1. #include<stdio.h>
2. void main ()
3. {
4. char *p = "hello javatpoint";
5. printf("String p: %s\n",p);
6. char *q;
7. printf("copying the content of p into q...\n");
8. q = p;
9. printf("String q: %s\n",q);
10. }
Output
String p: hello javatpoint
copying the content of p into q...
String q: hello javatpoint
1. #include<stdio.h>
2. void main ()
3. {
4. char *p = "hello javatpoint";
5. printf("Before assigning: %s\n",p);
6. p = "hello";
7. printf("After assigning: %s\n",p);
8. }
Output
Before assigning: hello javatpoint
After assigning: hello
next →← prev
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
1. char[] gets(char[]);
Reading string using gets()
1. #include<stdio.h>
2. void main ()
3. {
4. char s[30];
5. printf("Enter the string? ");
6. gets(s);
7. printf("You entered %s",s);
8. }
Output
Enter the string?
javatpoint is the best
You entered javatpoint is the best
The gets() function is risky to use since it doesn't perform any array bound checking and
keep reading the characters until the new line (enter) is encountered. It suffers from
buffer overflow, which can be avoided by using fgets(). The fgets() makes sure that not
more than the maximum limit of characters are read. Consider the following example.
1. #include<stdio.h>
2. void main()
3. {
4. char str[20];
5. printf("Enter the string? ");
6. fgets(str, 20, stdin);
7. printf("%s", str);
8. }
Output
Enter the string? javatpoint is the best website
javatpoint is the b
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
1. int puts(char[])
Let's see an example to read a string using gets() and print it on the console using
puts().
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char name[50];
5. printf("Enter your name: ");
6. gets(name); //reads string from user
7. printf("Your name is: ");
8. puts(name); //displays string
9. return 0;
10. }
Output:
Enter your name: Sonoo Jaiswal
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. return 0;
7. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
5. char ch2[20];
6. strcpy(ch2,ch);
7. printf("Value of second string is: %s",ch2);
8. return 0;
9. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }
Output:
Here, we are using gets() function which reads string from the console.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20],str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1,str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10. }
Output:
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
10. }
Output:
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:
Output:
C Math
C Programming allows us to perform mathematical operations through the functions defined
in <math.h> header file. The <math.h> header file contains various methods for
performing mathematical operations such as sqrt(), pow(), ceil(), floor() etc.
C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h
header file are given below.
C Math Example
Let's see a simple example of math functions found in math.h header file.
1. #include<stdio.h>
2. #include <math.h>
3. int main(){
4. printf("\n%f",ceil(3.6));
5. printf("\n%f",ceil(3.3));
6. printf("\n%f",floor(3.6));
7. printf("\n%f",floor(3.2));
8. printf("\n%f",sqrt(16));
9. printf("\n%f",sqrt(7));
10. printf("\n%f",pow(2,4));
11. printf("\n%f",pow(3,3));
12. printf("\n%d",abs(-12));
13. return 0;
14. }
Output:
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
File Handling in C
In programming, we may require some specific input data to be generated several numbers
of times. Sometimes, it is not enough to only display the data on the console. The data to
be displayed may be very large, and only a limited amount of data can be displayed on the
console, and since the memory is volatile, it is impossible to recover the programmatically
generated data again and again. However, if we need to do so, we may store it onto the
local file system which is volatile and can be accessed every time. Here, comes the need of
file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local
file system through our C program. The following operations can be performed on a file.
o The file name (string). If the file is stored at some specific location, then we must
mention the path at which the file is stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.
Mode Description
1. #include<stdio.h>
2. void main( )
3. {
4. FILE *fp ;
5. char ch ;
6. fp = fopen("file_handle.c","r") ;
7. while ( 1 )
8. {
9. ch = fgetc ( fp ) ;
10. if ( ch == EOF )
11. break ;
12. printf("%c",ch) ;
13. }
14. fclose (fp ) ;
15. }
Output
#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the
character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file.txt", "w");//opening file
5. fprintf(fp, "Hello file by fprintf...\n");//writing data into file
6. fclose(fp);//closing file
7. }
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. char buff[255];//creating char array to store data of file
5. fp = fopen("file.txt", "r");
6. while(fscanf(fp, "%s", buff)!=EOF){
7. printf("%s ", buff );
8. }
9. fclose(fp);
10. }
Output:
1. #include <stdio.h>
2. void main()
3. {
4. FILE *fptr;
5. int id;
6. char name[30];
7. float salary;
8. fptr = fopen("emp.txt", "w+");/* open for writing */
9. if (fptr == NULL)
10. {
11. printf("File does not exists \n");
12. return;
13. }
14. printf("Enter the id\n");
15. scanf("%d", &id);
16. fprintf(fptr, "Id= %d\n", id);
17. printf("Enter the name \n");
18. scanf("%s", name);
19. fprintf(fptr, "Name= %s\n", name);
20. printf("Enter the salary\n");
21. scanf("%f", &salary);
22. fprintf(fptr, "Salary= %.2f\n", salary);
23. fclose(fptr);
24. }
Output:
Enter the id
1
Enter the name
sonoo
Enter the salary
120000
Now open file from current directory. For windows operating system, go to TC\bin directory,
you will see emp.txt file. It will have following information.
emp.txt
Id= 1
Name= sonoo
Salary= 120000
Syntax:
Example:
1. #include <stdio.h>
2. main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//openingfile
5. fputc('a',fp);//writing single character into file
6. fclose(fp);//closing file
7. }
file1.txt
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12. fclose(fp);
13. getch();
14. }
myfile.txt
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. clrscr();
6.
7. fp=fopen("myfile2.txt","w");
8. fputs("hello c programming",fp);
9.
10. fclose(fp);
11. getch();
12. }
myfile2.txt
hello c programming
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char text[300];
6. clrscr();
7.
8. fp=fopen("myfile2.txt","r");
9. printf("%s",fgets(text,200,fp));
10.
11. fclose(fp);
12. getch();
13. }
Output:
hello c programming
C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write
data into file at desired location.
Syntax:
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.
Example:
1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("myfile.txt","w+");
6. fputs("This is javatpoint", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }
myfile.txt
C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful if
you have to use stream many times.
Syntax:
Example:
File: file.txt
File: rewind.c
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("file.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12.
13. rewind(fp);//moves the file pointer at beginning of the file
14.
15. while((c=fgetc(fp))!=EOF){
16. printf("%c",c);
17. }
18.
19. fclose(fp);
20. getch();
21. }
Output:
Syntax:
Example:
File: ftell.c
1. #include <stdio.h>
2. #include <conio.h>
3. void main (){
4. FILE *fp;
5. int length;
6. clrscr();
7. fp = fopen("file.txt", "r");
8. fseek(fp, 0, SEEK_END);
9.
10. length = ftell(fp);
11.
12. fclose(fp);
13. printf("Size of file: %d bytes", length);
14. getch();
15. }
Output:
C Preprocessor Directives
The C preprocessor is a micro processor that is used by compiler to transform your code
before compilation. It is called micro preprocessor because it allows us to add macros.
Note: Proprocessor direcives are executed before compilation.
o #include
o #define
o #undef
o #ifdef
o #ifndef
o #if
o #else
o #elif
o #endif
o #error
o #pragma
What is Macro
Please visit next page.
C Macros
A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. There are two types of macros:
1. Object-like Macros
2. Function-like Macros
Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:
1. #define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
Function-like Macros
The function-like macro looks like function call. For example:
Visit #define to see the full example of object-like and function-like macros.
C Predefined Macros
ANSI C defines many predefined macros that can be used in c program.
1. #include<stdio.h>
2. int main(){
3. printf("File :%s\n", __FILE__ );
4. printf("Date :%s\n", __DATE__ );
5. printf("Time :%s\n", __TIME__ );
6. printf("Line :%d\n", __LINE__ );
7. printf("STDC :%d\n", __STDC__ );
8. return 0;
9. }
Output:
File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1
next →← prev
C #include
The #include preprocessor directive is used to paste code of given file into current file. It
is used include system-defined and user-defined header files. If included file is not found,
compiler renders error.
1. #include <filename>
2. #include "filename"
The #include <filename> tells the compiler to look for the directory where system
header files are held. In UNIX, it is \usr\include directory.
The #include "filename" tells the compiler to look in the current directory from where
program is running.
Let's see a simple example of #include directive. In this program, we are including
stdio.h file because printf() function is defined in this file.
1. #include<stdio.h>
2. int main(){
3. printf("Hello C");
4. return 0;
5. }
Output:
Hello C
#include notes:
Note 3: You can use only comment after filename otherwise it will give error. C
#define
The #define preprocessor directive is used to define constant or micro substitution. It can
use any basic data type.
Syntax:
1. #include <stdio.h>
2. #define PI 3.14
3. main() {
4. printf("%f",PI);
5. }
Output:
3.140000
1. #include <stdio.h>
2. #define MIN(a,b) ((a)<(b)?(a):(b))
3. void main() {
4. printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
5. }
Output:
C #undef
The #undef preprocessor directive is used to undefine the constant or macro defined by
#define.
Syntax:
1. #undef token
1. #include <stdio.h>
2. #define PI 3.14
3. #undef PI
4. main() {
5. printf("%f",PI);
6. }
Output:
The #undef directive is used to define the preprocessor constant to a limited scope so that
you can declare constant again.
Let's see an example where we are defining and undefining number variable. But before
being undefined, it was used by square variable.
1. #include <stdio.h>
2. #define number 15
3. int square=number*number;
4. #undef number
5. main() {
6. printf("%d",square);
7. }
Output:
225
next →← prev
C #ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it
executes the code otherwise #else code is executed, if present.
Syntax:
1. #ifdef MACRO
2. //code
3. #endif
1. #ifdef MACRO
2. //successful code
3. #else
4. //else code
5. #endif
C #ifdef example
Let's see a simple example to use #ifdef preprocessor directive.
1. #include <stdio.h>
2. #include <conio.h>
3. #define NOINPUT
4. void main() {
5. int a=0;
6. #ifdef NOINPUT
7. a=2;
8. #else
9. printf("Enter a:");
10. scanf("%d", &a);
11. #endif
12. printf("Value of a: %d\n", a);
13. getch();
14. }
Output:
Value of a: 2
But, if you don't define NOINPUT, it will ask user to enter a number.
1. #include <stdio.h>
2. #include <conio.h>
3. void main() {
4. int a=0;
5. #ifdef NOINPUT
6. a=2;
7. #else
8. printf("Enter a:");
9. scanf("%d", &a);
10. #endif
11.
12. printf("Value of a: %d\n", a);
13. getch();
14. }
Output:
Enter a:5
next →← prev
C #ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it
executes the code otherwise #else code is executed, if present.
Syntax:
1. #ifndef MACRO
2. //code
3. #endif
1. #ifndef MACRO
2. //successful code
3. #else
4. //else code
5. #endif
C #ifndef example
Let's see a simple example to use #ifndef preprocessor directive.
1. #include <stdio.h>
2. #include <conio.h>
3. #define INPUT
4. void main() {
5. int a=0;
6. #ifndef INPUT
7. a=2;
8. #else
9. printf("Enter a:");
10. scanf("%d", &a);
11. #endif
12. printf("Value of a: %d\n", a);
13. getch();
14. }
Output:
Enter a:5
Value of a: 5
But, if you don't define INPUT, it will execute the code of #ifndef.
1. #include <stdio.h>
2. #include <conio.h>
3. void main() {
4. int a=0;
5. #ifndef INPUT
6. a=2;
7. #else
8. printf("Enter a:");
9. scanf("%d", &a);
10. #endif
11. printf("Value of a: %d\n", a);
12. getch();
13. }
Output:
Value of a: 2
Value of a: 5 C #if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code otherwise #elseif or #else or #endif code is executed.
Syntax:
1. #if expression
2. //code
3. #endif
1. #if expression
2. //if code
3. #else
4. //else code
5. #endif
1. #if expression
2. //if code
3. #elif expression
4. //elif code
5. #else
6. //else code
7. #endif
C #if example
Let's see a simple example to use #if preprocessor directive.
1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 0
4. void main() {
5. #if (NUMBER==0)
6. printf("Value of Number is: %d",NUMBER);
7. #endif
8. getch();
9. }
Output:
1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 1
4. void main() {
5. clrscr();
6. #if (NUMBER==0)
7. printf("1 Value of Number is: %d",NUMBER);
8. #endif
9.
10. #if (NUMBER==1)
11. printf("2 Value of Number is: %d",NUMBER);
12. #endif
13. getch();
14. }
Output:
C #else
The #else preprocessor directive evaluates the expression or condition if condition of #if is
false. It can be used with #if, #elif, #ifdef and #ifndef directives.
Syntax:
1. #if expression
2. //if code
3. #else
4. //else code
5. #endif
1. #if expression
2. //if code
3. #elif expression
4. //elif code
5. #else
6. //else code
7. #endif
C #else example
Let's see a simple example to use #else preprocessor directive.
1. #include <stdio.h>
2. #include <conio.h>
3. #define NUMBER 1
4. void main() {
5. #if NUMBER==0
6. printf("Value of Number is: %d",NUMBER);
7. #else
8. print("Value of Number is non-zero");
9. #endif
10. getch();
11. }
Output:
C #error
The #error preprocessor directive indicates error. The compiler gives fatal error if #error
directive is found and skips further compilation process.
C #error example
Let's see a simple example to use #error preprocessor directive.
1. #include<stdio.h>
2. #ifndef __MATH_H
3. #error First include then compile
4. #else
5. void main(){
6. float a;
7. a=sqrt(7);
8. printf("%f",a);
9. }
10. #endif
Output:
1. #include<stdio.h>
2. #include<math.h>
3. #ifndef __MATH_H
4. #error First include then compile
5. #else
6. void main(){
7. float a;
8. a=sqrt(7);
9. printf("%f",a);
10. }
11. #endif
Output:
2.645751
C #pragma
The #pragma preprocessor directive is used to provide additional information to the
compiler. The #pragma directive is used by the compiler to offer machine or operating-
system feature.
Syntax:
1. #pragma token
1. #pragma argsused
2. #pragma exit
3. #pragma hdrfile
4. #pragma hdrstop
5. #pragma inline
6. #pragma option
7. #pragma saveregs
8. #pragma startup
9. #pragma warn
1. #include<stdio.h>
2. #include<conio.h>
3.
4. void func() ;
5.
6. #pragma startup func
7. #pragma exit func
8.
9. void main(){
10. printf("\nI am in main");
11. getch();
12. }
13.
14. void func(){
15. printf("\nI am in func");
16. getch();
17. }
A list of 50 top frequently asked C programming interview questions and answers are given
below.
1) What is C language?
C is a mid-level and procedural programming language. The Procedural programming
language is also known as the structured programming language is a technique in which
large programs are broken down into smaller modules, and each module uses structured
code. This technique minimizes error and misinterpretation. More details.
More details.
scanf(): The scanf() function is used to take input from the user.
More details.
8) What is the difference between the local variable and
global variable in C?
Following are the differences between a local variable and global variable:
More details.
More details.
o C functions are used to avoid the rewriting the same code again and again in our
program.
o C functions can be called any number of times from any place of our program.
o When a program is divided into functions, then any part of our program can easily be
tracked.
o C functions provide the reusability concept, i.e., it breaks the big task into smaller
tasks so that it makes the C program more understandable.
More details.
1. #include <stdio.h>
2. void change(int,int);
3. int main()
4. {
5. int a=10,b=20;
6. change(a,b); //calling a function by passing the values of variables.
7. printf("Value of a is: %d",a);
8. printf("\n");
9. printf("Value of b is: %d",b);
10. return 0;
11. }
12. void change(int x,int y)
13. {
14. x=13;
15. y=17;
16. }
Output:
Value of a is: 10
Value of b is: 20
1. #include <stdio.h>
2. void change(int*,int*);
3. int main()
4. {
5. int a=10,b=20;
6. change(&a,&b); // calling a function by passing references of variables.
7. printf("Value of a is: %d",a);
8. printf("\n");
9. printf("Value of b is: %d",b);
10. return 0;
11. }
12. void change(int *x,int *y)
13. {
14. *x=13;
15. *y=17;
16. }
Output:
Value of a is: 13
Value of b is: 17
More details.
1. Winding phase
2. Unwinding phase
Winding phase: When the recursive function calls itself, and this phase ends when the
condition is reached.
Unwinding phase: Unwinding phase starts when the condition is reached, and the control
returns to the original call.
Example of recursion
1. #include <stdio.h>
2. int calculate_fact(int);
3. int main()
4. {
5. int n=5,f;
6. f=calculate_fact(n); // calling a function
7. printf("factorial of a number is %d",f);
8. return 0;
9. }
10. int calculate_fact(int a)
11. {
12. if(a==1)
13. {
14. return 1;
15. }
16. else
17. return a*calculate_fact(a-1); //calling a function recursively.
18. }
Output:
More details.
Syntax:
1. data_type array_name[size];
o Multidimensional array: Multidimensional array is an array that contains more
than one array.
Syntax:
1. data_type array_name[size];
Example of an array:
1. #include <stdio.h>
2. int main()
3. {
4. int arr[5]={1,2,3,4,5}; //an array consists of five integer values.
5. for(int i=0;i<5;i++)
6. {
7. printf("%d ",arr[i]);
8. }
9. return 0;
10. }
Output:
1 2 3 4 5
More details.
For example:
1. Data_type *p;
The above syntax tells that p is a pointer variable that holds the address number of a given
data type value.
Example of pointer
1. #include <stdio.h>
2. int main()
3. {
4. int *p; //pointer of type integer.
5. int a=5;
6. p=&a;
7. printf("Address value of 'a' variable is %u",p);
8. return 0;
9. }
Output:
More details.
More details.
1. #include<stdio.h>
2. void main()
3. {
4. int *ptr = malloc(constant value); //allocating a memory space.
5. free(ptr); //ptr becomes a dangling pointer.
6. }
In the above example, initially memory is allocated to the pointer variable ptr, and then the
memory is deallocated from the pointer variable. Now, pointer variable, i.e., ptr becomes a
dangling pointer.
The problem of a dangling pointer can be overcome by assigning a NULL value to the
dangling pointer. Let's understand this through an example:
1. #include<stdio.h>
2. void main()
3. {
4. int *ptr = malloc(constant value); //allocating a memory space.
5. free(ptr); //ptr becomes a dangling pointer.
6. ptr=NULL; //Now, ptr is no longer a dangling pointer.
7. }
In the above example, after deallocating the memory from a pointer variable, ptr is
assigned to a NULL value. This means that ptr does not point to any memory location.
Therefore, it is no longer a dangling pointer.
1. #include <stdio.h>
2. int main()
3. {
4. int a=10;
5. int *ptr,**pptr; // *ptr is a pointer and **pptr is a double pointer.
6. ptr=&a;
7. pptr=&ptr;
8. printf("value of a is:%d",a);
9. printf("\n");
10. printf("value of *ptr is : %d",*ptr);
11. printf("\n");
12. printf("value of **pptr is : %d",**pptr);
13. return 0;
14. }
In the above example, pptr is a double pointer pointing to the address of the ptr variable
and ptr points to the address of 'a' variable.
More details.
1. For example:
2. int a[10];
The above example creates an array of integer type, and the size of an array is fixed, i.e.,
10.
More details.
1. For example
2. int *p= malloc(sizeof(int)*10);
More details.
Syntax
Syntax
Syntax
1. ptr = realloc(ptr, newsize); // updating the memory size using realloc() function.
Syntax
The above syntax releases the memory from a pointer variable ptr.
More details.
More details.
Syntax of structure
1. struct structure_name
2. {
3. Member_variable1;
4. Member_variable2
5. .
6. .
7. }[structure variables];
1. #include <stdio.h>
2. struct student
3. {
4. char name[10]; // structure members declaration.
5. int age;
6. }s1; //structure variable
7. int main()
8. {
9. printf("Enter the name");
10. scanf("%s",s1.name);
11. printf("\n");
12. printf("Enter the age");
13. scanf("%d",&s1.age);
14. printf("\n");
15. printf("Name and age of a student: %s,%d",s1.name,s1.age);
16. return 0;
17. }
Output:
More details.
25) What is a union?
o The union is a user-defined data type that allows storing multiple types of data in a
single unit. However, it doesn't occupy the sum of the memory of all members. It
holds the memory of the largest member only.
o In union, we can access only one variable at a time as it allocates one common
space for all the members of a union.
Syntax of union
1. union union_name
2. {
3. Member_variable1;
4. Member_variable2;
5. .
6. .
7. Member_variable n;
8. }[union variables];
1. #include<stdio.h>
2. union data
3. {
4. int a; //union members declaration.
5. float b;
6. char ch;
7. };
8. int main()
9. {
10. union data d; //union variable.
11. d.a=3;
12. d.b=5.6;
13. d.ch='a';
14. printf("value of a is %d",d.a);
15. printf("\n");
16. printf("value of b is %f",d.b);
17. printf("\n");
18. printf("value of ch is %c",d.ch);
19. return 0;
20. }
Output:
value of a is 1085485921
value of b is 5.600022
value of ch is a
In the above example, the value of a and b gets corrupted, and only variable ch shows the
actual output. This is because all the members of a union share the common memory space.
Hence, the variable ch whose value is currently updated.
More details.
Syntax
1. #include<stdio.h>
2. int main()
3. {
4. char a[20];
5. int n=sprintf(a,"javaToint");
6. printf("value of n is %d",n);
7. return 0;}
Output:
value of n is 9
28) Can we compile a program without main() function?
Yes, we can compile, but it can't be executed.
But, if we use #define, we can compile and run a C program without using the main()
function. For example:
1. #include<stdio.h>
2. #define start main
3. void start() {
4. printf("Hello");
5. }
More details.
The getche() function reads a single character from the keyword, but data is displayed on
the output screen. Press Alt+f5 to see the entered character.
1. #include<stdio.h>
2. #include<conio.h>
3. int main()
4. {
5.
6. char ch;
7. printf("Enter a character ");
8. ch=getch(); // taking an user input without printing the value.
9. printf("\nvalue of ch is %c",ch);
10. printf("\nEnter a character again ");
11. ch=getche(); // taking an user input and then displaying it on the screen.
12. printf("\nvalue of ch is %c",ch);
13. return 0;
14. }
Output:
Enter a character
value of ch is a
Enter a character again a
value of ch is a
In the above example, the value entered through a getch() function is not displayed on the
screen while the value entered through a getche() function is displayed on the screen.
33) What is the newline escape sequence?
The new line escape sequence is represented by "\n". It inserts a new line on the output
screen.
More details.
A near pointer doesn't have explicit selector whereas far, and huge pointers have explicit
selector. When you perform pointer arithmetic on the far pointer, the selector is not
modified, but in case of a huge pointer, it can be modified.
These are the non-standard keywords and implementation specific. These are irrelevant in a
modern platform.
Syntax
1. (type_name) expression;
38) What are the functions to open and close the file in C
language?
The fopen() function is used to open file whereas fclose() is used to close file.
1. for(;;){
2. //code to be executed
3. }
1. while(1){
2. //code to be executed
3. }
1. do{
2. //code to be executed
3. }while(1);