c Notes Updated
c Notes Updated
What is C – Introduction to C
Programming Language
C programming language is a procedural and general-purpose
programming language. It is fast and simple to learn and implement. It
was developed by Dennis Ritchie in the year of 1972.
Real-World Applications of C
The use of the C programming language is not limited to the
development of operating systems and applications. It is also used in
GUI development, IDE development etc. Some uses of C language are:-
1. Operating Systems:-
Advertisement
With the help of C, you can write your own operating system. Isn’t it
cool? The C programming language is used to develop windows and
linux kernels and also the Apple OS X kernel.
3. Embedded Systems:-
In daily life, we use different embedded systems like coffee machines,
microwaves, climate control systems etc. C makes it easy to develop
these systems.
4. Database:-
Popular database management software, MySQL was developed using
the C programming language.
5. Ease of Computation:-
C provides faster computation in programs. The implementation of
algorithms and data structures is swift in C. With the help of C, you can
perform high degree calculations such as MATLAB, Mathematica etc.
6. Gaming:-
C programming is relatively faster than Java or Python. C language has
been used in various gaming applications and graphics. Many popular
games like Tic-Tac-Toe, The Snake game, Sudoku etc. are developed
using the C language.
7. Development of New languages:-
The C language is fast and easy to understand. So many programming
languages like Java, Python, PHP etc. get influenced by this. Even the
libraries of Python are developed using C. The syntax and control
structures of PERL, PHP and C++ are based upon the C language.
8. Assemblers:-
Assemblers are mainly used to translate assembly level language to
machine level language. C also helped in developing GNU assembler.
9. Text Editors:-
C also helped in creating various text editors like Vim, Gedit etc.
Advertisement
10. Interpreters:-
You can also create language interpreters using the C programming
langauge. C helped in developing different programming language
interpreters like Python and MATLAB interpreters etc.
Advertisement
Clang Compiler
MinGW Compiler
Turbo C etc.
Advertisement
Main() function
int main()
{
Declaration part;
Executable part;
return 0;
}
Function definition;
Structure of C programming
language:-
Following is a basic example of C language:-
Commands Meaning
#include<stdio.h It helps you to include the stdio.h header file into your program. With this,
> you can perform input/output operations.
int main() From here the execution of the C program starts. It is the main() function.
/* comments */ If you write something inside this ‘/* */’ then it won’t get executed.
printf(“Hello
Used for printing the output to the screen.
World”);
int main()
{}
Variable Declaration:-
Next, you have to declare some variables to start with the program code.
In C, you cannot use any variables if you have not declared it first.
Example:-
int main(){
float a;
int f;
Body:-
Advertisement
Example:-
int main(){
float a = 2.3;
printf("%d",a);
Return Statement:-
It is the last part of each and every C program. It depends on the return
type of the function. Return Statement is used for returning values from
a function. If the return type is void then you don’t have to write the
return statement in the program code.
int main(){
float a = 2.3;
printf("%d",a);
return 0;
What is a Compiler:-
You can say that a compiler is a computer program that is used for
converting the program code to machine understandable code. It is
software that converts the code to machine-friendly language.
Advantages of C:-
1. Portability:- In C, you can execute a block of code in different
environments. Suppose, you create a program in one platform and you
are running or modifying the program in other platforms. Portability is
one of the best features of the C programming language.
2. Simple and Efficient:- The C programming language is easy to
implement. The syntax of the C language is easy to understand. If you
are confused about which programming language you should learn as a
beginner then the C language is the best choice for you. It is efficient
and simple to learn and use.
3. Speed:- It compiles and executes faster than Java or Python. Because
C is a compiler-based programming language and Java and Python are
interpreter-based programming languages.
4. Popular:- The C language is used in making operating systems and
embedded systems. It is one of the most widely used programming
languages in the world.
5. Rich Library:- The C language has a rich library that offers useful
built-in functions. Apart from these functions, you can also add or define
user-defined functions to the library. These functions help in solving
numerous types of problems easily and also help in better and clean
coding.
Advertisement
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.
The following are the phases through which our program passes before being
transformed into an executable form:
o Preprocessor
o Compiler
o Assembler
o Linker
Preprocessor
The source code is the code which is written in a text editor and the source code
file is given an extension ".c". This source code is first passed to the preprocessor,
and then the preprocessor expands this code. After expanding the code, the
expanded code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The
compiler converts this code into assembly code. Or we can say that the C compiler
converts the pre-processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name
of the object file generated by the assembler is the same as the source file. The
extension of the object file in DOS is '.obj,' and in UNIX, the extension is 'o'. If the
name of the source file is 'hello.c', then the name of the object file would be
'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions
are pre-compiled, and the object code of these library files is stored with '.lib' (or
'.a') extension. The main working of the linker is to combine the object code of
library files with the object code of our program. Sometimes the situation arises
when our program refers to the functions defined in other files; then linker plays a
very important role in this. It links the object code of these files to our program.
Therefore, we conclude that the job of the linker is to link the object code of our
program with the object code of the library files and other files. The output of the
linker is the executable file. The name of the executable file is the same as the
source file but differs only in their extensions. In DOS, the extension of the
executable file is '.exe', and in UNIX, the executable file can be named as 'a.out'.
For example, if we are using printf() function in a program, then the linker adds its
associated code in an output file.
hello.c
1. #include<stdio.h>
2. int main(){
3. //printing information
4. printf("Hello World");
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
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,cb;
4. printf("enter a number:");
5. scanf("%d",&number);
6. cb= number*number*number;
7. printf("cube of number is:%d ",cb);
8. return 0;
9. }
Output
enter a number:5
cube of number is:125
1. #include<stdio.h>
2.
3. int main(){
4. int x,,y,result;
5.
6. printf("enter first number:");
7. scanf("%d",,&x);
8. printf("enter second number:");
9. scanf("%d",,&y);
10.
11.result=x+y;
12. printf("sum of 2 numbers:%d ",result);
13.
14. return 0;
15.}
Output
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.
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.
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 us extern keyword.
myfile.h
1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }
Tokens in C
Tokens in C is the most important element to be used in creating a program in C.
We can define the token as the smallest individual element in C. For `example, we
cannot create a sentence without using words; similarly, we cannot create a
program in C without using tokens in C. Therefore, we can say that tokens in C is
the building block or the basic component for creating a program in C language.
Classification of tokens in C
Keywords in C
Do If static While
Identifiers in C
Identifiers in C are used for naming variables, functions, arrays, structures, etc.
Identifiers in C are the user-defined words. It can be composed of uppercase
letters, lowercase letters, underscore, or digits, but the starting letter should be
either an underscore or an alphabet. Identifiers cannot be used as keywords. Rules
for constructing identifiers in C are given below:
Strings in C
char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.
char a[] = "javatpoint"; // The compiler allocates the memory at the run time.
Operators in C
Operators in C is a special symbol used to perform the functions. The data items
on which the operators are applied are known as operands. Operators are applied
between the operands. Depending on the number of operands, operators are
classified as follows:
Unary Operator
Binary Operator
The binary operator is an operator applied between two operands. The following is
the list of the binary operators:
o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Conditional Operators
o Assignment Operator
o Misc Operator
Constants in C
A constant is a value assigned to the variable which will remain the same
throughout the program, i.e., the constant value cannot be changed.
Types of constants in C
Constant Example
Special characters in C
Some special characters are used in C, and they have a special meaning which
cannot be used for another purpose.
o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in the
opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when
printing the value of more than one variable using a single printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes
that we are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an
operator for multiplication.
o Tilde (~): It is used as a destructor to free memory.
o Period (.): It is used to access a member of a structure or a union.
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 Identifiers
C identifiers represent the name in the C program, for example, variables,
functions, arrays, structures, unions, labels, etc. An identifier can be composed of
letters such as uppercase, lowercase letters, underscore, digits, but the starting
letter should be either an alphabet or an underscore. If the identifier is not used in
the external linkage, then it is called as an internal identifier. If the identifier is
used in the external linkage, then it is called as an external identifier.
Types of identifiers
o Internal identifier
o External identifier
Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal
identifier. The internal identifiers can be local variables.
External Identifier
Keyword Identifier
1. int main()
2. {
3. int a=10;
4. int A=20;
5. printf("Value of a is : %d",a);
6. printf("\nValue of A is :%d",A);
7. return 0;
8. }
Output
Value of a is : 10
Value of A is :20
The above output shows that the values of both the variables, 'a' and 'A' are
different. Therefore, we conclude that the identifiers are case sensitive.
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
Arithmetic Operators in C
int main()
{
int a = 10, b = 4, res;
// printing a and b
printf("a is %d and b is %d\n", a, b);
res = a + b; // addition
printf("a + b is %d\n", res);
res = a - b; // subtraction
printf("a - b is %d\n", res);
res = a * b; // multiplication
printf("a * b is %d\n", res);
res = a / b; // division
printf("a / b is %d\n", res);
res = a % b; // modulus
printf("a %% b is %d\n", res);
return 0;
}
Output
a is 10 and b is 4
a + b is 14
a - b is 6
a * b is 40
a / b is 2
a % b is 2
2. Unary Arithmetic Operators in C
The unary arithmetic operators operate or work with a single operand. In C,
we have two unary arithmetic operators which are as follows:
Symbo
Operator l Operation Implementation
Unary Plus
+ Returns the value of its operand. +h
Operator
Increment Operator in C
Decrement Operator in C
The ‘–‘ operator is used to decrement the value of an integer. Just like the
increment operator, the decrement operator can also be used in two ways:
1. Pre-Decrement
When placed before the variable name (also called the pre-
decrement operator), its value is decremented instantly. For example, – –
x.
2. Post Decrement
When it is placed after the variable name (also called post-
decrement operator), its value is preserved temporarily until the execution
of this statement and it gets updated before the execution of the next
statement. For example, x – –.
int main()
{
int a = 10, res;
// post-decrement example:
// res is assigned 11 only, a is not updated yet
res = a--;
printf("a is %d and result is %d\n", a,
sizrsize res); // a becomes 10 now
// pre-decrement example:
// res is assigned 10 only since a is updated here
// itself
res = --a;
return 0;
}
Output
Post Increment and Decrement
a is 11 and result is 10
a is 10 and result is 11
Relational Operators
Relational operators are used for the comparison of two values to
understand the type of relationship a pair of number shares. For example,
less than, greater than, equal to, etc. Let’s see them one by one
C
// C program to demonstrate working of
relational operators
#include <stdio.h>
int main()
{
int a = 10, b = 4;
// equal to
if (a == b)
printf("a is equal to b\n");
else
printf("a and b are not equal\
n");
// not equal to
if (a != b)
printf("a is not equal to b\n");
else
printf("a is equal b\n");
return 0;
}
Logical Operators:
They are used to combine two or more conditions/constraints or to
complement the evaluation of the original condition under consideration.
They are described below:
1. Logical AND operator: The ‘&&’ operator returns true when both
the conditions under consideration are satisfied. Otherwise, it
returns false. For example, a && b returns true when both a and b
are true (i.e. non-zero).
2. Logical OR operator: The ‘||’ operator returns true even if one
(or both) of the conditions under consideration is satisfied.
Otherwise, it returns false. For example, a || b returns true if one
of a or b, or both are true (i.e. non-zero). Of course, it returns true
when both a and b are true.
3. Logical NOT operator: The ‘!’ operator returns true the condition
in consideration is not satisfied. Otherwise, it returns false. For
example, !a returns true if a is false, i.e. when a=0.
Examples:
C
// C program to demonstrate working of
logical operators
#include <stdio.h>
int main()
{
int a = 10, b = 4, c = 10, d = 20;
// logical operators
// logical OR example
if (a > b || c == d)
printf("a is greater than b OR c
is equal to d\n");
else
printf("Neither a is greater than
b nor c is equal "
" to d\n");
return 0;
}
sizeof operator in C
Output
1
4
4
8
Note: sizeof() may give different output according to machine, we have run
our program on a 32-bit gcc compiler.
Assignment Operators in C
Assignment operators are used to assigning value to a variable. The left side
operand of the assignment operator is a variable and right side operand of
the assignment operator is a value. The value on the right side must be of
the same data-type of the variable on the left side otherwise the compiler
will raise an error.
Different types of assignment operators are shown below:
“=”: This is the simplest assignment operator. This operator is used
to assign the value on the right to the variable on the left.
For example:
a = 10;
b = 20;
ch = 'y';
“+=”: This operator is combination of ‘+’ and ‘=’ operators. This
operator first adds the current value of the variable on left to the
value on the right and then assigns the result to the variable on the
left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
“-=”This operator is combination of ‘-‘ and ‘=’ operators. This
operator first subtracts the current value of the variable on left from
the value on the right and then assigns the result to the variable on
the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
“*=”This operator is combination of ‘*’ and ‘=’ operators. This
operator first multiplies the current value of the variable on left to
the value on the right and then assigns the result to the variable on
the left.
Example:
(a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
“/=”This operator is combination of ‘/’ and ‘=’ operators. This
operator first divides the current value of the variable on left by the
value on the right and then assigns the result to the variable on the
left.
Example:
(a /= b) can be written as (a = a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.
Below example illustrates the various Assignment Operators:
// C program to demonstrate
// working of Assignment operators
#include <stdio.h>
int main()
{
// Assigning value 10 to a
// using "=" operator
int a = 10;
printf("Value of a is %d\n", a);
return 0;
}
Output:
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10
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).
C Format Specifier
The Format specifier is a string used in the formatted input and output functions.
The format string determines the format of the input and output. The format
string always starts with a '%' character.
Format Description
specifier
o %d
1. int main()
2. {
3. int b=6;
4. int c=8;
5. printf("Value of b is:%d", b);
6. printf("\nValue of c is:%d",c);
7.
8. return 0;
9. }
In the above code, we are printing the integer value of b and c by using the %d
specifier.
Output
o %u
1. int main()
2. {
3. int b=10;
4. int c= -10;
5. printf("Value of b is:%u", b);
6. printf("\nValue of c is:%u",c);
7.
8. return 0;
9. }
In the above program, we are displaying the value of b and c by using an unsigned
format specifier, i.e., %u. The value of b is positive, so %u specifier prints the exact
value of b, but it does not print the value of c as c contains the negative value.
Output
o %o
1. int main()
2. {
3. int a=0100;
4. printf("Octal value of a is: %o", a);
5. printf("\nInteger value of a is: %d",a);
6. return 0;
7. }
In the above code, we are displaying the octal value and integer value of a.
Output
o %x and %X
1. int main()
2. {
3. int y=0xA;
4. printf("Hexadecimal value of y is: %x", y);
5. printf("\nHexadecimal value of y is: %X",y);
6. printf("\nInteger value of y is: %d",y);
7. return 0;
8. }
In the above code, y contains the hexadecimal value 'A'. We display the
hexadecimal value of y in two formats. We use %x and %X to print the
hexadecimal value where %x displays the value in small letters, i.e., 'a' and %X
displays the value in a capital letter, i.e., 'A'.
Output
o %f
1. int main()
2. {
3. float y=3.4;
4. printf("Floating point value of y is: %f", y);
5. return 0;
6. }
Output
o %e
1. int main()
2. {
3. float y=3;
4. printf("Exponential value of y is: %e", y);
5. return 0;
6. }
Output
o %E
1. int main()
2. {
3. float y=3;
4. printf("Exponential value of y is: %E", y);
5. return 0;
6. }
Output
o %g
1. int main()
2. {
3. float y=3.8;
4. printf("Float value of y is: %g", y);
5. return 0;
6. }
In the above code, we are displaying the floating value of y by using %g specifier.
The %g specifier displays the output same as the input with a same precision.
Output
o %p
1. int main()
2. {
3. int y=5;
4. printf("Address value of y in hexadecimal form is: %p", &y);
5. return 0;
6. }
Output
o %c
1. int main()
2. {
3. char a='c';
4. printf("Value of a is: %c", a);
5. return 0;
6. }
Output
o %s
1. int main()
2. {
3. printf("%s", "javaTpoint");
4. return 0;
5. }
Output
In the above program, %8d specifier displays the value after 8 spaces while %-8d
specifier will make a value left-aligned.
Output
Now we will see how to fill the empty spaces. It is shown in the below
code:
1. int main()
2. {
3. int x=12;
4. printf("%08d", x);
5. return 0;
6. }
In the above program, %08d means that the empty space is filled with zeroes.
Output
Specifying Precision
We can specify the precision by using '.' (Dot) operator which is followed by
integer and format specifier.
1. int main()
2. {
3. float x=12.2;
4. printf("%.2f", x);
5. return 0;
6. }
Output
bi
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?"
ASCII value in C
What is ASCII code?
The full form of ASCII is the American Standard Code for information
interchange. It is a character encoding scheme used for electronics
communication. Each character or a special character is represented by some
ASCII code, and each ascii code occupies 7 bits in memory.
In the above example, we assign 'A' to the character variable whose ascii value is
65, so 65 will be stored in the character variable rather than 'A'.
We will create a program which will display the ascii value of the
character variable.
1. #include <stdio.h>
2.
3. int main()
4. {
5. char ch; // variable declaration
6.
7. printf("\n Enter a character");
8. scanf("%c",&ch); // user input
9. printf("\n The ascii value of the ch variable is : %d", ch);
10. Return 0;
11. }
In the above code, the first user will give the character input, and the input will get
stored in the 'ch' variable. If we print the value of the 'ch' variable by using %c
format specifier, then it will display 'A' because we have given the character input
as 'A', and if we use the %d format specifier then its ascii value will be displayed,
i.e., 65.
Output
The above output shows that the user gave the input as 'A', and after giving input,
the ascii value of 'A' will get printed, i.e., 65.
Now, we will create a program which will display the ascii value of all the
characters.
1. #include <stdio.h>
2. int main()
3. {
4. int k; // variable declaration
5. for(int k=0;k<=255;k++) // for loop from 0-255
6. {
7. printf("\nThe ascii value of %c is %d", k,k);
8. }
9. return 0;
10.}
The above program will display the ascii value of all the characters. As we know
that ascii value of all the characters starts from 0 and ends at 255, so we iterate
the for loop from 0 to 255.
Now we will create the program which will sum the ascii value of a string.
1. #include <stdio.h>
2. int main()
3. {
4. int sum=0; // variable initialization
5. char name[20]; // variable initialization
6. int i=0; // variable initialization
7. printf("Enter a name: ");
8. scanf("%s", name);
9. while(name[i]!='\0') // while loop
10. {
11. printf("\nThe ascii value of the character %c is %d", name[i],name
[i]);
12. sum=sum+name[i];
13. i++;
14. }
15. printf("\nSum of the ascii value of a string is : %d", sum);
16. return 0;
17. }
In the above code, we are taking user input as a string. After taking user input, we
execute the while loop which adds the ascii value of all the characters of a string
and stores it in a 'sum' variable.
Output
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:
Compile Time Error: Cannot modify a const object
2) C #define preprocessor
The #define preprocessor is also used to define constant. We will learn about
#define preprocessor directive later.
Types of literals
There are four types of literals that exist in C programming:
o Integer literal
o Float literal
o Character literal
o String literal
Integer literal
It is a numeric literal that represents only integer type values. It represents the
value neither in fractional nor exponential part.
It is defined by representing the digits between 0 to 9. For example, 45, 67, etc.
L or l: It is a size qualifier that specifies the size of the integer type as long.
U or u: It is a sign qualifier that represents the type of the integer as unsigned. An
unsigned qualifier contains only positive values.
Note: The order of the qualifier is not considered, i.e., both lu and ul are the same.
1. #include <stdio.h>
2. int main()
3. {
4. const int a=23; // constant integer literal
5. printf("Integer literal : %d", a);
6. return 0;
7. }
Output
Integer literal : 23
Float literal
It is a literal that contains only floating-point values or real numbers. These real
numbers contain the number of parts such as integer part, real part, exponential
part, and fractional part. The floating-point literal must be specified either in
decimal or in exponential form. Let's understand these forms in brief.
Decimal form
The decimal form must contain either decimal point, exponential part, or both. If it
does not contain either of these, then the compiler will throw an error. The decimal
notation can be prefixed either by '+' or '-' symbol that specifies the positive and
negative numbers.
1. #include <stdio.h>
2. int main()
3. {
4. const float a=4.5; // constant float literal
5. const float b=5.6; // constant float literal
6. float sum;
7. sum=a+b;
8. printf("%f", sum);
9. return 0;
10.}
Output
10.100000
Exponential form
The exponential form is useful when we want to represent the number, which is
having a big magnitude. It contains two parts, i.e., mantissa and exponent. For
example, the number is 2340000000000, and it can be expressed as 2.34e12 in an
exponential form.
The following are the rules for creating a float literal in exponential
notation:
Character literal
1. #include <stdio.h>
2. int main()
3. {
4. const char c='ak';
5. printf("%c",c);
6. return 0;
7. }
In the above code, we have used two characters, i.e., 'ak', within single quotes. So,
this statement will generate a warning as shown below.
Warning generated:
String literal
For example,
String1= "javatpoint";
String2= "family";
To concatenate the above two strings, we use '+' operator, as shown in the below
statement:
Programming Errors in C
Errors are the problems or the faults that occur in the program, which makes the
behavior of the program abnormal, and experienced developers can also make
these faults. Programming errors are also known as the bugs or faults, and the
process of removing these bugs is known as debugging.
These errors are detected either during the time of compilation or execution. Thus,
the errors must be removed from the program for the successful execution of the
program.
o Syntax error
o Run-time error
o Linker error
o Logical error
o Semantic error
Syntax error
Syntax errors are also known as the compilation errors as they occurred at the
compilation time, or we can say that the syntax errors are thrown by the
compilers. These errors are mainly occurred due to the mistakes while typing or do
not follow the syntax of the specified programming language. These mistakes are
generally made by beginners only because they are new to the language. These
errors can be easily debugged or corrected.
For example:
1. #include <stdio.h>
2. int main()
3. {
4. a = 10;
5. printf("The value of a is : %d", a);
6. return 0;
7. }
Output
In the above output, we observe that the code throws the error that 'a' is
undeclared. This error is nothing but the syntax error only.
There can be another possibility in which the syntax error can exist, i.e., if we
make mistakes in the basic construct. Let's understand this scenario through an
example.
1. #include <stdio.h>
2. int main()
3. {
4. int a=2;
5. if(.) // syntax error
6.
7. printf("a is greater than 1");
8. return 0;
9. }
In the above code, we put the (.) instead of condition in 'if', so this generates the
syntax error as shown in the below screenshot.
Output
Run-time error
Sometimes the errors exist during the execution-time even after the successful
compilation known as run-time errors. When the program is running, and it is not
able to perform the operation is the main cause of the run-time error. The division
by zero is the common example of the run-time error. These errors are very
difficult to find, as the compiler does not point to these errors.
1. #include <stdio.h>
2. int main()
3. {
4. int a=2;
5. int b=2/0;
6. printf("The value of b is : %d", b);
7. return 0;
8. }
Output
In the above output, we observe that the code shows the run-time error, i.e.,
division by zero.
Linker error
Linker errors are mainly generated when the executable file of the program is not
created. This can be happened either due to the wrong function prototyping or
usage of the wrong header file. For example, the main.c file contains
the sub() function whose declaration and definition is done in some other file such
as func.c. During the compilation, the compiler finds the sub() function
in func.c file, so it generates two object files, i.e., main.o and func.o. At the
execution time, if the definition of sub() function is not found in the func.o file,
then the linker error will be thrown. The most common linker error that occurs is
that we use Main() instead of main().
1. #include <stdio.h>
2. int Main()
3. {
4. int a=78;
5. printf("The value of a is : %d", a);
6. return 0;
7. }
Output
Logical error
The logical error is an error that leads to an undesired output. These errors
produce the incorrect output, but they are error-free, known as logical errors.
These types of mistakes are mainly done by beginners. The occurrence of these
errors mainly depends upon the logical thinking of the developer. If the
programmers sound logically good, then there will be fewer chances of these
errors.
1. #include <stdio.h>
2. int main()
3. {
4. int sum=0; // variable initialization
5. int k=1;
6. for(int i=1;i<=10;i++); // logical error, as we put the semicolon after loop
7. {
8. sum=sum+k;
9. k++;
10. }
11. printf("The value of sum is %d", sum);
12. return 0;
13. }
Output
In the above code, we are trying to print the sum of 10 digits, but we got the
wrong output as we put the semicolon (;) after the for loop, so the inner
statements of the for loop will not execute. This produces the wrong output.
Semantic error
Semantic errors are the errors that occurred when the statements are not
understandable by the compiler.
1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. a=2;
6. b=3;
7. c=1;
8. a+b=c; // semantic error
9. return 0;
10.}
In the above code, we use the statement a+b =c, which is incorrect as we cannot
use the two operands on the left-side.
Output
BASIC C PROGRAMS
#include <stdio.h>
int main()
{
printf("Hello World!"); // printf() is use to display string
return 0;
}
#include<stdio.h>
int main()
{
int num1,num2,temp;
temp = num1;
num1 = num2;
num2 = temp;
#include<stdio.h>
Int main()
{
double num1, num2, total;
printf("Enter two numbers: ");
return 0;
}
int main()
{
int num1, num2;
int sum, sub, mult, mod;
float div;
return 0;
}
return 0;
}
#include <stdio.h>
int main()
{
float celsius, fahrenheit;
return 0;
}
#include <stdio.h>
int main()
{
char c;
short s;
int a;
long l;
float b;
double g;
return 0;
}
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
#include <stdio.h>
int main()
{
/*write a c program to find area and circumference of circle*/
int rad;
float PI = 3.14, area, ci;
ci = 2 *PI * rad;
printf("\nCircumference of Circle : %f ", ci);
return (0);
}
#include <stdio.h>
int main()
{
int days, years, weeks;
return 0;
}
12. Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40%
of basic salary, and house rent allowance is 20% of basic salary. Write a program to
calculate his gross salary.
#include <stdio.h>
void main()
{
float basic,da,hra,gs;
clrscr();
da=basic*40/100;
hra=basic*20/100;
gs=basic+da+hra;
13. If the marks obtained by a student in five different subjects are input through the
keyboard, write a program to find out the Total marks and percentage marks
obtained by the student. Assume that the maximum marks that can be obtained by a
student in each subject is 100.
#include <stdio.h>
void main()
{
int m1,s1,e1,c1,h1,total;
float perc;
total=m1+s1+e1+c1+h1;
perc=total/5;
14. Write a C program to calculate Net Amount of product, enter Product name,
quantity and price of per product. Tax is 2.5% of amount, Discount is 5% of amount,
find Net amount=Amount + Tax - discount. Display Invoice.
15. Calculate Simple Interest based on formula SI=p*n*r/100, Enter the value of
Principle amount, no. of years and rate of interest.
IF…ELSE STATEMENT
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.
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
Let's see a simple example of C language if statement.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("Enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. return 0;
10.}
Output
Enter a number:4
4 is even number
enter a number:5
Output
If-else Statement
The if-else statement is used to perform two operations for a single condition. The
if-else statement is an extension to the if statement using which, we can perform
two different operations, i.e., one is for the correctness of that condition, and the
other is for the incorrectness of the condition. Here, we must notice that if and else
block cannot be executed simiulteneously. Using if-else statement is always
preferable since it always invokes an otherwise case with every if condition. The
syntax of the if-else statement is given below.
1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
5. }
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
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.}
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
Programs:
int main()
{
int A;
if (A > 0)
printf("%d is positive.", A);
else if (A < 0)
printf("%d is negative.", A);
else
printf("%d is zero.", A);
return 0;
}
return 0;
}
return 0;
}
#include <stdio.h>
int main()
{
int cp,sp, amt;
return 0;
}
Switch
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.}
PlayNext
Unmute
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
3) The case value can be used only inside the switch statement.
Let's try to understand it by the examples. We are assuming that there are
following variables.
1. int x,y,z;
2. char a,b;
3. float f;
Valid Switch Invalid Switch Valid Case Invalid Case
case '-':
printf("%d - %d = %d\n", x, y, x - y);
break;
case '*':
printf("%d * %d = %d\n", x, y, x * y);
break;
case '/':
printf("%d / %d = %d\n", x, y, x / y);
break;
default:
printf("Invalid Operator Input\n");
}
}
return 0;
}
Output
Enter the operator (+, -, *, /)
+
Enter the two numbers: 100 + 200
100 + 200 = 300
// Driver Code
int main()
{
int day;
printf(“\n Enter day number:”);
scanf(“%d”,&day);
C Loops
The looping can be defined as repeating the same process multiple times until a
specific condition satisfies. There are three types of loops used in the C language.
In this part of the tutorial, we are going to learn all the aspects of C loops.
Advantage of loops in C
1) It provides code reusability.
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or
linked lists).
Types of C Loops
There are three types of loops in C language that is given below:
1. do while
2. while
3. for
do-while loop in C
The do-while loop continues until a given condition satisfies. It is also called post
tested loop. It is used when it is necessary to execute the loop at least once
(mostly menu driven programs).
1. do{
2. //code to be executed
3. }while(condition);
while loop in C
The while loop in c is to be used in the scenario where we don't know the number
of iterations in advance. The block of statements is executed in the while loop until
the condition specified in the while loop is satisfied. It is also called a pre-tested
loop.
1. while(condition){
2. //code to be executed
3. }
for loop in C
The for loop is used in the case where we need to execute some part of the code
until the given condition is satisfied. The for loop is also called as a per-tested loop.
It is better to use for loop if the number of iteration is known in advance.
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
Infinitive do while loop
The do-while loop will run infinite times if we pass any non-zero value as the
conditional expression.
1. do{
2. //statement
3. }while(1);
while loop in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part
of the code to be executed multiple times depending upon a given boolean
condition. It can be viewed as a repeating if statement. The while loop is mostly
used in the case where the number of iterations is not known in advance.
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
Program to print table for the given number using while loop
in C
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0,b=9;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. while(i<=10){
7. printf("%d \n",(number*i));
8. i++;
9. }
10.return 0;
11. }
Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
500
600
700
800
900
1000
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
C Program: Print table for the given number using C for loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. for(i=1;i<=10;i++){
7. printf("%d \n",(number*i));
8. }
9. return 0;
10.}
Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Enter a number: 1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Properties of Expression 1
o The expression represents the initialization of the loop variable.
o We can initialize more than one variable in Expression 1.
o Expression 1 is optional.
o In C, we can not declare the variables in Expression 1. However, It can be an
exception in some compilers.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. for(a=0,b=12,c=23;a<2;a++)
6. {
7. printf("%d ",a+b+c);
8. }
9. }
Output
35 36
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int i=1;
5. for(;i<5;i++)
6. {
7. printf("%d ",i);
8. }
9. }
Output
1 2 3 4
Properties of Expression 2
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
1. #include<stdio.h>
2. void main ()
3. {
4. for(;;)
5. {
6. printf("welcome to javatpoint");
7. }
8. }
Nested Loops in C
defining any number of loops. The nesting level can be defined at n times. You can
define any type of loop inside another loop; for example, you can define 'while'
loop inside a 'for' loop.
1. Outer_loop
2. {
3. Inner_loop
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while'
loop or 'do-while' loop.
The nested for loop means any type of loop which is defined inside the 'for' loop.
1. #include <stdio.h>
2. int main()
3. {
4. int n;// variable declaration
5. printf("Enter the value of n :");
6. // Displaying the n tables.
7. for(int i=1;i<=n;i++) // outer loop
8. {
9. for(int j=1;j<=10;j++) // inner loop
10. {
11. printf("%d\t",(i*j)); // printing the value.
12. }
13. printf("\n");
14. }
o First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
o The program control checks whether the condition 'i<=n' is true or not.
o If the condition is true, then the program control passes to the inner loop.
o The inner loop will get executed until the condition is true.
o After the execution of the inner loop, the control moves back to the update of the
outer loop, i.e., i++.
o After incrementing the value of the loop counter, the condition is checked again,
i.e., i<=n.
o If the condition is true, then the inner loop will be executed again.
o This process will continue until the condition of the outer loop is true.
Output:
Nested while loop
The nested while loop means any type of loop which is defined inside the 'while'
loop.
1. while(condition)
2. {
3. while(condition)
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
1. #include <stdio.h>
2. int main()
3. {
4. int rows; // variable declaration
5. int columns; // variable declaration
6. int k=1; // variable initialization
7. printf("Enter the number of rows :"); // input the number of rows.
8. scanf("%d",&rows);
9. printf("\nEnter the number of columns :"); // input the number of columns.
10. scanf("%d",&columns);
11. int a[rows][columns]; //2d array declaration
12. int i=1;
13. while(i<=rows) // outer loop
14. {
15. int j=1;
16. while(j<=columns) // inner loop
17. {
18. printf("%d\t",k); // printing the value of k.
19. k++; // increment counter
20. j++;
21. }
22. i++;
23. printf("\n");
24. }
25. }
Output:
The nested do..while loop means any type of loop which is defined inside the
'do..while' loop.
1. do
2. {
3. do
4. {
5. // inner loop statements.
6. }while(condition);
7. // outer loop statements.
8. }while(condition);
1. #include <stdio.h>
2. int main()
3. {
4. /*printing the pattern
5. ********
6. ********
7. ********
8. ******** */
9. int i=1;
10.do // outer loop
11. {
12. int j=1;
13. do // inner loop
14. {
15. printf("*");
16. j++;
17. }while(j<=8);
18. printf("\n");
19. i++;
20. }while(i<=4);
21. }
Output:
Explanation of the above code.
Infinite Loop in C
What is infinite loop?
An infinite loop is a looping construct that does not terminate the loop and
executes the loop forever. It is also called an indefinite loop or an endless loop.
It either produces a continuous output or no output.
o All the operating systems run in an infinite loop as it does not exist after performing
some task. It comes out of an infinite loop only when the user manually shuts down
the system.
o All the servers run in an infinite loop as the server responds to all the client
requests. It comes out of an indefinite loop only when the administrator shuts down
the server manually.
o All the games also run in an infinite loop. The game will accept the user requests
until the user exits from the game.
We can create an infinite loop through various loop structures. The following are
the loop structures through which we will define the infinite loop:
o for loop
o while loop
o do-while loop
o go to statement
o C macros
For loop
Let's see the infinite 'for' loop. The following is the definition for the infinite for
loop:
1. for(; ;)
2. {
3. // body of the for loop.
4. }
As we know that all the parts of the 'for' loop are optional, and in the above for
loop, we have not mentioned any condition; so, this loop will execute infinite
times.
1. #include <stdio.h>
2. int main()
3. {
4. for(;;)
5. {
6. printf("Hello javatpoint");
7. }
8. return 0;
9. }
In the above code, we run the 'for' loop infinite times, so "Hello javatpoint" will
be displayed infinitely.
Output
while loop
Now, we will see how to create an infinite loop using a while loop. The following is
the definition for the infinite while loop:
1. while(1)
2. {
3. // body of the loop..
4. }
In the above while loop, we put '1' inside the loop condition. As we know that any
non-zero integer represents the true condition while '0' represents the false
condition.
1. #include <stdio.h>
2. int main()
3. {
4. int i=0;
5. while(1)
6. {
7. i++;
8. printf("i is :%d",i);
9. }
10.return 0;
11. }
In the above code, we have defined a while loop, which runs infinite times as it
does not contain any condition. The value of 'i' will be updated an infinite number
of times.
Output
do..while loop
The do..while loop can also be used to create the infinite loop. The following is
the syntax to create the infinite do..while loop.
1. do
2. {
3. // body of the loop..
4. }while(1);
The above do..while loop represents the infinite condition as we provide the '1'
value inside the loop condition. As we already know that non-zero integer
represents the true condition, so this loop will run infinite times.
goto statement
We can also use the goto statement to define the infinite loop.
1. infinite_loop;
2. // body statements.
3. goto infinite_loop;
In the above code, the goto statement transfers the control to the infinite loop.
Macros
We can also create the infinite loop with the help of a macro constant. Let's
understand through an example.
1. #include <stdio.h>
2. #define infinite for(;;)
3. int main()
4. {
5.
6. infinite
7. {
8. printf("hello");
9. }
10.
11. return 0;
12.}
In the above code, we have defined a macro named as 'infinite', and its value is
'for(;;)'. Whenever the word 'infinite' comes in a program then it will be replaced
with a 'for(;;)'.
Output
Till now, we have seen various ways to define an infinite loop. However, we need
some approach to come out of the infinite loop. In order to come out of the infinite
loop, we can use the break statement.
1. #include <stdio.h>
2. int main()
3. {
4. char ch;
5. while(1)
6. {
7. ch=getchar();
8. if(ch=='n')
9. {
10. break;
11. }
12. printf("hello");
13. }
14. return 0;
15. }
In the above code, we have defined the while loop, which will execute an infinite
number of times until we press the key 'n'. We have added the 'if' statement inside
the while loop. The 'if' statement contains the break keyword, and the break
keyword brings control out of the loop.
Sometimes the situation arises where unintentional infinite loops occur due to the
bug in the code. If we are the beginners, then it becomes very difficult to trace
them. Below are some measures to trace an unintentional infinite loop:
o We should examine the semicolons carefully. Sometimes we put the semicolon at
the wrong place, which leads to the infinite loop.
1. #include <stdio.h>
2. int main()
3. {
4. int i=1;
5. while(i<=10);
6. {
7. printf("%d", i);
8. i++;
9. }
10.return 0;
11. }
In the above code, we put the semicolon after the condition of the while loop which
leads to the infinite loop. Due to this semicolon, the internal body of the while loop
will not execute.
1. #include <stdio.h>
2. int main()
3. {
4. char ch='n';
5. while(ch='y')
6. {
7. printf("hello");
8. }
9. return 0;
10.}
In the above code, we use the assignment operator (ch='y') which leads to the
execution of loop infinite number of times.
o We use the wrong loop condition which causes the loop to be executed indefinitely.
1. #include <stdio.h>
2. int main()
3. {
4. for(int i=1;i>=1;i++)
5. {
6. printf("hello");
7. }
8. return 0;
9. }
The above code will execute the 'for loop' infinite number of times. As we put the
condition (i>=1), which will always be true for every condition, it means that
"hello" will be printed infinitely.
o We should be careful when we are using the break keyword in the nested loop
because it will terminate the execution of the nearest loop, not the entire loop.
1. #include <stdio.h>
2. int main()
3. {
4. while(1)
5. {
6. for(int i=1;i<=10;i++)
7. {
8. if(i%2==0)
9. {
10. break;
11. }
12. }
13. }
14. return 0;
15. }
In the above code, the while loop will be executed an infinite number of times as
we use the break keyword in an inner loop. This break keyword will bring the
control out of the inner loop, not from the outer loop.
o We should be very careful when we are using the floating-point value inside the
loop as we cannot underestimate the floating-point errors.
1. #include <stdio.h>
2. int main()
3. {
4. float x = 3.0;
5. while (x != 4.0) {
6. printf("x = %f\n", x);
7. x += 0.1;
8. }
9. return 0;
10.}
In the above code, the loop will run infinite times as the computer represents a
floating-point value as a real value. The computer will represent the value of 4.0 as
3.999999 or 4.000001, so the condition (x !=4.0) will never be false. The solution
to this problem is to write the condition as (k<=4.0).
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
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.
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 no
n-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
1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. if(i==5){//if value of i is equal to 5, it will continue the loop
7. continue;
8. }
9. printf("%d \n",i);
10. }//end of for loop
11. return 0;
12. }
Loops Programs
1. Find Factorial of a Number
#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}
Output:
Output:
Enter a number:654
Sum is=15
Enter a number:123
Sum is=6
#include <stdio.h>
int main()
{
int i, n;
return 0;
}
#include <stdio.h>
int main()
{
char ch;
return 0;
}
6.Check whether number is palindrome or not.
1. #include<stdio.h>
2. int main()
3. {
4. int n,r,rev=0,temp;
5. printf("enter the number=");
6. scanf("%d",&n);
7. temp=n;
8. while(n>0)
9. {
10. r=n%10;
11. rev=(rev*10)+r;
12. n=n/10;
13. }
14. if(temp==rev)
15. printf("palindrome number ");
16. else
17. printf("not palindrome");
18. return 0;
19. }
Output:
7. Fibonacci Series in C
1. #include<stdio.h>
2. int main()
3. {
4. int n1=0,n2=1,n3,i,number;
5. printf("Enter the number of elements:");
6. scanf("%d",&number);
7. printf("\n%d %d",n1,n2);//printing 0 and 1
8. for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already prin
ted
9. {
10. n3=n1+n2;
11. printf(" %d",n3);
12. n1=n2;
13. n2=n3;
14. }
15. return 0;
16. }
Output:
star.c
1. #include <stdio.h>
2. #include <conio.h>
3. void main()
4. {
5. int i, j, rows;
6. printf (" Enter a number to define the rows: \n ");
7. scanf("%d", &rows);
8. printf("\n");
9. for (i = 1; i <= rows; ++i) // outer loop
10. {
11.
for (j = 1; j <= i; ++j) // inner loop
12. {
13. printf ("* "); // print the Star
14. }
15. printf ("\n");
16. }
17. getch();
18.}
Output
9. Star Pattern
1. #include <stdio.h>
2. #include <conio.h>
3. void main()
4. {
5.
6. int i, j, rows, k = 0;
7. printf (" Enter a number to define the rows: \n");
8. scanf ("%d", &rows);
9.
10. for ( i =1; i <= rows; i++)
11. {
12. for ( j = 1; j <= rows - i; j++)
13. {
14. printf (" ");
15. }
16. // use for loop where k is less than equal to (2 * i -1)
17. for ( k = 1; k <= ( 2 * i - 1); k++)
18. {
19. printf ("* "); // print the Star
20. }
21. printf ("\n");
22. }
23. getch();
24.}
Output
10. Program to print the half Pyramid of number
1. #include <stdio.h>
2. #include <conio.h>
3. void main()
4. {
5. // declare the local variables
6. int i, j, rows;
7. printf (" Enter a number to define the rows: \n ");
8. scanf("%d", &rows);
9. printf("\n");
10. for (i = 1; i <= rows; ++i)
11. {
12. for (j = 1; j <= i; ++j)
13. {
14. printf ("%d ", j);
15. }
16. printf ("\n");
17. }
18. getch();
19. }
Output
11. Number Pattern
1. #include <stdio.h>
2. #include <conio.h>
3. void main()
4. {
5. // declare the local variables
6. int i, j, rows;
7. printf (" Enter a number to define the rows: \n ");
8. scanf("%d", &rows);
9. printf("\n");
10. for (i = 1; i <= rows; ++i)
11. {
12. for (j = 1; j <= i; ++j)
13. {
14. printf ("%d ", i); // print the number
15. }
16. printf ("\n");
17. }
18. getch();
19. }
Output
C Array
An array is defined as the collection of similar type of data items stored at
contiguous memory locations. Arrays are the derived data type in C programming
language which can store the primitive type of data such as int, char, double, float,
etc. It also has the capability to store the collection of derived data types, such as
pointers, structure, etc. The array is the simplest data structure where each data
element can be randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want
to store the marks of a student in 6 subjects, then we don't need to define
different variables for the marks in the different subject. Instead of that, we can
define an array which can store the marks in each subject at the contiguous
memory locations.
By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.
Properties of Array
The array contains the following properties.
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
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an
array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code
only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we
can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList
which we will learn later.
Declaration of C Array
We can declare an array in the c language in the following way.
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};
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
Sorting an array
In the following program, we are using bubble sort method to sort the array in
ascending order.
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[i] > a[j])
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. }
/*
* C Program to find the largest number in an array using loops
*/
#include <stdio.h>
int main()
{
int size, i, largest;
return 0;
}
#include<stdio.h>
int main()
int n;
scanf(“%d”,&n);
int arr[n];
int i;
for(i = 0; i < n; i++)
scanf(“%d”,&arr[i]);
printf(“%d\n”,arr[i]);
return 0;
void main()
int a[100];
int i, n, sum=0;
printf("--------------------------------------\n");
scanf("%d",&n);
printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
printf("element - %d : ",i);
scanf("%d",&a[i]);
sum += a[i];
Sample Output:
Find sum of all elements of array:
--------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 2
element - 1 : 5
element - 2 : 8
Sum of all elements stored in the array is : 15
#include<stdio.h>
main()
{
int i,size;
printf("Enter size of array\n");
scanf("%d",&size);
int a[size];
printf("Enter numbers to separate even and odd\n");
for(i=0;i<size;i++)
{
scanf("%d",&a[i]);
}
printf("Even numbers are:\n");
for(i=0;i<size;i++)
{
if(a[i]>=0)
{
if(a[i]%2==0)
{
printf("%d\n",a[i]);
}
}
}
}
}
}
for(j=size1,i=0;i<size2;i++)
{
c[j]=b[i];
j++;
}
printf("Array after merging\n");
for(i=0;i<size1+size2;i++)
{
printf("%d\n",c[i]);
}
//Sorting
for(i=0;i<size1+size2;i++)
{
for(j=i+1;j<size1+size2;j++)
{
if(c[i]>c[j])
{
temp=c[i];
c[i]=c[j];
c[j]=temp;
}
}
}
printf("Array afetr sorting the merged array\n");
for(i=0;i<size1+size2;i++)
{
printf("%d\n",c[i]);
}
}
Output:
2-D Array:
Write a Program in c to Add all element of 2D Array
\* C Program to to Add all element of 2D Array *\
int i,j,r,c,sum=0;
printf(“\n Enter No. of rows:”);
scanf(“%d”,&r);
Ans.
return 0;
}
/************************************************************
The output of above Addition of two 3x3 martix C program would be:
***********************************************************/
Figure: Screen shot for addition of two 3x3 matrix
C program
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. By char array
2. By string literal
1. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
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
Output
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. }
Output
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: 0
Your name is: Sonoo Jaiswal
C String Functions
There are many important string functions defined in "string.h" library.
It reads a single character from input device i.e. stdin. This function is defined in <stdio.h>
header file.
Usage: var_name=getchar( );
The characters accepted by getchar( ) are buffered until RETURN is hit. It is a buffered
function. The buffered function gets the input from the keyboard and store it in the memory
buffer temporally until user press the Enter key.
It means getchar( ) requires Enter key to be pressed following the character that you typed. It
echoes typed character. If an end-of-file(EOF) condition error occurs, getchar() returns EOF.
2. putchar():
It displays or writes a single character to the standard output device or screen at the current
cursor position. This function is defined in <stdio.h> header file.
The putchar( ) function returns the character written or EOF if an error occurs.
Example:
//Learnprogramo
#include<stdio.h>
int main()
char x;
x=getchar();
putchar(x);
return 0;
}
Output:
If we input any character say j then output is j. So the output is: y /* the keypress is echoed on
the screen */ y
This function is used to read a character from the console but does not echo to the screen.
This function is included in header file <conio.h>
Usage: var_name=getch( );
getch() function is a non-buffered function. It does not use any buffer, so the entered character
is immediately returned without waiting for the enter key.
The character data read by this function is directly assigned to a variable rather it goes to the
memory buffer.
Another use of this function is to maintain the output on the screen until you have not to press
the Enter key. getch() works only on dos like TC compiler. It does not work on a Linux
platform.
2. getche():
getche( ) function is used to read a character from the console and echoes that character to
the screen. This function is included in header file <conio.h>.
Usage: var_name=getche( );
It does not use any buffer, so the entered character is immediately returned without waiting for
the enter key. getche() works only on DOS-like TC compiler. It does not work on a Linux
platform.
The main difference between getch() and getche() is getch() does not echo character after
reading, while getche() echoes character after reading.
3. putch():
putch() function displays or writes single character to the standard output device(i.e. stdout).
This function is defined in <conio.h> header file.
Usage: putch(var_name);
putch() does not translate linefeed characters (\n) into carriage-return/linefeed pairs. The
putch() function returns the character written or EOF if an error occurs.
//Learnprogramo
#include<stdio.h>
#include<conio.h>
int main()
char x;
x=getch();
putch(x);
return 0;
}
Output:
1. gets():
gets() function accepts single or multiple characters of string including spaces from the
standard input device until ENTER key is pressed. This function in <stdio.h> header file.
Syntax: gets(var_name);
gets() is also buffered function. It will read a string from the keyboard until the user presses the
Enter key from the keyboard. It will mark the null character (‘\0’) in the memory at the string
when you press the enter key.
gets stops when either the newline character is read or when the end-of-file(EOF) is reached,
whichever comes first.
2. puts():
puts() function displays or writes a string to the standard output device. It appends a newline
character to string. This function is defined in <stdio.h> header file.
Syntax: puts(var_name);
//Learnprogramo
#include<stdio.h>
int main()
char name[20];
gets(name);
puts("Name is:");
puts(name);
return 0;
}
Output:
Function Operation
getche() Reads a character with echo and do not wait for return.
getch() Reads a character without echo and do not wait for return.
putchar(
Writes a character to the screen.
)
int main() {
char s1[] = "TajMahal"; // String Given
char s2[8]; // Variable to hold value
int length = 0;
while(s1[length] != '\0') {
s2[length] = s1[length];
length++;
}
return 0;
}
Output
Output of this program should be −
Value in s1 = TajMahal
Value in s2 = TajMahal
int main() {
char s1[] = "TajMahal"; // String Given
char s2[8]; // Variable to store reverse string
while(s1[length] != '\0') {
length++;
}
loop = 0;
while(length >= 0) {
s2[length] = s1[loop];
length--;
loop++;
}
printf("%s\n", s2);
return 0;
}
Output
Output of this program should be −
Printing in reverse - lahaMjaT
Storing in reverse - lahaMjaT
int main() {
char s1[] = "advise";
char s2[] = "advice";
int n = 0;
unsigned short flag = 1;
if(flag == 1) {
printf("%s and %s are identical\n", s1, s2);
} else {
printf("%s and %s are NOT identical\n", s1, s2);
}
return 0;
}
Output
Output of this program should be −
advise and advice are NOT identical
#include <stdio.h>
#include <string.h>
int main() {
char s1[10] = "Taj";
char s2[] = "Mahal";
n1 = strlen(s1);
n2 = strlen(s2);
j = 0;
for(i = n1; i< n1+n2; i++ ) {
s1[i] = s2[j];
j++;
}
s1[i] = '\0';
printf("%s", s1);
return 0;
}
Output of this program should be −
TajMahal
C Functions
In c, we can divide a large program into the basic building blocks known as
function. The function contains the set of programming statements enclosed by
{}. A function can be called multiple times to provide reusability and modularity to
the C program. In other words, we can say that the collection of functions creates
a program. The function is also known as procedure or subroutine in other
programming languages.
Advantage of functions in C
There are the following advantages of C functions.
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 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.
S C function Syntax
N aspects
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.
1. #include<stdio.h>
2. void printName();
3. int main ()
4. {
5. printf("Hello ");
6. printName();
7. return 0;
8. }
9. void printName()
10. {
11. printf("Javatpoint");
12. }
Output
Hello Javatpoint
Example 2
1. #include<stdio.h>
2. void sum(); function declaration
3. int main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum(); function call
7. Return 0;
8. }
9. void sum() // definition
10.
11. {
12. int a,b,c;
13. printf(“\n Enter two Numbers:”);
14. scanf(“%d %d”,&a,&b);
15. c=a+b;
16. Printf(“\n Sum is:%d”,c);
17.}
Output
The sum is 34
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
1. #include<stdio.h>
2. int square();
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
1. #include<stdio.h>
2. void sum(int, int);
3. int main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10.}
11. void sum(int a, int b)
12.{
13. printf("\nThe sum is %d",a+b);
14.}
Output
The sum is 34
1. #include<stdio.h>
2. void average(int, int, int, int, int); // declaraction
3. int 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); // call
10.}
11. void average(int a, int b, int c, int d, int e) // defination
12.{
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16.}
Output
1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12.int sum(int a, int b)
13. {
14. return a+b;
15. }
Output
1. #include<stdio.h>
2. int even_odd(int);
3. void main()
4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("% d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18.}
19. int even_odd(int n)
20.{
21. if(n%2==0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }
Output
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.
S Header Description
N 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.
9 signal.h All the signal handling functions are defined in this header
file.
Power=Pow(base,exponent)
/* function declaration */
int max(int num1, int num2);
int main () {
return 0;
}
Recursion in C
Recursion is the process which comes into existence when a function calls a copy of
itself to work on a smaller problem. Any function which calls itself is called recursive
function, and such function calls are called recursive calls.
1. #include<stdio.h>
2.
3. long factorial(int n)
4. {
5. if (n == 0)
6. return 1;
7. else
8. return(n * factorial(n-1));
9. }
10. Long factorial(int);
11. void main()
12. {
13. int number;
14. long fact;
15. printf("Enter a number: ");
16. scanf("%d", &number);
17.
18. fact = factorial(number);
19. printf("Factorial of %d is %ld\n", number, fact);
20. return 0;
21. }
Output:
Enter a number: 6
Factorial of 5 is: 720
#include <stdio.h>
int fibonacci(int n) {
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return (fibonacci(n-1) + fibonacci(n-2));
}
int main() {
int n;
return 0;
}
0 1 1 2 3 5 8 13…
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.txt".
o The mode in which the file is to be opened. It is a string.
Mode Description
1. #include<stdio.h>
2. int 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.return 0;
16. }
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:
PlayNext
Unmute
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
Example:
1. #include <stdio.h>
2. Int 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:
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:
PlayNext
Unmute
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
Example:
1. #include <stdio.h>
2. Int main(){
3. FILE *fp;
4. fp = fopen("file1.txt", "w");//opening file
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. int main(){
4. FILE *fp;
5. char c;
6.
7. fp=fopen("myfile.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10.printf("%c",c);
11. }
12.fclose(fp);
13.
14.}
myfile.txt
PlayNext
Unmute
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
Syntax:
Example:
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5.
6.
7. fp=fopen("myfile2.txt","w");
8. fputs("hello c programming",fp);
9.
10.fclose(fp);
11.}
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. }
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
1. #include<stdio.h>
2. int main()
3. {
4. FILE *fp;
5. char c;
6.
7. fp=fopen("file.txt","r");
8.
9. while((c=fgetc(fp))!=EOF)
10. {
11.printf("%c",c);
12.
13. }
14.
15. rewind(fp);//moves the file pointer at beginning of the file
16.
17. while((c=fgetc(fp))!=EOF){
18.printf("%c",c);
19. }
20.
21. fclose(fp);
22. return 0;
23. }
Output:
As you can see, rewind() function moves the file pointer at beginning of the file
that is why "this is simple text" is printed 2 times. If you don't call rewind()
function, "this is simple text" will be printed only once.
C ftell() function
The ftell() function returns the current file position of the specified stream. We can
use ftell() function to get the total size of a file after moving file pointer at the end
of file. We can use SEEK_END constant to move the file pointer at the end of file.
Syntax:
Example:
File: ftell.c
1. #include <stdio.h>
2. int main ()
3. {
4. FILE *fp;
5. int length;
6. fp = fopen("file.txt", "r");
7. fseek(fp, 0, SEEK_END);
8. length = ftell(fp);
9. fclose(fp);
10. printf("Size of file: %d bytes", length);
11. Return 0;
12. }
Output:
Structure in C
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. };
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.
Here, struct is the keyword; employee is the name of the structure; id, name,
and salary are the members or fields of the structure. Let's understand it by the
diagram given below:
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.
AD
If no. of variables are fixed, use 2nd approach. It saves your code to declare a
variable in main() function.
AD
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:
AD
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, "Sonu Gupta");//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.000000
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.add.pin,emp.add.phone);
20.}
Output
Arun
Delhi
110001
1234567890
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
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,e1.doj.yyyy);
27. return 0;
28.}
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
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.pho
ne);
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. }
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.
memory can't be increased while executing memory can be increased while executing
program. program.
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.
17. printf("Sum=%d",sum);
18. free(ptr);
19. return 0;
20.}
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.
AD
1. ptr=realloc(ptr, new-size)
AD
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.
Use of realloc() in C
CProgrammingServer Side Programming
The function realloc is used to resize the memory block which is allocated by
malloc or calloc before.
Here is the syntax of realloc in C language,
void *realloc(void *pointer, size_t size)
Here,
pointer − The pointer which is pointing the previously allocated memory block by
malloc or calloc.
size − The new size of memory block.
Here is an example of realloc() in C language,
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
printf("
Error! memory not allocated.");
exit(0);
}
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("
Sum : %d", s);
p = (int*) realloc(p, 6);
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("
Sum : %d", s);
return 0;
}
Output
Enter elements of array : 3 34 28 8
Sum : 73
Enter elements of array : 3 28 33 8 10 15
Sum : 145
POINTERS
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.
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 th
erefore printing p gives the address of number.
7. printf("Value of p variable is %d \n",*p); // As we know that * is used to deref
erence a pointer therefore if we print *p, we will get the value stored at the a
ddress contained by p.
8. return 0;
9. }
Output
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.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many applications of pointers in c language.
AD
AD
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
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;
Output
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 co
ntained by p i.e. 10 will be printed
12. printf("value stored at pp: %d\n",**pp); // value stored at the address contained b
y 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
As you can see in the above figure, p2 contains the address of p (fff2), and p
contains the address of number variable (fff4).
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",*p2);
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 9of **p variable is 50
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
For 32-bit int variable, it will be incremented by 2 bytes.
64-bit
For 64-bit int variable, it will be incremented by 4 bytes.
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 in
cremented by 4 bytes.
9. return 0;
10.}
Output
Output
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:
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 i
mmidiate previous location.
9. }
Output
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer
is given below:
AD
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
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.
AD
AD
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
For 64-bit int variable, it will subtract 4 * number.
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.
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
AD
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
1. #include<stdio.h>
2. int show();
3. void showadd(int);
4. int (*arr[3])();
5. int (*(*ptr)[3])();
6.
7. int main ()
8. {
9. int result1;
10. arr[0] = show;
11. arr[1] = showadd;
12. ptr = &arr;
13. result1 = (**ptr)();
14. printf("printing the value returned by show : %d",result1);
15. (*(*ptr+1))(result1);
16.}
17. int show()
18.{
19. int a = 65;
20. return a++;
21. }
22.Void showadd(int b)
23. {
24. printf("\nAdding 90 to the value returned by show: %d",b+90);
25. }
Output
A null pointer is a special reserved value which is defined in a stddef header file.
Here, Null means that the pointer is referring to the 0 th memory location.
Let's look at the situations where we need to use the null pointer.
AD
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr;
5. printf("Address: %d", ptr); // printing the value of ptr.
6. printf("Value: %d", *ptr); // dereferencing the illegal pointer
7. return 0;
8. }
In the above code, we declare the pointer variable *ptr, but it does not contain the
address of any variable. The dereferencing of the uninitialized pointer variable will
show the compile-time error as it does not point any variable. According to the
stack memory concept, the local variables of a function are stored in the stack,
and if the variable does not contain any value, then it shows the garbage value.
The above program shows some unpredictable results and causes the program to
crash. Therefore, we can say that keeping an uninitialized pointer in a program can
cause serious harm to the computer.
We can avoid the above situation by using the Null pointer. A null pointer is a
pointer pointing to the 0th memory location, which is a reserved memory and
cannot be dereferenced.
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr=NULL;
5. if(ptr!=NULL)
6. {
7. printf("value of ptr is : %d",*ptr);
8. }
9. else
10. {
11. printf("Invalid pointer");
12. }
13. return 0;
14.}
In the above code, we create a pointer *ptr and assigns a NULL value to the
pointer, which means that it does not point any variable. After creating a pointer
variable, we add the condition in which we check whether the value of a pointer is
null or not.
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr;
5. ptr=(int*)malloc(4*sizeof(int));
6. if(ptr==NULL)
7. {
8. printf("Memory is not allocated");
9. }
10. else
11. {
12. printf("Memory is allocated");
13. }
14. return 0;
15. }
In the above code, we use the library function, i.e., malloc(). As we know, that
malloc() function allocates the memory; if malloc() function is not able to allocate
the memory, then it returns the NULL pointer. Therefore, it is necessary to add the
condition which will check whether the value of a pointer is null or not, if the value
of a pointer is not null means that the memory is allocated.
C Function Pointer
As we know that we can create a pointer of any data type such as int, char, float,
we can also create a pointer pointing to a function. The code of a function always
resides in memory, which means that the function has some address. We can get
the address of memory by using the function pointer.
1. #include <stdio.h>
2. int main()
3. {
4. printf("Address of main() function is %p",main);
5. return 0;
6. }
Output
In the above output, we observe that the main() function has some address.
Therefore, we conclude that every function has some address.
For example:
In the above declaration, *ip is a pointer that points to a function which returns an
int value and accepts an integer value as an argument.
Till now, we have learnt how to declare the function pointer. Our next step is to
assign the address of a function to the function pointer.
In the above declaration, 'fp' pointer contains the address of the 'func' function.
AD
Or
1. result = fp(a , b); // Calling a function using function pointer, and indirec
tion operator can be removed.
The effect of calling a function by its name or function pointer is the same. If we
are using the function pointer, we can omit the indirection operator as we did in
the second case. Still, we use the indirection operator as it makes it clear to the
user that we are using a function pointer.
1. #include <stdio.h>
2. int add(int,int);
3. int main()
4. {
5. int a,b;
6. int (*ip)(int,int);
7. int result;
8. printf("Enter the values of a and b : ");
9. scanf("%d %d",&a,&b);
10. ip=add;
11. result=(*ip)(a,b);
12. printf("Value after addition is : %d",result);
13. return 0;
14.}
15. int add(int a,int b)
16.{
17. int c=a+b;
18. return c;
19. }
Output
AD
1. include <stdio.h>
2. void func1(void (*ptr)());
3. void func2();
4. int main()
5. {
6. func1(func2);
7. return 0;
8. }
9. void func1(void (*ptr)())
10.{
11. printf("Function1 is called");
12. (*ptr)();
13. }
14.void func2()
15. {
16. printf("\nFunction2 is called");
17. }
In the above code, we have created two functions, i.e., func1() and func2(). The
func1() function contains the function pointer as an argument. In the main()
method, the func1() method is called in which we pass the address of func2. When
func1() function is called, 'ptr' contains the address of 'func2'. Inside the func1()
function, we call the func2() function by dereferencing the pointer 'ptr' as it
contains the address of func2.
Output
1. #include <stdio.h>
2. float add(float,int);
3. float sub(float,int);
4. float mul(float,int);
5. float div(float,int);
6. int main()
7. {
8. float x; // variable declaration.
9. int y;
10. float (*fp[4]) (float,int); // function pointer declaration.
11. fp[0]=add; // assigning addresses to the elements of an arra
y of a function pointer.
12. fp[1]=sub;
13. fp[2]=mul;
14. fp[3]=div;
15. printf("Enter the values of x and y :");
16. scanf("%f %d",&x,&y);
17. float r=(*fp[0]) (x,y); // Calling add() function.
18. printf("\nSum of two values is : %f",r);
19. r=(*fp[1]) (x,y); // Calling sub() function.
20. printf("\nDifference of two values is : %f",r);
21. r=(*fp[2]) (x,y); // Calliung sub() function.
22. printf("\nMultiplication of two values is : %f",r);
23. r=(*fp[3]) (x,y); // Calling div() function.
24. printf("\nDivision of two values is : %f",r);
25. return 0;
26.}
27.
28.float add(float x,int y)
29. {
30. float a=x+y;
31. return a;
32.}
33. float sub(float x,int y)
34.{
35. float a=x-y;
36. return a;
37. }
38.float mul(float x,int y)
39. {
40. float a=x*y;
41. return a;
42.}
43. float div(float x,int y)
44.{
45. float a=x/y;
46. return a;
47. }
In the above code, we have created an array of function pointers that contain the
addresses of four functions. After storing the addresses of functions in an array of
function pointers, we call the functions using the function pointer.
Output