C Programming Notes
C Programming Notes
• Clear and Unambiguous: Algorithm should be clear and unambiguous. Each of its
steps should be clear in all aspects and must lead to only one meaning.
• Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined
inputs.
• Well-Defined Outputs: The algorithm must clearly define what output will be yielded and
it should be well-defined as well.
• Finite-ness: The algorithm must be finite, i.e. it should not end up in an infinite loops or
similar.
• Feasible: The algorithm must be simple, generic and practical, such that it can be
executed upon will the available resources. It must not contain some future
technology, or anything.
• Language Independent: The Algorithm designed must be language-independent, i.e. it
must be just plain instructions that can be implemented in any language, and yet the output
1|Page
will be same, as expected.
2|Page
Example:
Write an algorithm to calculate the addition of two given numbers. Step 1:
Start
Step 2: Read two numbers A and B
Step 3: Add A and B and store result in C Step
4: Display C
Step 5: Stop
3|Page
Basic Symbols used in Flowchart Designs
1. Terminal: Terminal is the first and last symbols in the flowchart.
2. Input/Output: Program instructions that take input from input devices and display output
on output devices are indicated with parallelogram in a flowchart.
4. Decision Diamond symbol represents a decision point. Decision based operations such
as yes/no question or true/false are indicated by diamond in flowchart.
5. Connectors: Whenever flowchart becomes complex or it spreads over more than one page,
it is useful to use connectors to avoid any confusions. It is represented by a circle.
6. Flow lines: Flow lines indicate the exact sequence in which instructions are executed.
Arrows represent the direction of flow of control and relationship among different symbols
of flowchart.
4|Page
• Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
• Proper Debugging: The flowchart helps in debugging process.
• Efficient Program Maintenance: The maintenance of operating program becomes easy with
the help of flowchart. It helps the programmer to put efforts more efficiently on that part
Algorithm Flowchart
Step 1: Start
Step 2: Read two numbers A and B
Step 3: Add A and B and store result in C Step
4: Display C
Step 5: Stop
5|Page
Algorithm Flowchart
Step 1: Start
Step 2: Read three numbers A, B and C Step Start
3: C = A
Step 4: A = B
Step 5: B = C Read A, B and C
Step 6: Print A and B Step
7: Stop
C=
A
A=
B
B=
C
Print A and B
Stop
Write algorithm and flowchart to find sum and average of three numbers
Algorithm Flowchart
Step 1: Start
Step 2: Read three numbers A, B and C Step Start
3: sum = A + B + C
Step 4: avg = sum/3
Step 5: Print sum and avg Step Read A, B and C
6: Stop
sum = A + B + C
avg = sum/3
Stop
6|Page
Write an algorithm to determine whether a given number is divisible by 5 or not
Step 1- Start
Step 2- Read / input the number. Step
3- if n%5==0 then goto step 5.
Step 4- else number is not divisible by 5 goto step 6. Step
5- display the output number is divisible by 5. Step 6-
Stop
Write algorithm and draw flow-chart to print even numbers from 1 to 100.
Algorithm Flowchart
Algorithm
1. Start
2. Initialize the variable i to 1.
3. while i<=100
4. if i%2==0
5. print the number
6. increment value of i
7. stop
7|Page
Algorithm Flowchart
Algorithm
Step-1 Start
Step-2 Input two numbers say
NUM1,NUM2 Step-3 IF NUM1 >
NUM2 THEN print largest is
NUM1 ELSE print largest is NUM2
ENDIF
Step-4 Stop
Algorithm Flowchart
Step 1: Start
N is an Even Number.
Else
4: Exit
8|Page
Algorithm Flowchart
Step-1 Start
Step-2 Read three numbers say
num1,num2, num3
Step-3 if num1>num2 then go to
step-5
Step-4 IF num2>num3 THEN
print num2 is largest ELSE print
num3 is largest ENDIF GO TO
Step-6
Step-5 IF num1>num3 THEN
print num1 is largest ELSE print
num3 is largest ENDIF
Step-6 Stop
Algorithm Flowchart
step 1. Start
step 2. Read the number n step
3. [Initialize]
i=1, fact=1
step 4. Repeat step 4 through 6 until i=n
step 5. fact=fact*i
step 6. i=i+1 step
7. Print fact step
8. Stop
9|Page
Algorithm Flowchart
Step-1 Start
Step-2 Input NUM
Step-3
R=SQRT(NUM)
Step-4 I=2
Step-5 IF ( I > R) THEN
Write NUM is Prime Number Stop
ENDIF
Step 6 IF ( NUM % I ==0) THEN
Write NUM is Not Prime Stop
ENDIF
Step-7 I = I + 1
Step-8 Go to Step-5
What is Pseudocode
Definition: Pseudocode is an informal way of programming description that does not require
any strict programming language syntax or underlying technology considerations. It is used for
creating an outline or a rough draft of a program.
Example:
10 | P a g
e
c) Find the smallest (minimum) and largest (maximum) of the five entered numbers.
Read n1,n2,n3,n4,n5
avg
Set max to n2
Else
Set max to n1
Set max to n3
Set max to n4
Set max to n5
Write max
The formula used in this program are Surface_area = 4 * Pi * r2, Volume = 4/3 * Pi * r3 where r
is the radius of the sphere, Pi= 22/7
11 | P a g e
/*
* C Program to Find Volume and Surface Area of Sphere
*/
#include <stdio.h>
#include <math.h>
int main()
{
float radius;
float surface_area, volume;
#include <stdio.h>
int main()
{
int x, y, t;
printf("Enter two integers\n");
scanf("%d%d", &x, &y);
12 | P a g e
printf("Before Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y); t = x;
x = y;
y = t;
printf("After Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y); return
0;
}
The output of the program:
Enter two integers
23
45
Before Swapping
First integer = 23
Second integer = 45
After Swapping First
integer = 45 Second
integer = 23
If a five-digit number is input through the keyboard, write a program to calculate the sum of
its digits. (Hint: Use the modulus operator ‘%’)
#include <stdio.h>
#include < conio.h>
int main()
{
long int Num;
int Digit1, Digit2,Digit3, Digit4, Digit5 , Sum=0;
Clrscr();
Printf(“Enter 5 digit Number : ”);
Scanf(“%ld”,&Num);
Digit1 = Num % 10;
Num = Num / 10;
Digit2 = Num % 10;
13 | P a g e
Num = Num / 10;
Digit3 = Num % 10;
Num = Num / 10;
Digit4 = Num % 10;
Num = Num / 10;
Digit5 = Num % 10;
Num = Num / 10;
Sum = Digit1 + Digit2 + Digit3 + Digit4 + Digit5;
printf(“Sum of Digits = %d”, Sum);
getch();
Return 0;
}
Draw a flowchart for checking whether given number is prime or not.
14 | P a g e
History of C Language
Features of C Language
C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1|Page
Basic Structure of C Program
2|Page
First C Program
printf("Hello C Language");
return 0;
Header Files
Header files are helping file of your C program which holds the definitions of various functions and
their associated variables that needs to be imported into your C program with the help of pre-
processor #include statement.
All the header file have a '.h' an extension that contains C function declaration and macro definitions.
In other words, the header files can be requested using the preprocessor directive #include. The
default header file that comes with the C compiler is the stdio.h. (Standard input output)
3|Page
Give the significance of <math.h> and <stdio.h> header files.
enumerated Write syntax and use of pow ()function of <math.h> header file.
main() function in C
main() function is the entry point of any C program. It is the point at which execution of
program is started. When a C program is executed, the execution control goes directly to the
main() function. Every C program have a main() function.
void main()
{
.........
.........
}
In above syntax;
• void: is a keyword in C language, void means nothing, whenever we use void as a function
return type then that function nothing return. here main() function no return any value.
• In place of void we can also use int return type of main() function, at that time main() return
integer type value.
• main: is a name of function which is predefined function in C library.
Character set of C
C language also has a set of characters which include alphabets, digits, and special symbols. C language
supports a total of 256 characters.
Every C program contains statements. These statements are constructed using words and these
words are constructed using characters from C character set. C language character set contains the
following set of characters...
4|Page
1. Alphabets
2. Digits
3. Special Symbols
Alphabets
C language supports all the alphabets from the English language. Lower and upper case letters together
support 52 alphabets.
lower case letters - a to z
UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical values in C language. Digits
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL bell
backspace verticaltab etc.,
Every character in C language has its equivalent ASCII (American Standard Code for
Information Interchange) value.
C Tokens
Every C program is a collection of instructions and every instruction is a collection of some
individual units. Every smallest individual unit of a c program is called token. Every instruction in a
c program is a collection of tokens. Tokens are used to construct c programs and they are said to the
basic building blocks of a c program.
In a c program tokens may contain the following...
1. Keywords
2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
5|Page
7. Data values
C Keywords
Keywords are the reserved words with predefined meaning which already known to
the compiler
Whenever C compiler come across a keyword, automatically it understands its meaning.
Properties of Keywords
1. All the keywords in C programming language are defined as lowercase letters so they must
be used only in lowercase letters
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords can not be used as user-defined names like variable, functions, arrays,
pointers, etc...
4. Every keyword in C programming language represents something or specifies some kind
of action to be performed by the compiler.
5. C has 32 Keywords as follows:
Keywords
6|Page
do if static while
C Identifiers
Example
int marks;
char studentName[30];
C data types
The Data type is a set of value with predefined characteristics. data types are used to
declare variable, constants, arrays, pointers, and functions.
In the c programming language, data types are classified as follows...
7|Page
3. Double data type
4. Character data type
• float
• double
We use the keyword "float" to represent floating-point data type and "double" to represent double
data type in c. Both float and double are similar but they differ in the number of decimal places. The
float value contains 6 decimal places whereas double value contains 15 or 19 decimal places. The
following table provides complete details about floating-point data types.
8|Page
Character data type
The character data type is a set of characters enclosed in single quotations. The following table
provides complete details about the character data type.
The following table provides complete information about all the data types in c programming language...
9|Page
Here is the syntax of enum in C language,
#include<stdio.h>
int main() {
return 0;
Output
The value of enum week: 10 11 12 13 10 16 17
The default value of enum day: 0 1 2 3 18 11 12
• Arrays
• Structures
• Unions
• Enumeration
10 | P a g e
C Variables
Variable is a name given to a memory location where we can store different values of
the same datatype during the program execution.
Every variable in c programming language must be declared in the declaration section before it is
used. Every variable must have a datatype that determines the range and type of values be stored
and the size of the memory to be allocated.
A variable name may contain letters, digits and underscore symbol. The following are the rules to
specify a variable name...
Declaration of Variable
Declaration Syntax:
datatype variableName;
Example
int number;
C Constants
A constant is a named memory location which holds only one value throughout the
program execution.
In C programming language, a constant can be of any data type like integer, floating-point, character,
string and double, etc.,
11 | P a g e
Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a
maximum length of one character.
Example
'A'
'2'
'+'
String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences that
are enclosed in double quotations.
Creating constants in C
In a c programming language, constants can be created using two concepts...
int i = 9 ;
const int x = 10 ;
12 | P a g e
i = 15 ;
x = 100 ; // creates an error printf("i =
%d\nx = %d", i, x ) ;
#defien PI 3.14
void main(){
int r, area ;
printf("Please enter the radius of circle : ") ;
scanf("%d", &r) ;
area = PI * (r * r) ;
printf("Area of the circle = %d", area) ;
}
13 | P a g e
CHAPTER 2
C Operators
An operator is a symbol used to perform arithmetic and logical operations in a program. That means
an operator is a special symbol that tells the compiler to perform mathematical or logical operations.
C programming language supports a rich set of operators that are classified as follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
14 | P a g e
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
15 | P a g e
is FLASE and returns FALSE if it is TRUE 10) is TRUE
Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is
FALSE then complete condition becomes FALSE.
Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE
then complete condition becomes TRUE.
16 | P a g e
The symbol used is --.
Example:
int m=5;
int n = ++m;
printf(%d%d”,m,n);
When the increment operator is used prior to the variable name m, the value of the variable m is
incremented first and then assigned to the variable n. The values of both the variable m and n here
will be 6. But if the increment operator ++ is used after the variable name, then the value of the
variable m is assigned to the variable n and then the value of m is increased.
Therefore the values of m and n will be 6 and 5 respectively.
Programming Code 1:
#include <stdio.h>
int main()
{
int i=5;
printf(“%d\n”,++i);
return 0;
}
Output: 6
• variable++;
17 | P a g e
Example Post-increment unary operator:
++i;
Programming Code 1:
#include <stdio.h>
int main()
{
int i=5;
printf(“%d\n”,i++);
return 0;
}
Output: 5
Explanation: In the above example the value of ‘i’ is initialize by 5 after that applying the post
increment operation on variable ‘i’ then it updated 6 but the output is print before update i.e. 5.
1. Decrement operator is used to decrease the current value of variable by subtracting integer
1.
2. Like Increment operator, decrement operator can be applied to only variables.
3. Decrement operator is denoted by –.
When decrement operator used in C Programming then it can be used as pre-decrement or post-
decrement operator.
Pre-decrement operator is used to decrement the value of variable before using in the expression. In
the Pre-decrement value is first decremented and then used inside the expression.
b = --var;
18 | P a g e
Chapter 2 Basics of C Programming
Suppose the value of variable var is 10 then we can say that value of variable ‘var’ is firstly
decremented then updated value will be used in the expression.
Post-decrement operator is used to decrement the value of variable immediatly after executing
expression completely in which post decrement is used. In the Post-decrement old value is first used
in a expression and then old value will be decrement by 1.
b = var--;
Value of variable ‘var’ is 5. Same value will be used in expression and after execution of
expression new value will be 4.
CProgram
#include<stdio.h>
void main()
{
int a,b,x=10,y=10;
a = x--;
b = --y;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
Output :
Value of a : 10
Value of b : 9
19 | P a g e
Chapter 2 Basics of C Programming
Example
20 | P a g e
int i;
clrscr();
printf("Enter a number:");
scanf("%d",&i);
i%2==0?printf("%d is even",i):printf("%d is odd",i) ;
getch();
}
sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This operator is
used with the following syntax.
sizeof(variableName);
Example
Type Conversion
The type conversion is the process of converting a data value from one data type to another data type
automatically by the compiler. Sometimes type conversion is also called implicit type conversion.
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
21 | P a g e
i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i
i=x;
printf("i value is %d\n",i); x
=i;
printf("x value is %f\n",x); i
= ch ;
printf("i value is %d\n",i);
}
Output:
Typecasting
Typecasting is also called an explicit type conversion. Compiler converts data from one data type to
another data type implicitly. When compiler converts implicitly, there may be a data loss. In such a
case, we convert the data from one data type to another data type using explicit type conversion. To
perform this we use the unary cast operator. The general syntax of typecasting is as follows.
(TargetDatatype) DataValue
22 | P a g e
Example
int totalMarks = 450, maxMarks = 600 ; float
average ;
In the above example code, both totalMarks and maxMarks are integer data values. When we
perform totalMarks / maxMarks the result is a float value, but the destination (average) datatype is a
float. So we use type casting to convert totalMarks and maxMarks into float data type.
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c ;
float avg ;
printf("Enter any three integer values : ") ;
scanf("%d%d%d", &a, &b, &c) ;
avg = (a + b + c) / 3 ;
printf("avg before casting = %f\n",avg);
C Input Functions
C programming language provides built-in functions to perform input operations. The input
operations are used to read user values (input) from the keyboard. The c programming language
provides the following built-in input functions.
23 | P a g e
1. scanf()
2. getchar()
3. getch()
4. gets()
5. fscanf()
scanf() function
The scanf() function is used to read multiple data values of different data types from the keyboard.
The scanf() function is built-in function defined in a header file called "stdio.h". When we want to
use scanf() function in our program, we need to include the respective header file (stdio.h) using
#include statement. The scanf() function has the following syntax...
Syntax:
scanf("format strings",&variableNames);
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i;
printf("\nEnter any integer value: ");
scanf("%d",&i);
printf("\nYou have entered %d number",i);
Output:
24 | P a g e
In the above example program, we used the scanf() function to read an integer value from the keyboard
and store it into variable 'i'.
The scanf function also used to read multiple data values of different or the same data types. Consider the
following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i;
float x;
printf("\nEnter one integer followed by one float value : ");
scanf("%d%f",&i, &x);
printf("\ninteger = %d, float = %f",i, x);
Output:
In the above example program, we used the scanf() function to read one integer value and one float
value from the keyboard. Here 'i' is an integer variable so we have used format string
%d, and 'x' is a float variable so we have used format string %f.
The scanf() function returns an integer value equal to the total number of input values read using
scanf function.
Example Program
#include<stdio.h>
25 | P a g e
#include<conio.h>
void main(){
int i,a,b;
float x;
printf("\nEnter two integers and one float : "); i =
scanf("%d%d%f",&a, &b, &x); printf("\nTotal
inputs read : %d",i);
Output:
getchar() function
The getchar() function is used to read a character from the keyboard and return it to the program.
This function is used to read a single character. To read multiple characters we need to write multiple
times or use a looping statement. Consider the following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char ch;
printf("\nEnter any character : "); ch =
getchar();
printf("\nYou have entered : %c\n",ch);
Output:
26 | P a g e
getch() function
The getch() function is similar to getchar function. The getch() function is used to read a character
from the keyboard and return it to the program. This function is used to read a single character. To
read multiple characters we need to write multiple times or use a looping statement. Consider the
following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char ch;
printf("\nEnter any character : "); ch =
getch();
printf("\nYou have entered : %c",ch);
Output:
gets() function
The gets() function is used to read a line of string and stores it into a character array. The gets()
function reads a line of string or sequence of characters till a newline symbol enters. Consider the
following example program...
27 | P a g e
Example Program
#include<stdio.h>
#include<conio.h>
Output:
fscanf() function
The fscanf() function is used with the concept of files. The fscanf() function is used to read data
values from a file. When you want to use fscanf() function the file must be opened in reading
mode.
C Output Functions
C programming language provides built-in functions to perform output operation. The output
operations are used to display data on user screen (output screen) or printer or any file. The c
programming language provides the following built-in output functions...
1. printf()
2. putchar()
3. puts()
4. fprintf()
28 | P a g e
printf() function
The printf() function is used to print string or data values or a combination of string and data values
on the output screen (User screen). The printf() function is built-in function defined in a header file
called "stdio.h". When we want to use printf() function in our program we need to include the
respective header file (stdio.h) using the #include statement. The printf() function has the
following syntax...
Syntax:
printf("message to be display!!!");
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
printf("Hello! Welcome to btechsmartclass!!!");
}
Output:
In the above example program, we used the printf() function to print a string on to the output screen.
The printf() function is also used to display data values. When we want to display data values we use
format string of the data value to be displayed.
Syntax:
printf("format string",variableName);
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 10;
29 | P a g e
float x = 5.5;
printf("%d %f",i, x);
Output:
In the above example program, we used the printf() function to print data values of variables i and x
on to the output screen. Here i is a an integer variable so we have used format string %d and x is a
float variable so we have used format string %f.
The printf() function can also be used to display string along with data values.
Syntax:
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 10;
float x = 5.5;
printf("Integer value = %d, float value = %f",i, x);
Output:
In the above program, we are displaying string along with data values.
30 | P a g e
Every function in the C programming language must have a return value. The printf() function also
have an integer as a return value. The printf() function returns an integer value equivalent to the
total number of characters it has printed.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i;
i = printf("btechsmartclass");
printf(" is %d number of characters.",i);
Output:
In the above program, first printf() function printing "btechsmartclass" which is of 15 characters. So
it returns integer value 15 to the variable "i". The value of "i" is printed in the second printf()
function.
Generally, when we write multiple printf() statements the result is displayed in a single line because
the printf() function displays the output in a single line. Consider the following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
printf("Welcome to ");
31 | P a g e
printf("btechsmartclass ");
printf("the perfect website for learning");
}
Output:
In the above program, there are 3 printf() statements written in different lines but the output is
displayed in single line only.
To display the output in different lines or as we wish, we use some special characters
called escape sequences. Escape sequences are special characters with special functionality used in
printf() function to format the output according to the user requirement. In the C programming
language, we have the following escape sequences...
Escape Meaning
sequence
\n Moves the cursor to New Line
\t Inserts Horizontal Tab (5 characters space)
\v Inserts Vertical Tab (5 lines space)
\a Beep sound
\b Backspace (removes the previous character from its
current position)
\\ Inserts Backward slash symbol
\? Inserts Question mark symbol
\' Inserts Single quotation mark symbol
\" Inserts Double quotation mark symbol
32 | P a g e
Output:
putchar() function
The putchar() function is used to display a single character on the output screen. The putchar()
functions prints the character which is passed as a parameter to it and returns the same character as a
return value. This function is used to print only a single character. To print multiple characters we
need to write multiple times or use a looping statement.
Consider the following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
char ch = 'A';
putchar(ch);
}
Output:
puts() function
The puts() function is used to display a string on the output screen. The puts() functions prints
a string or sequence of characters till the newline. Consider the following example program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
33 | P a g e
char name[30];
printf("\nEnter your favourite website: "); gets(name);
puts(name);
}
Output:
fprintf() function
The fprintf() function is used with the concept of files. The fprintf() function is used to print a line
into the file. When you want to use fprintf() function the file must be opened in writting mode.
Comment
A comment starts with a slash asterisk /* and ends with a asterisk slash */ and can be anywhere in
your program. Comments can span several lines within your C program. Comments are typically
added directly above the related C source code.
34 | P a g e
Develop a simple ‘C’ program for addition and multiplication of two integer numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,add,mul;
clrscr();
printf("Enter value for a and b:");
scanf("%d%d",&a,&b);
add=a+b;
mul=a*b;
printf("\nAddition of a and b=%d\n",add);
printf("\Multiplication of a and b=%d",mul);
getch();
}
getchar( ) -
It is function from stdio.h header file. This function is used to input a single character.
The enter key is pressed which is followed by the character that is typed. The character that is entered is
echoed.
Syntax:
ch=getchar();
Example:
void main()
{
char ch;
ch = getchar();
printf("Input Char Is :%c",ch);
}
During the program execution, a single character gets or read through the getchar(). The given
value is displayed on the screen and the compiler waits for another character to be typed. If you
press the enter key/any other characters and then only the given character is printed through the
printf function.
putchar( ) -
It is used from standard input (stdio.h) header file. This function is the other side of getchar. A single
character is displayed on the screen.
Syntax:
putchar(ch);
void main()
{
char ch='a';
putchar(ch);
getch();
35 | P a g e
}
getch( ) -
It is used from the console (conio.h) header file. This function is used to input a single character.
The character is read instantly and it does not require an enter key to
be pressed. The character type is returned but it does not echo on the screen.
Syntax:
ch=getch();
Where, ch - assigned the character that is returned by getch(). void
main()
{
char ch;
ch = getch();
printf("Input Char Is :%c",ch);
}
During the program execution, a single character gets or read through the getch(). The given value is
not displayed on the screen and the compiler does not wait for another character to be typed. And
then, the given character is printed through the printf function.
putch( )-
It is used from console input output header file (conio.h) This function is a counterpart of getch().
Which means that it will display a single character on the screen.
The character that is displayed is returned.
Syntax:
putch(ch); Where, ch - the character that is to be printed. void
main()
{
char ch='a';
putch(ch)
}
State the use of printf( ) & scanf( ) with suitable example. printf( )
& scanf( ):
printf() and scanf() functions are library functions in C programming language defined in
“stdio.h”.
printf() function is used to print the character, string, float, integer, octal and hexadecimal values
onto the output screen.
scanf() function is used to read character, string, numeric data from keyboard. %d format
specifier is used in printf() and scanf() to specify the value of an integer variable.
%c is used to specify character, %f for float variable, %s for string variable, and %x for
hexadecimal variable.
Example:
#include<stdio.h>
#include<conio.h>
void main() {
int i;
clrscr();
printf("Enter a number");
scanf("%d",&i);
printf("Entered number is: %d",i);
36 | P a g e
getch();
}
Output
Enter days
265
Months = 8 Days = 25
Enter days
364
Months = 12 Days = 4
Enter days 45
Months = 1 Days = 15
#include<stdio.h>
int main() {
float radius, area;
return (0);
}
Output:
Enter the radius of Circle : 2.0
37 | P a g e
Area of Circle : 6.14
#include <stdio.h>
int main()
{
double n1, n2, n3;
printf("Enter three different numbers: "); scanf("%lf
%lf %lf", &n1, &n2, &n3);
if( n1>=n2 && n1>=n3 )
printf("%.2f is the largest number.", n1); if(
n2>=n1 && n2>=n3 )
printf("%.2f is the largest number.", n2); if(
n3>=n1 && n3>=n2 )
printf("%.2f is the largest number.", n3); return
0;
}
#include <stdio.h>
int main()
{
int num;
if(num > 0)
{
printf("Number is POSITIVE");
}
if(num < 0)
{
printf("Number is NEGATIVE");
}
if(num == 0)
{
printf("Number is ZERO");
}
return 0;
}
38 | P a g e
C program to convert temperature from degree fahrenheit to Celsius Temperature conversion
formula
/**
* C program to convert temperature from degree fahrenheit to celsius
*/
#include <stdio.h>
int main()
{
float celsius, fahrenheit;
return 0;
}
#include
#include
void main()
{
float km, m, miles;
clrscr();
printf("Enter the distance in kilometers : ");
scanf("%f",&km);
m = km * 1000;
printf("The equivalent distance in meters is : %f",m);
39 | P a g e
printf("%f Miles", miles);
}
getch();
}
#include<stdio.h>
int main()
{
float k, cel;
printf("Enter the temperature in celsius: "); scanf("%f",
&cel);
return 0;}
General syntax:
scanf(“control string”, arg1, arg2..);
Control string here refers to the format of the input data. It includes the conversion character
%, a data type character and an optional number that specifies the field width. It also may contain
new line character or tab. arg1, arg2 refers to the address of memory locations where the data should
be stored.
Example:
scanf(“%d”,&num1);
Eg: #include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("Enter a number");
scanf("%d",&i);
printf("Entered number is: %d",i);
getch();
}
40 | P a g e
Decision making in C
Decision making is about deciding the order of execution of statements based on certain
conditions or repeat a group of statements until certain specified conditions are met. C language
handles decision-making by supporting the following statements,
• if statement
• switch statement
• conditional operator statement (? : operator)
• goto statement
making statement:
1. if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-else statement
5. switch statement
6. conditional operator statement (? : operator)
1. Simple if statement
2. if .. else statement
3. Nested if ... else statement
4. Using else if statement
Simple if statement
The general form of a simple if statement is,
if(expression)
{
statement inside;
}
statement outside;
Example:
#include <stdio.h>
void main( )
1|Page
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
}
Output:
x is greater than y
if...else statement
The general form of a simple if...else statement is,
if(expression)
{
statement block1;
}
else
{
statement block2;
}
2|Page
If the expression is true, the statement-block1 is executed, else statement-block1 is skipped and
statement-block2 is executed.
Example:
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
Output:
y is greater than x
Example:
#include <stdio.h>
void main( )
{
int a, b, c;
3|Page
printf("Enter 3 numbers...");
scanf("%d%d%d",&a, &b, &c);
if(a > b)
{
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}
C Program Enter the Student Marks and Find the Percentage and Grade
#include<stdio.h>
void main()
{
int m1,m2,m3,total;
float per;
clrscr();
printf("Enter 3 Nos.");
scanf("%D%D%D",&m1,&m2,&m3);
total=m1+m2+m3; per=total*100/300;
if(per>=60&&per<=100)
printf("You are 1st :");
else if(per>=50&&per<=60)
printf("You are 2nd");
else if(per>=40&&per<=50)
printf("You are 3rd");
else
4|Page
printf("You are Fail");
getch();
}
Switch statement in C
The switch statement allows us to execute one code block among many alternatives.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
5|Page
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, / default:
printf("Error! operator is not correct");
}
return 0;
}
Output
6|Page
Example of switch statement
#include<stdio.h>
void main( )
{
int a, b, c, choice;
while(choice != 3)
{
/* Printing the available options */
printf("\n 1. Press 1 for addition");
7|Page
printf("\n 2. Press 2 for subtraction");
printf("\n Enter your choice");
/* Taking users input */
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}
if...else Ladder
The if...else statement executes two different codes depending upon whether the test expression is
true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder
allows you to check between multiple test expressions and execute different statements.
8|Page
}
#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
Output
Enter two integers: 12
23
Result: 12 < 23
#include <stdio.h>
int main()
{
int y;
if(y % 4 == 0)
{
//Nested if else
9|Page
if( y % 100 == 0)
{
if ( y % 400 == 0)
printf("%d is a Leap Year", y);
else
printf("%d is not a Leap Year", y);
}
else
printf("%d is a Leap Year", y );
}
else
printf("%d is not a Leap Year", y);
return 0;
}
Output:
Enter year: 1991
1991 is not a Leap Year
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
return 0;
}
C program for palindrome without using string functions
#include <stdio.h>
int main()
10 | P a g e
{
char text[100];
int begin, middle, end, length = 0;
gets(text);
end = length - 1;
middle = length/2;
return 0;
}
#include<stdio.h>
int main()
{
int x, y, z, large;
clrscr();
printf(" Enter any three integer numbers for x, y, z : ") ; scanf("%d
%d %d", &x, &y, &z) ;
large = x > y ? ( x > z ? x : z) : (y > z ? y : z) ;
printf("\n\n Largest or biggest or greatest or maximum among 3 numbers using Conditional
ternary Operator : %d", large) ;
getch();
return 0;
}
Sample Output:
11 | P a g e
Enter any three integer numbers for x, y, z : 536 234 782
Largest or biggest or greatest or maximum among 3 numbers using Conditional ternary Operator :
782
#include <stdio.h>
int main()
{
char ch;
printf("Enter a character\n");
scanf("%c", &ch);
return 0;
}
#include <stdio.h>
int main()
{
int week;
switch(week)
12 | P a g e
{
case 1:
printf("Monday"); break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday"); break;
default:
printf("Invalid input! Please enter week number between 1-7.");
}
return 0;
}
Output
Enter week number(1-7): 1
Monday
#include<stdio.h>
#include<conio.h>
int main()
{
int marks;
clrscr();
printf("Enter the marks of the students");
scanf("%d",&marks);
marks=marks/10;
switch(marks)
13 | P a g e
{
case 10:
case 9:
case 8:
printf("The grade is Honors");
break;
case 7:
case 6:
printf("The grade is 1st Division"); break;
case 5:
printf("The grade is 2nd Division"); break;
case 4:
printf("The grade is 3rd Division"); break;
default:
printf("Student is failed");
}
getch();
return(0);
}
OUTPUT:
Enter the marks of the student 72
The grade is 1st Division
int type;
int isRightAngled;
clrscr();
0; i < 3; i++)
{
14 | P a g e
scanf(“%d”, &sides[i]);
}
temp = sides[i];
sides[i] = sides[j];
sides[j] = temp;
}
}
}
type = 3;
isRightAngled = 0;
switch(type)
{
case 0:
printf(“The triangle is Invalid\n”);
break;
case 1:
printf(“The triangle is Equilateral Triangle\n”);
break;
case 2:
if(isRightAngled == 1)
printf(“The triangle is Isosceles and Right Angled Triangle\n”); else
15 | P a g e
printf(“The triangle is Isosceles Triangle\n”);
break;
case 3:
if(isRightAngled == 1)
printf(“The triangle is Scalene and Right Angled Triangle\n”); else
printf(“The triangle is Scalene Triangle\n”); break;
}
getch();
}
Print the season name of the year based on the month number
#include <stdio.h>
int main()
{
int month;
switch(month)
{
case 12:
case 1:
case 2:
printf(“\n Winter”);
break;
case 3:
case 4:
case 5:
printf(“\n Spring”);
break;
case 6:
case 7:
case 8:
printf(“\n Summer”);
break;
case 9:
case 10:
case 11:
16 | P a g e
printf(“\n Autumn”);
break;
default:
printf(“\n Invalid Month number”);
break;
}
return 0;
C For loop
Step 1: First initialization happens and the counter variable gets initialized.
Step 2: In the second step the condition is checked, where the counter variable is tested for the given
condition, if the condition returns true then the C statements inside the body of for loop gets
executed, if the condition returns false then the for loop gets terminated and the control comes out of
the loop.
17 | P a g e
Step 3: After successful execution of statements inside the body of loop, the counter variable is
incremented or decremented, depending on the operation (++ or –).
Example of For loop
#include <stdio.h> int
main()
{
int i;
for (i=1; i<=3; i++)
{
printf("%d\n", i);
}
return 0;
}
Output:
1
2
3
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=0;i<10;i++)
{
printf("Welcome to C programming\n");
}
getch();
}
C – while loop
18 | P a g e
Example of while loop
#include <stdio.h>
int main()
{
int i = 1;
while (i <= 5)
{
printf("%d\n", i);
++i;
}
return 0;
}
Output
1
2
3
4
5
19 | P a g e
do...while loop
The do..while loop is similar to the while loop with one important difference. The body of
do...while loop is executed at least once. Only then, the test expression is evaluated. The
syntax of the do...while loop is:
do
{
// statements inside the body of the loop
}
while (testExpression);
do..while loop
//Statements
}while(condition test);
20 | P a g e
Example of do while loop
#include <stdio.h>
int main()
{
int j=0;
do
{
printf("Value of variable j is: %d\n", j);
j++;
}while (j<=3);
return 0;
}
Output:
Value of variable j is: 0
Value of variable j is: 1
Value of variable j is: 2
Value of variable j is: 3
#include<stdio.h>
#include<conio.h>
void main()
21 | P a g e
{
int no,sum=0;
clrscr();
do
scanf("%d",&no);
sum=sum+no;
}while(no!=0);
C – goto statement
When a goto statement is encountered in a C program, the control jumps directly to the label mentioned in
the goto stateemnt
Syntax of goto statement in C
goto label_name;
..
..
label_name: C-statements
Flow Diagram of goto
22 | P a g e
Example of goto statement
#include <stdio.h>
int main()
{
int sum=0;
for(int i = 0; i<=10; i++){
sum = sum+i;
if(i==5){
goto addition;
}
}
addition:
printf("%d", sum);
return 0;
}
Output:
15
C – Continue statement
Syntax:
23 | P a g e
continue;
24 | P a g e
}
Output:
01235678
C – break statement
1. It is used to come out of the loop instantly. When a break statement is encountered inside a loop,
the control directly comes out of loop and the loop gets terminated. It is used with if statement,
whenever used inside loop.
2. This can also be used in switch case control structure. Whenever it is encountered in
switch-case block, the control comes out of the switch-case(see the example below).
Syntax:
break;
Example – Use of break in a while loop
#include <stdio.h>
int main()
{
int num =0;
while(num<=100)
{
printf("value of variable num is: %d\n", num); if
(num==2)
{
break;
}
num++;
}
printf("Out of while-loop");
return 0;
}
Output:
value of variable num is: 0
value of variable num is: 1
value of variable num is: 2
25 | P a g e
Out of while-loop
#include <stdio.h>
int main()
{
int n, t, sum = 0, remainder;
printf("Enter an integer\n");
scanf("%d", &n);
t = n;
while (t != 0)
{
remainder = t % 10;
sum = sum + remainder; t
= t / 10;
}
return 0;
}
#include <stdio.h>
void main()
{
int j,i,n=5;
printf("Input upto the table number starting from 1 : "); scanf("%d",&n);
printf("Multiplication table from 1 to %d \n",n);
for(i=1;i<=10;i++)
{
for(j=1;j<=n;j++)
{
if (j<=n-1)
printf("%dx%d = %d, ",j,i,i*j);
else
printf("%dx%d = %d",j,i,i*j);
26 | P a g e
}
printf("\n");
}
}
#include<stdio.h>
int main()
{
int n1=0,n2=1,n3,i,number; printf("Enter
the number of elements:");
scanf("%d",&number);
printf("\n%d %d",n1,n2);//printing 0 and 1
for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2; printf("
%d",n3); n1=n2;
n2=n3;
}
return 0;
}
Output:
23
456
7 8 9 10
11 12 13 14 15
#include<stdio.h>
int main()
int i,j,k;
k=1;
27 | P a g e
for(i=1;i<=5;i++)
for(j=5;j>=1;j--)
if(j > i)
printf(" ");
else
printf("%d",k++);
printf("\n");
return 0; }
28 | P a g e
CHAPTER 3
Define Array
Array is a collection of same data types. They
are declared by the given syntax:
Datatype array_name [dimensions] = {element1,element2,….,element}
The declaration form of one-dimensional array is
Data_type array_name [size];
e.g
int array[3] = {1,2,3);
Characteristics of Arrays in C
1) An array holds elements that have the same data type.
2) Array elements are stored in subsequent memory locations.
3) Two-dimensional array elements are stored row by row in subsequent memory locations.
4) Array name represents the address of the starting element.
5) Array size should be mentioned in the declaration. Array size must be a constant
expression and not a variable.
Declaration of C Array
array_name[array_size];
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.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
1|Page
Array example
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
Output
80
60
70
85
75
2|Page
Array: Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.
int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the
following code.
int marks[]={20,30,40,50,60};
Let's see the C program to declare and initialize the array in C.
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Output
20
30
40
50
60
Array Example: Sorting an array
In the following program, we are using bubble sort method to sort the array in ascending order.
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
3|Page
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...\n");
for(i = 0; i<10; i++)
{
printf("%d\n",a[i]);
}
}
4|Page
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are
being done simultaneously. However, this will not work with 2D arrays. We will have to define at
least the second dimension of the array. The two-dimensional array can be declared and defined in
the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two-dimensional array example in C
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
5|Page
2D array example: Storing elements in a matrix and printing it.
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ......... \n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
Output
Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
6|Page
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
56 10 30
34 21 34
45 56 78
7|Page
printf("Sum of entered matrices:-\n");
8|Page
9|Page
Following operations can be performed on arrays:
1. Traversing
2. Searching
3. Insertion
4. Deletion
5. Sorting
6. Merging
1. Traversing: It is used to access each data item exactly once so that it can be processed. E.g.
We have linear array A as below:
1 2 3 4 5
10 20 30 40 50
Here we will start from beginning and will go till last element and during this process we will access
value of each element exactly once as below:
A [1] = 10
A [2] = 20
A [3] = 30
A [4] = 40
A [5] = 50
2. Searching: It is used to find out the location of the data item if it exists in the given collection of data
items.
E.g.
We have linear array A as below:
1 2 3 4 5
15 50 35 20 25
Suppose item to be searched is 20. We will start from beginning and will compare 20 with each element.
This process will continue until element is found or array is finished. Here:
1) Compare 20 with 15
20 # 15, go to next element.
2) Compare 20 with 50
10 | P a g e
20 # 50, go to next element.
3) Compare 20 with 35
20 #35, go to next element.
4) Compare 20 with 20
20 = 20, so 20 is found and its location is 4.
3. Insertion: It is used to add a new data item in the given collection of data items. E.g.
We have linear array A as below:
1 2 3 4 5
10 20 50 30 15
New element to be inserted is 100 and location for insertion is 3. So shift the elements from 5th location
to 3rd location downwards by 1 place. And then insert 100 at 3rd location. It is shown below:
4. Deletion: It is used to delete an existing data item from the given collection of data items. E.g.
We have linear array A as below:
1 2 3 4 5
10 20 50 40 25 60
11 | P a g e
The element to be deleted is 50 which is at 3rd location. So shift the elements from 4th to 6th
location upwards by 1 place. It is shown below:
1 2 3 4 5 6
10 20 40 25 60
5. Sorting: It is used to arrange the data items in some order i.e. in ascending or descending order in case
of numerical data and in dictionary order in case of alphanumeric data.
E.g.
We have linear array A as below:
1 2 3 4 5
10 50 40 20 30
After arranging the elements in increasing order by using a sorting technique, the array will be:
1 2 3 4 5
10 20 30 40 50
6. Merging: It is used to combine the data items of two sorted files into single file in the sorted form We
have sorted linear array A as below:
1 2 3 4 5 6
12 | P a g e
10 40 50 80 95 100
1 2 3 4
20 35 45 90
1 2 3 4 5 6 7 8 9 10
10 20 35 40 45 50 80 90 95 100
Address of first element is random, address of next element depend upon the type of array. Here, the
type is character and character takes one byte in memory, therefore every next address will increment by
one.
Index of array will always starts with zero.
Declaration of String or Character array
Declaration of array means creating sequential bolcks of memory to hold fixed number of values.
13 | P a g e
char String-name[size of String ];
In the above example we have declared a character array which can hold twenty-five characters at a time.
Initialization of String
Initialization of string means assigning value to declared character array or string.
Examples 1 :Using sequence of characters.
In the above example, we are declaring and initializing a string at same time. When we declare and
initialize a string at same time, giving the size of array is optional and it is programmer's job to specify
the null character at the end to terminate the string.
Example 2 : Using assignment operator
In this approch, programmer doesn't need to provide null character, compiler will automatically add null
character at the end of string.
Input string using getche() function
The getche() read characters from console (output window) one by one and put these characters into string
using loop.
Examples for input string with getche() function
#include<stdio.h>
void main()
{
char String [50];
char ch;
int i;
if(ch==13) //Statement 2
break;
14 | P a g e
String [i] = '\0'; //Statement 3
printf("\n\n\tHello, ");
for(i=0; String [i]!='\0';i++)
printf("%c", String [i]);
Output :
In the above example, A for loop will execute upto 50 time and getche() which inside for loop will read
single character from console and put the character into ch. If user press the enter key, condition given in
statement 2 will satisfy and terminate the loop otherwise every character will assign to String. Statement
4 is assigning null character to String.
The scanf() can read the entire word at a time. The format specifier for a string is "%s". The scanf()
ignores the any occurrence of leading whitespace characters and terminate the string at the first
occurrence of whitespace after any input.
Examples for input string with scanf() function
#include<stdio.h>
void main()
{
char String [50];
}
Output :
Enter your name : Kumar Wadhwa
Hello Kumar
In the output of above example there is five leading whitespaces in the input which is ignored by the
compiler.
15 | P a g e
Input string using gets() function
The gets() can read the entire line at a time and the string will not terminate until user press the enter key.
The gets() will put all the leading and trailing whitespaces into str.
Examples for input string with gets() function
#include<stdio.h>
void main()
{
char String [50];
}
Output :
Enter your name : Kumar Wadhwa
Hello Kumar Wadhwa
Built in functions like substring(), charAt() etc No built in functions are provided in Java
‘+’ can be used to appended strings together to ‘+’ cannot be used to append two
The charAt() method can be used to access The characters in a Character Array can
16 | P a g e
characters at a particular index in a String. be accessed normally like in any other
Strings can be stored in any any manner in the Elements in Character Array are stored
locations.
All Strings are stored in the String Constant All Character Arrays are stored in
Not preferred for storing passwords in Java. Preferred for storing passwords in Java.
A String can be converted into Character Array by A Character Array can be converted into
using the toCharArray() method of String class. String by passing it into a String
C String Functions
strcat(first_string, concats or joins first string with second string. The result
3)
second_string) of the string is stored in first string.
strcmp(first_string, compares the first string with second string. If both strings
4)
second_string) are same, it returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in lowercase.
7) strupr(string) returns string characters in uppercase.
17 | P a g e
Function C String Length: strlen() function
Description The strlen() function returns the length of the given string. It doesn't count
null character '\0'.
Input #include<stdio.h>
#include <string.h> int
main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Output Length of string is: 10
18 | P a g e
Function C Compare String: strcmp()
Description The strcmp(first_string, second_string) function compares two string and returns 0
if both strings are equal.
Here, we are using gets() function which reads string from the console.
Input #include<stdio.h>
#include <string.h> int
main(){
char str1[20],str2[20]; printf("Enter
1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: "); gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
19 | P a g e
Function C String Lowercase: strlwr()
Description The strlwr(string) function returns string characters in lowercase. Let's see
a simple example of strlwr() function.
Input #include<stdio.h>
#include <string.h>
int main(){
char str[20]; printf("Enter
string: ");
gets(str);//reads string from console printf("String is:
%s",str);
printf("\nLower String is: %s",strlwr(str));
return 0;
}
Output Enter string: JAVATpoint
String is: JAVATpoint
Lower String is: javatpoint
C Program to Find the Length of a String without using the Built-in Function
#include<stdio.h>
#include<conio.h>
void main(){
char str[50];
int i, len=0;
clrscr();
20 | P a g e
printf("Enter a string");
scanf("%s",&str); for(i=0;
str[i]!='\0'; i++){ len++;
}
printf("The length of string is %d",len);
getch();
}
i = 0;
while (str1[i] == str2[i] && str1[i] != '\0')
i++;
if (str1[i] > str2[i])
printf("str1 > str2");
else if (str1[i] < str2[i])
printf("str1 < str2");
else
printf("str1 = str2");
return (0);
}
21 | P a g e
C Program to Copy One String into Other Without Using Library Function.
#include<stdio.h>
int main() {
char s1[100], s2[100];
int i;
i = 0;
while (s1[i] != '\0') {
s2[i] = s1[i];
i++;
}
s2[i] = '\0';
printf("\nCopied String is %s ", s2);
return (0);
}
Output:
Enter the string : c4learn.com Copied
String is c4learn.com
22 | P a g e
C Program to Concat Two Strings without Using Library Function
#include<stdio.h>
#include<string.h>
int main() {
char s1[50], s2[30];
concat(s1, s2);
printf("nConcated string is :%s", s1);
return (0);
}
void concat(char s1[], char s2[]) { int
i, j;
i = strlen(s1);
for (j = 0; s2[j] != '\0'; i++, j++) {
s1[i] = s2[j];
}
s1[i] = '\0';
}
Enter String 1 : Pritesh
Enter String 2 : Taral
Concated string is : PriteshTaral
23 | P a g e
Reverse String Without Using Library Function [ Strrev ]
#include<stdio.h>
#include<string.h>
int main() {
char str[100], temp;
int i, j = 0;
i = 0;
j = strlen(str) - 1;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
Output :
24 | P a g e
What is Structure
Structure in c is a user-defined data type that enables us to store the collection of different data
types. Each element of a structure is called a member. Structures ca; simulate the use of classes and
templates as it can store various information
The ,struct keyword is used to define the structure. Let's see the syntax to define the structure in
c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Let's see the example to define a structure for an entity employee in c.
struct employee
{ int id;
char name[20];
float salary;
};
25 | P a g e
};
Now write given code inside the main() function.
struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the structure. Here, e1 and e2 can
be treated in the same way as the objects in C++ and Java.
2nd way:
Let's see another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
Accessing members of the structure
There are two ways to access structure members:
1. By . (member or dot operator)
2. By -> (structure pointer operator)
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. #include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
26 | P a g e
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
//printing first employee information printf(
"employee 1 id : %d\n", e1.id); printf(
"employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
Let's see another example of the structure in C language to store many employees information.
#include<stdio.h>
#include <string.h> struct
employee
{ int id;
char name[50];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array e1.salary=56000;
27 | P a g e
printf( "employee 1 id : %d\n", e1.id); printf(
"employee 1 name : %s\n", e1.name);
printf( "employee 1 salary : %f\n", e1.salary);
Give a method to create, declare and initialize structure also develop a program to demonstrate
nested structure.
Declaration of structure:-
struct structure_name
{
data_type member 1;
data_type member 2;
.
.
.
data_type member n;
} structure variable 1, structure variable 2,..., structure variable n;
Example:-
struct student
{
28 | P a g e
int rollno;
char name[10];
}s1;
Initialization:-
struct student s={1,"abc"};
structure variable contains two members as rollno and name. the above example initializes rollno to 1
and name to "abc".
Program:-
#include<stdio.h>
#include<conio.h>
struct college
{
int collegeid;
char collegename[20];
};
struct student
{
int rollno;
char studentname[10];
struct college c;
};
void main()
{
struct student s={1,"ABC",123,"Polytechnic"};
clrscr();
printf("\n Roll number=%d",s.rollno); printf("\n
Student Name=%s",s.studentname); printf("\n
College id=%d",s.c.collegeid); printf("\n College
name=%s",s.c.collegename); getch();
}
Develop a program using structure to print data of three students having data members
name, class, percentage.
#include<stdio.h>
#include<conio.h>
void main() { struct
student
{
char name[20];
char c[20];
int per;
29 | P a g e
} s[3];
int i;
clrscr();
for(i=0;i<3;i++)
{
printf("Enter name, class, percentage");
scanf("%s%s%d",&s[i].name,&s[i].c,&s[i].per);
}
for(i=0;i<3;i++)
{
printf("%s %s %d\n",s[i].name,s[i].c,s[i].per);
}
getch();
}
Write a program to declare structure employee having data member name, age, street and city.
Accept data for two employees and display it.
#include<stdio.h>
#include<conio.h>
struct employee
{
char name[10],street[10],city[10];
int age;
};
void main()
{
int i;
struct employee e[2];
clrscr();
for(i=0;i<2;i++)
{
printf("\n Enter name:");
scanf("%s",&e[i].name);
printf("\n Enter age:");
scanf("%d",&e[i].age);
printf("\n Enter street:");
scanf("%s",&e[i].street);
printf("\n Enter city:");
scanf("%s",&e[i].city);
}
for(i=0;i<2;i++)
{
printf("\n Name=%s",e[i].name);
printf("\n Age=%d",e[i].age); printf("\n
Street=%s",e[i].street); printf("\n
City=%s",e[i].city);
30 | P a g e
}
getch();
}
C – Typedef
• Typedef is a keyword that is used to give a new symbolic name for the existing name in a C
program. This is same like defining alias for the commands.
• Consider the below structure.
struct student
{
int mark [2];
char name [10];
float average;
}
• Variable for the above structure can be declared in two ways.
1st way :
struct student record; /* for normal variable */
struct student *record; /* for pointer variable */
2nd way :
typedef struct student status;
• When we use “typedef” keyword before struct <tag_name> like above, after that we can
simply use type definition “status” in the C program to declare structure variable.
• Now, structure variable declaration will be, “status record”.
• This is equal to “struct student record”. Type definition for “struct student” is
status. i.e. status = “struct student”
AN ALTERNATIVE WAY FOR STRUCTURE DECLARATION USING TYPEDEF IN C:
typedef struct student
{
int mark [2];
char name [10];
float average;
} status;
// Structure using typedef:
31 | P a g e
#include <stdio.h>
#include <string.h>
int main()
{
status record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5; printf("
Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage); return
0;
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
#include <stdio.h>
#include <limits.h>
32 | P a g e
int main()
{
typedef long long int LLI;
return 0;
}
OUTPUT:
C enums
Enumerated Type Declaration
When you define an enum type, the blueprint for the variable is created. Here's how you can create
variables of enum types.
33 | P a g e
#include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; int
main()
{
// creating today variable of enum week type enum
week today;
today = Wednesday; printf("Day
%d",today+1); return 0;
}
Output
Day 4
#include <conio.h>
int main()
{
int a[10000],i,n,key;
34 | P a g e
Enter size of the array: 5
Enter elements in array: 4 6
2
1
3
Enter the key: 2
element found
Write a program to declare the structure student, having data members as rollno, name and
percentage. Accept data for five students and display the same.
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s[10];
int main()
{
int i;
// storing information
for(i=0; i<10; ++i)
{
s[i].roll = i+1;
printf("\n");
}
printf("Displaying Information:\n\n");
// displaying information for(i=0;
i<10; ++i)
35 | P a g e
{
printf("\nRoll number: %d\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
printf("\n");
}
return 0;
}
Output
Enter information of students:
Roll number: 1
Name: Tom
Marks: 98
.
36 | P a g e
CHAPTER 4
Need 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.
1|Page
Library Functions: Math functions
C – Library functions
• Library functions in C language are inbuilt functions which are grouped together and
placed in a common place called library.
• Each library function in C performs specific operation.
• We can make use of these library functions to get the pre-defined output instead of
writing our own code to get those outputs.
• These library functions are created by the persons who designed and created C
compilers.
• All C standard library functions are declared in many header files which are saved as
file_name.h.
• Actually, function declaration, definition for macros are given in all header files.
• We are including these header files in our C program using “#include<file_name.h>”
command to make use of the functions those are declared in the header files.
• When we include header files in our C program using “#include<filename.h>”
command, all C code of the header files are included in C program. Then, this C
program is compiled by compiler and executed.
C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h header
file are given below.
1) ceil(number) rounds up the given number. It returns the integer value which
is greater than or equal to given number.
2) floor(number) rounds down the given number. It returns the integer value
which is less than or equal to given number.
2|Page
C Math Example
Let's see a simple example of math functions found in math.h header file
#include<stdio.h>
#include <math.h>
int main(){ printf("\n%f",ceil(3.6));
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
printf("\n%f",pow(2,4));
printf("\n%f",pow(3,3));
printf("\n%d",abs(-12));
return 0;
}
Output:
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
3|Page
Explain any four library functions under conio.h header file.
clrscr() -This function is used to clear the output screen.
getch() -It reads character from keyboard
getche()-It reads character from keyboard and echoes to o/p screen putch -
Writes a character directly to the console.
textcolor()-This function is used to change the text color
textbackground()-This function is used to change text background
C User-defined functions
C allows you to define functions according to your need. These functions are known as user- defined
functions. For example:
Example: User-defined function
Here is an example to add two integers. To perform this task, we have created an user-defined
addNumbers().
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a, int b) // function definition
{
int result;
result = a+b;
return result; // return statement
4|Page
}
C FUNCTION DECLARATION, FUNCTION CALL AND FUNCTION DEFINITION:
There are 3 aspects in each C function. They are,
Function declaration or prototype – This informs compiler about the function name, function parameters
and return value’s data type.
Function call – This calls the actual function
Function definition – This contains all the statements to be executed.
• As you know, functions should be declared and defined before calling in a C program.
• In the below program, function “square” is called from main function.
• The value of “m” is passed as argument to the function “square”. This value is
multiplied by itself in this function and multiplied value “p” is returned to main
function from function “square”.
#include<stdio.h>
// function prototype, also called function declaration float
square ( float x );
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n"); scanf (
"%f", &m ) ;
// function call n
= square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}
5|Page
float square ( float x ) // function definition
{
float p ; p
=x*x;
return ( p ) ;
}
Scope of Variable in C
The scope of a variable decides the portion of a program in which the variable can be accessed.
The scope of the variable is defined as follows...
Scope of a variable is the portion of the program where a defined variable can be
accessed.
The variable scope defines the visibility of variable in the program. Scope of a variable depends on
the position of variable declaration.
In C programming language, a variable can be declared in three different positions and they are as
follows...
6|Page
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
subtraction() ;
multiplication() ;
getch() ;
}
void addition()
{
int result ;
result = num1 + num2 ;
printf("\naddition = %d", result) ;
}
void subtraction()
{
int result ;
result = num1 - num2 ; printf("\nsubtraction
= %d", result) ;
}
void multiplication()
{
int result ;
result = num1 * num2 ;
printf("\nmultiplication = %d", result) ;
}
Output:
7|Page
In the above example program, the variables num1 and num2 are declared as global variables.
They are declared before the main() function. So, they can be accessed by function main() and other
functions that are defined after main(). In the above example, the functions main(), addition(),
subtraction() and multiplication() can access the variables num1 and num2.
void main(){
void addition() ;
int num1, num2 ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
getch() ;
}
void addition()
{
int sumResult ;
sumResult = num1 + num2 ;
printf("\naddition = %d", sumResult) ;
}
Output:
8|Page
The above example program shows an error because, the variables num1 and num2 are declared
inside the function main(). So, they can be used only inside main() function and not in addition()
function.
void main(){
void addition(int, int) ;
int num1, num2 ; clrscr()
;
num1 = 10 ;
num2 = 20 ;
addition(num1, num2) ;
getch() ;
}
void addition(int a, int b)
{
int sumResult ;
sumResult = a + b ;
printf("\naddition = %d", sumResult) ;
}
Output:
In the above example program, the variables a and b are declared in function definition as parameters.
So, they can be used only inside the addition() function.
9|Page
Parameter Passing in C
When a function gets executed in the program, the execution control is transferred from calling-
function to called function and executes function definition, and finally comes back to the calling
function. When the execution control is transferred from calling-function to called- function it may
carry one or number of data values. These data values are called as parameters.
Parameters are the data values that are passed from calling function to called function.
In C, there are two types of parameters and they are as follows...
• Actual Parameters
• Formal Parameters
In C Programming Language, there are two methods to pass parameters from calling function to
called function and they are as follows...
Call by Value
Call by Reference
Call by Value
In call by value parameter passing method, the copy of actual parameter values are copied to formal
parameters and these formal parameters are used in called function. The changes made on the formal
parameters does not effect the values of actual parameters. That means, after the execution control
comes back to the calling function, the actual parameter values remains same. For example consider
the following program...
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration clrscr()
;
num1 = 10 ;
num2 = 20 ;
10 | P a g e
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2); getch()
;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a=b;
b = temp ;
}
Output:
Call by Reference
In Call by Reference parameter passing method, the memory location address of the actual
parameters is copied to formal parameters. This address is used to access the memory locations of
the actual parameters in called function. In this method of parameter passing, the formal parameters
must be pointer variables.
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
11 | P a g e
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2); getch()
;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Output:
1 A copy of the value is passed into the An address of value is passed into the
function function
2 Changes made inside the function is Changes made inside the function validate
limited to the function only. The values outside of the function also. The values of
of the actual parameters do not change by the actual parameters do change by
changing the formal changing the formal
parameters. parameters.
3 Actual and formal arguments are Actual and formal arguments are created
created at the different memory at the same memory location
location
12 | P a g e
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.
Let's see an example to find the nth term of the Fibonacci series.
#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
printf("Enter the value of n?");
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
13 | P a g e
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}
Output
Enter the value of n?12
144
Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value
of a variable. There are four types of storage classes in C
o Automatic
o External
o Static
o Register
14 | P a g e
CHAPTER 5
C Pointers
The pointer in C language is a variable which stores the address of another variable. This variable
can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the
architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type intege r.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
Pointer Example
An example of using pointers to print the address and value is given below.
As you can see in the above figure, pointer variable stores the address of number variable, i.e., fff4.
The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p. Let's
1|Page
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore prin ting p
gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer th erefore if we
print *p, we will get the value stored at the address contained by p.
return 0;
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Advantage of pointer
1. Pointers reduce the length and complexity of a program.
2. They increase execution speed.
3. A pointer enables us to access a variable that is defined outside the function.
4. Pointers are more efficient in handling the data tables.
5. The use of a pointer array of character strings results in saving of data storage space in
memory.
6. It supports dynamic memory management.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
the pointer is used.
Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and
improves the performance.
2|Page
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;
datatype *pointer_name;
Data type of a pointer must be same as the data type of the variable to which the pointer variable
is pointing. void type pointer works with all data types, but is not often used.
#include<stdio.h>
void main()
{
int a = 10;
int *ptr; //pointer declaration
3|Page
ptr = &a; //pointer initialization
}
Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition, subtraction, etc. Increment
Decrement
Addition
Subtraction
Comparison
Incrementing Pointer in C
If we increment a pointer by 1, the pointer will start pointing to the immediate next location. This is
somewhat different from the general arithmetic since the value of the pointer will get increased by
the size of the data type to which the pointer is pointing.
Let's see the example of incrementing pointer variable on 64-bit architecture.
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incremented
by 4 bytes.
return 0;
}
Output
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304
4|Page
Traversing an array by using pointer
#include<stdio.h>
void main ()
{
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
int i;
printf("printing array elements...\n");
for(i = 0; i< 5; i++)
{
printf("%d ",*(p+i));
}
}
Output
printing array elements... 1
2 3 4 5
Decrementing Pointer in C
Like increment, we can decrement a pointer variable. If we decrement a pointer, it will start pointing to
the previous location. The formula of decrementing the pointer is given below:
new_address= current_address - i * size_of(data type)
Example
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-1;
printf("After decrement: Address of p variable is %u \n",p); // P will now point to the immidiate
previous location.
5|Page
}
Output
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is given below:
new_address= current_address + (number * size_of(data type))
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p); return 0;
}
Output
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. Subtracting any number
from a pointer will give an address. The formula of subtracting value from the pointer variable is
given below:
new_address= current_address - (number * size_of(data type))
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
6|Page
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p); return
0;
}
Output
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
7|Page
9 at 2686724
Pointers as Function Argument in C
Pointer as a function parameter is used to hold addresses of arguments passed during function
call. This is also known as call by reference. When a function is called by reference any change
made to the reference variable will effect the original variable.
#include <stdio.h>
int main()
{
int m = 10, n = 20; printf("m
= %d\n", m); printf("n =
%d\n\n", n);
/*
pointer 'a' and 'b' holds and points to
the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
m = 10
n = 20
After Swapping:
m = 20
n = 10
8|Page
Functions returning Pointer variables
A function can also return a pointer to the calling function. In this case you must be careful,
because local variables of function doesn't live outside the function. They have scope only inside
the function. Hence if you return a pointer connected to a local variable, that pointer will be
pointing to nothing when the function ends.
#include <stdio.h>
void main()
{
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
92 is larger
Pointer to functions
It is possible to declare a pointer pointing to a function which can then be used as an argument in
another function. A pointer to a function is declared as follows,
type (*pointer-name)(parameter);
Example:
#include <stdio.h>
int main( )
{
9|Page
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d", s);
return 0;
}
25
Dot(.) operator is used to access the data using normal structure variable and arrow (->) is used to
access the data using pointer variable. You have learnt how to access structure data using normal
variable in C – Structure topic. So, we are showing here how to access structure data using pointer
variable in below C program.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5}; struct
student *ptr;
ptr = &record1;
10 | P a g e
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
return 0;
}
OUTPUT:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
function:
include<stdio.h> int
sum(int x, int y)
{
return x+y;
}
int main()
{
int s; int(*fp)(int,
int); fp = sum;
s = fp(10,12);
printf(“Sum = %d”,s);
return 0;
}
11 | P a g e
Join Telegram Group click here
Happy Learning!