You are on page 1of 62

C Programming

Developed by Dennis M. Ritchie

• At bell labs.
Page | 1
• To develop UNIX operating system.

Q) What is a C language?

A) C is a Structured programming Language which is also called as a compiled Language.

 C is a Procedural programming language.

 General purpose Language.

 Imperative Language.

Q) Why C is widely used Professional Language for various reasons?

A) REASONS:

 Easy to learn.

 Structured Language.

 Programs are efficient.

 Platform Independent.

 Can handle low level Activities.

Q) What are the applications of C?

A) Real Time Applications of C:

 Operating Systems.

 Language Compilers.

 Language Interpreters.

 Assemblers.

 Text editors.

 Data bases.

1
Structure of a C program

Program specification:

write a c program to print Hello World

Page | 2 Program:

#include<stdio.h>
Pre processor commands
int main()
Main function
{
Printf function to display
printf(“Hello World \n”);

Return 0; End of the main function


}

Output: Hello World

C tokens
C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.
...
C tokens are of six types. They are,

 Keywords (eg: int, while),


 Identifiers (eg: main, total),
 Constants (eg: 10, 20),
 Strings (eg: “total”, “hello”),
 Special symbols (eg: (), {}),
 Operators (eg: +, /,-,*)

Identifiers variables and character set


Identifiers:

Identifiers are also known as Keywords in C. These are names given to Variables
,constants, Functions ,Structures and user defined data.

 32 standard data types are given below.

Auto Double int struct


Break Else long typedef
Case Enum register union
Char Extern return unsigned
Const Float short volatile

2
Continue For signed sizeof
Default Goto static while
Do If void switch

Rules for an Identifiers:


Page | 3
1. An identifier can only have alphanumeric characters (a-z,A-Z,0-9) and (_).

2. The first character of an identifier can only contain alphabet(a-z , A-Z) or underscore(_).

3. Identifiers are also case sensitive in C . For example Name and name are two different
identifiers.

4. keywords are not allowed to be used as Identifiers.

5. No special character such as semicolon ,period ,whitespaces ,slash or comma are permitted
to be used as an identifier.

Variables :

A variable is a storage place which has some memory allocation to it.

 Natural size of integer(2 or 4 bytes).

 Single -precision Floating point(32 bits).

 Double-precision Floating point(64 bits).

 Typically a single octet(one byte).

 Represents the absence of type.

Rules to Name a variable:

 Variables should not start with a digit.

 variables name can consist of alphabets , digits and special symbols(@,$,#,* etc..,).

 keywords are not allowed as variable name .

 variable names should be given in lower case

Declaring the variable:

It should be done before they are used in the program.

Defining the variable:

Defining a variable is to assign a storage to the variable.[ int a,b;]

3
Initializing a variable:

Page | 4 initializing means to provide it with a value.

 A variable can be initialized and defined in a single statement . [ int a=10;]

Program Specification:

write a program to add the two variables.

Program:

#include<stdio.h>

extern int a,b; /*declaring the variables*/

extern int c;

int main()

int a,b; /*defining a variable*/

a=7;

b=14; /*initializing a variable*/

c=a+b;

Printf(“ sum is : %d \n”,c);

return 0;

Output:

sum is 21

4
Program specification:

Page | 5 write a C program to add two numbers without declaring the variables.

Program:

#include<stdio.h>

#include<conio.h>

int main()

int a,b,sum;

clrscr();

printf(“ enter the first number:”);

scanf(“%d”,&a);

printf(“ enter the second number: ”);

scanf(“ %d“,&b);

sum=a+b;

printf(“sum of two numbers: %d”,sum); output:

return 0; enter the first number:20

} enter the second number:19

sum of two numbers:39

Character set
Character:

It denotes any alphabet , digit or special symbols used to represent information.

Character set:

5
Fundamental raw material of any language and they are used to

Represent information.

Characters in C are divided into two categories:

Page | 6 Source character set:

 Alphabets
 Digits
 Special characters
 Escape sequence

Execution character set:

Escape sequence

Alphabets ----- A-Z,a-b

Digits----------- 0 1 2 3 4 5 6 7 8 9

Special characters:

 Tilde ( ~)

 Percent (%)

 Vertical bar (|)

 At (@)

 Plus (+)

 Less than (<)

 Greater than (>)

 Underscore (_)

 Minus (--)

 Caret (^)

 Number sign (#)

 Equal to (=)

 Ampersand (&)

 Question mark (?)

 Slash (/)

6
 Parenthesis [ () ]

 Asterisk (*)

 Back Slash (\)

Page | 7  Apostrophe (‘ ’)

 Colon (:)

 Brackets ([ ])

 Quotations (“ “)

 Semi colon (;)

 Exclamation (!)

 Comma (,)

 Dot operator (.)

 Flower braces ({})

 Dollar sign ($)

White Space Characters

• \b blank space

• \t horizontaltab

• \v verticaltab

• \r carriage return

• \f form feed

• \n new line

• \\ Back slash

• \’ Single quote

• \" Double quote

• \? Question mark

• \0 Null

• \a Alarm (bell

7
Execution Character Set:

Character ASCII value Escape Sequence Result

Page | 8
Null 000 \0 Null

Alarm (bell) 007 \a Beep Sound

Back space 008 \b Moves previous position

Horizontal tab 009 \t Moves next horizontal tab

New line 010 \n Moves next Line

Vertical tab 011 \v Moves next vertical tab

Form feed 012 \f Moves initial position of next


page

Carriage return 013 \r Moves beginning of the line

Double quote 034 \" Present Double quotes

Single quote 039 \' Present Apostrophe

Question mark 063 \? Present Question Mark

Back slash 092 \\ Present back slash

Octal number \000

Hexadecimal number \x

8
Identifiers and variables:

The identifier is only used to identify an entity uniquely in a program at the


time of execution whereas, a variable is a name given to a memory location ,that is used to hold a
Page | 9
value .

 Variable is only kinds of Identifiers are function names , class , names , structure names etc..

Example :

int a;

int a

identifier variable

Program Specification:

Write a C program to print an given integer.

Program:

#include <stdio.h>

int main()

int a;

printf("Enter an integer\n");

scanf("%d", &a);

printf("The integer is %d\n", a);

return 0;

} output:

enter an integer:7

The integer is 7

9
constants

Page | 10
Constants:

C Constants is the most fundamental and essential part of the C programming language.
Constants in C are the fixed values that are used in a program, and its value remains the same during
the entire execution of the program.

 Constants are also called literals.

 Constants can be any of the data types.

 It is considered best practice to define constants using only upper-case names.

Syntax:

const type constant_name;

Example:

#include<stdio.h>

int main()

const int SIDE = 10;

int area;

area = SIDE*SIDE;

printf("The area of the square with side: %d is: %d sq. units" , SIDE, area);

} output:

The area of the square with side:10 is:100 sq.units

Real constants:

The numbers containing fractional parts like 99.25 are called real or floating points
constant.

Integer constants:

 It's referring to a sequence of digits. Integers are of three types viz:

 Decimal Integer

10
 Octal Integer

 Hexadecimal Integer

Example:

Page | 11  15, -265, 0, 99818, +25, 045, 0X6

Character string:

It simply contains a single character enclosed within ' and ' (a pair of single quote). It
is to be noted that the character '8' is not the same as 8. Character constants have a specific set of
integer values known as ASCII values (American Standard Code for Information Interchange).

Example : 'X', '5', ';'

String constants:

 These are a sequence of characters enclosed in double quotes, and they may include letters,
digits, special characters, and blank spaces. It is again to be noted that "G" and 'G' are
different - because "G" represents a string as it is enclosed within a pair of double quotes
whereas 'G' represents a single character.

Example:

 "Hello!", "2015", "2+1

Data types
Qualifier:

Qualifiers are nothing but an addition of a prefix keyword with existing datatypes to add some extra
feature in a declared variable.

There are two qualifiers in C –

1. const

2. volatile

const in c

const keyword is used to make some variable constant in the program.

Example:

1.int x=5;

x is an integer variable which holds some data 5 and it can be changed to some other value
anywhere in the program.

2. const int x=5;

11
x is a constant integer variable which holds some data 5 and it can not be changed to some other
value anywhere in the program.

volatile Qualifier in C

 volatile keyword mostly used with the variable which can expect change from outside word
Page | 12
also i.e by external peripheral or some other thread.

 volatile keyword tells the compiler not to optimise code related the variable usually, when
we know it can be changed from “outside”.

Syntax:

volatile unsigned int vui_var;

Point to remember for volatile

 A compiler can not optimize the volatile variable i.e every time variable access from its real
memory location not from cache or somewhere else.

 The volatile variable may also have const qualifier if someone doesn’t want to modify in a
program.But this variable can change from outside peripheral or thread e.g status register

Enumerator :

The enum keyword allows a programmer to create a named finite set of elements. The names of the
elements of the set are also defined by the programmer.

 The sole purpose of the enumerator is to increase the clarity of the program.

 There is no input or output mechanism for enumerators, so the program must have hard
coded statements which set the value of the enumerator.

 Enumerator values are stored as integers, so integers can be used either in setting the value
of an enumerator or testing the value of an enumerator.

 The declaration of an enum defines the elements of the enumerator. It is necessary define a
variable to use the enum.

 By default the values stored for an enum variable is 0 through (N - 1), where the enumerator
has N elements. This can be changed, however

Program specification:

Write a C Program to demonstrate enum datatype.

Program:

#include <stdio.h>

enum week {sunday, monday, tuesday, wednesday, thursday, friday, Saturday};

12
int main()

enum week today;

Page | 13 today = wednesday;

printf("Day %d",today+1);

return 0;

Output: Day 4

Why enums are used?

Enum variable takes only one value out of many possible values.

Program Specification:

Write a C program to demonstrate the enum variable takes only one value of many
possible values.

Program:

#include <stdio.h>

enum suit

{club = 0, diamonds = 10, hearts = 20, spades = 3 } card;

int main()

card = club;

printf("Size of enum variable = %d bytes", sizeof(card));

return 0;

Output

Size of enum variable = 4 byte

13
Operators
Arithmetic Operators:

These are used to perform arithmetic/mathematical operations on operands.


Page | 14 The binary operators falling in this category are:

 Addition: The ‘+’ operator adds two operands. For example, x+y.

 Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.

 Multiplication: The ‘*’ operator multiplies For example, x*y.

 Division: The ‘/’ operator divides For example, x/y.

 Modulus: The ‘%’ operator returns the remainder whenFor example, x%y

Program Specification: write a C Program to demonstrate the working of arithmetic operators.

Program:

#include <stdio.h>

int main()

int a = 9,b = 4, c;

c = a+b;

printf("a+b = %d \n",c);

c = a-b;

printf("a-b = %d \n",c);

c = a*b;

printf("a*b = %d \n",c);

c=a/b;

printf("a/b = %d \n",c);

c=a%b;

printf("Remainder when a divided by b = %d \n",c);

return 0;

14
output:

a+b = 13

a-b = 5

Page | 15 a*b = 36

a/b = 2

Remainder when a divided by b=1

Relational operators:

• A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.

• Relational operators are used in decision making and loops.

Operator Meaning of Operator Example

== Equal to 5 == 3 returns 0

> Greater than 5 > 3 returns 1

< Less than 5 < 3 returns 0

!= Not equal to 5 != 3 returns 1

>= Greater than or equal to 5 >= 3 returns 1

<= Less than or equal to 5 <= 3 return 0

15
Program:

write a C program to demonstrate the working of Relational operators.

Program:

Page | 16 #include <stdio.h>

main()

int a = 21;

int b = 10;

int c ;

if( a == b )

printf("Line 1 - a is equal to b\n" );

else

printf("Line 1 - a is not equal to b\n" );

if ( a < b )

printf("Line 2 - a is less than b\n" );

else

printf("Line 2 - a is not less than b\n" );

if ( a > b )

16
printf("Line 3 - a is greater than b\n" );

else

Page | 17 {

printf("Line 3 - a is not greater than b\n" );

} /* Lets change value of a and b */

a = 5;

b = 20;

if ( a <= b )

printf("Line 4 - a is either less than or equal to b\n" );

if ( b >= a )

printf("Line 5 - b is either greater than or equal to b\n" );

Output:

Line 1 - a is not equal to b

Line 2 - a is not less than b

Line 3 - a is greater than b

Line 4 - a is either less than or equal to b

Line 5 - b is either greater than or equal to b

Assignment Operator in C Programming Language :

Assignment Operator is Used to assign value to an variable and is denoted by equal to


sign

17
Operator Description Example

= assigns values from right side operands to left side operand a=b
Page | 18

+= adds right operand to the left operand and assign the result to left a+=b is same as a=a+b

-= subtracts right operand from the left operand and assign the result to left a-=b is same as a=a-b
operand

*= mutiply left operand with the right operand and assign the result to left a*=b is same as a=a*b
operand

/= divides left operand with the right operand and assign the result to left a/=b is same as a=a/b
operand

%= calculate modulus using two operands and assign the result to left operand a%=b is same as a=a%b

Program Specification:

To demonstrate the working of Assignment operators.

Program:

#include <stdio.h>

main()

int a = 21;

18
int c ;

c = a;

printf("Line 1 - = Operator , Value of c = %d\n", c );

Page | 19 c += a;

printf("Line 2 - += Operator , Value of c = %d\n", c );

c -= a; printf("Line 3 - -= Operator , Value of c = %d\n", c );

c *= a;

printf("Line 4 - *= Operator , Value of c = %d\n", c );

c /= a;

printf("Line 5 - /= Operator , Value of c = %d\n", c );

c = 200;

c %= a;

printf("Line 6 - %= Operator , Value of c = %d\n", c );

Output:

Line 1 - = Operator , Value of c = 21

Line 2 - += Operator , Value of c = 42

Line 3 - -= Operator , Value of c = 21

Line 4 - *= Operator , Value of c = 441

Line 5 - /= Operator , Value of c = 21

Line 6 - %= Operator , Value of c = 11

Logical operators:

An expression containing logical operator returns either 0 or 1 depending upon whether


expression results true or false. Logical operators are commonly used in decision making in C
programming.

Operator Meaning of Operator Example

19
If c = 5 and d = 2 then,
Logial AND. True only if all
&& expression ((c == 5) && (d >
operands are true
5)) equals to 0.
Page | 20

If c = 5 and d = 2 then,
Logical OR. True only if either
|| expression ((c == 5) || (d >
one operand is true
5)) equals to 1.

Logical NOT. True only if the If c = 5 then, expression ! (c ==


!
operand is 0 5) equals to 0

Program Specification:

Write a C Program to demonstrate the working of logical operators.

Program:

#include <stdio.h>

int main()

int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);

printf("(a == b) && (c > b) equals to %d \n", result);

result = (a == b) && (c < b);

printf("(a == b) && (c < b) equals to %d \n", result);

result = (a == b) || (c < b);

20
printf("(a == b) || (c < b) equals to %d \n", result);

result = (a != b) || (c < b);

Page | 21 printf("(a != b) || (c < b) equals to %d \n", result);

result = !(a != b);

printf("!(a == b) equals to %d \n", result);

result = !(a == b);

printf("!(a == b) equals to %d \n", result);

return 0;

Output:

(a == b) && (c > b) equals to 1

(a == b) && (c < b) equals to 0

(a == b) || (c < b) equals to 1

(a != b) || (c < b) equals to 0

!(a != b) equals to 1

!(a == b) equals to 0

Explanation of logical operator program

 (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).

 (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).

 (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).

21
 (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).

 !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).

 !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).

Page | 22

Unary operators:

 C programming has two operators

increment ++ and decrement –

 To change the value of an operand (constant or variable) by 1.

Increment ++ increases the value by 1

 whereas decrement -- decreases the value by 1.

These two operators are unary operators, meaning they only operate on a single operator.

 Increment pre increment ( ++ a)

Post increment (a++)

 Decrement pre decrement (--a)

Post decrement (a--)

unary minus operator:

unary minus negate the value.

Program to demonstrate the unary minus operator

22
#include<stdio.h>

int main()

Page | 23 int a=10;

int b=-(a);

printf(“b=%d”,b);

return 0;

} Output:

b=-10

Ternary operator:

The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true comparison, and the
third is the result upon a false comparison

This operator used to shorten the if –else statement

Syntax :

result = condition? Value returned if true : value returned if false

Program specification: write a C program to demonstrate the woking of terinary operator.

Program:

#include <stdio.h>

main()

int a , b;

a = 10;

printf( "Value of b is %d\n", (a == 1) ? 20: 30 );

printf( "Value of b is %d\n", (a == 10) ? 20: 30 );}


Output:

value of b is 30

value of b is 20

23
Bitwise operators:

Bitwise operators are used for manipulating a data at the bit level, also called as bit level
programming. Bit-level programming mainly consists of 0 and 1. They are used in numerical
computations to make the calculation process faster.
Page | 24
Operator Meaning

& Bitwise AND operator

| Bitwise OR operator

^ Bitwise exclusive OR operator

~ Binary One's Complement Operator is a unary operator

<< Left shift operator

>> Right shift operator

The result of the computation of bitwise logical operators is shown in the table given below.

x y x&y x|y x^y

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

Decimal to binary conversion:

24
Page | 25

Program Specification:

write a program to demonstrate the bitwise & operator.

Program:

#include <stdio.h>

int main(void)

int x = 1, y = 2;

int result = x & y;

printf("%d & %d = %d\n", x, y, result);

return 0;

Output:

1&2=0

Calculation of the bitwise AND operation for the above code.

1 (decimal) = 0000 0001 (binary) &

2 (decimal) = 0000 0010 (binary)

-----------------------------------

0 (decimal) = 0000 0000 (binary)

Program Specification:

25
write a program to demonstrate the bitwise | operator

Program:

#include <stdio.h>

Page | 26 int main(void)

int x = 1, y = 2;

int result = x | y;

printf("%d | %d = %d\n", x, y, result);

return 0;

Output:

1|2=3

Calculation of the bitwise OR operation for the above code.

1 (decimal) = 0000 0001 (binary) |

2 (decimal) = 0000 0010 (binary)

-----------------------------------

3 (decimal) = 0000 0011 (binary)

Program: Write a program to demonstrate the bitwise ^ operator.

#include <stdio.h>

int main(void)

int x = 2, y = 7;

int result = x ^ y;

printf("%d ^ %d = %d\n", x, y, result);

return 0;

Output:

26
2^7=5

Page | 27 Calculation of the bitwise XOR operation for the above code.

2 (decimal) = 0000 0010 (binary) ^

7 (decimal) = 0000 0111 (binary)

-----------------------------------

5 (decimal) = 0000 0101 (binary)

Shift Left

We use shift left << operator to shift the bits left.

In the following example we have an integer which we will left shift 1 position.

Program Specification:

write a program to demonstrate the bitwise shift left <<.

Program:

#include <stdio.h>

int main(void)

//declare integer and assign value

int x = 4;

//shift left

int result = x << 1;

printf("Shift left x << 1 = %d\n", result);

return 0;

Output:

27
Shift left x << 1 = 8

Calculation:

4 (decimal) = 0000 0100 (binary)

Page | 28 ----------------------------------

4 << 1 = 0000 1000 (binary) = 8 (decimal)

Shift Right

We use shift right >> operator to shift the bits right.

In the following example we have an integer which we will right shift 1 position.

Program Specification:

write a program to demonstrate the bitwise right shift >> operator.

Program:

#include <stdio.h>

int main(void)

int x = 4;

int result = x >> 1;

printf("Shift left x >> 1 = %d\n", result);

return 0;

Output:

Shift right x >> 1 = 2

Calculation:

4 (decimal) = 0000 0100 (binary)

----------------------------------

4 >> 1 = 0000 0010 (binary) = 2 (decimal)

28
Control Structures
Control Structures :
Page | 29
1. If
2. If else
3. Nested if else
4. Switch

If statement

• Syntax of if statement:
The statements inside the body of “if” only execute if the given condition returns true. If the
condition returns false then the statements inside “if” are skipped.

if (condition)

//Block of C statements here //These statements will only execute if the condition is true

Figure 1: if condition.

Program Specification:

Write a c program to demonstrate the if condtion.

Program:

#include <stdio.h>

int main()

29
{

int x = 20;

int y = 22;

Page | 30 if (x<y)

printf("Variable x is less than y");

return 0;

Output:

Variable x is less than y

If else statement:

Syntax of if else statement:

 If condition returns true then the statements inside the body of “if” are executed and the
statements inside body of “else” are skipped.

 If condition returns false then the statements inside the body of “if” are skipped and the
statements in “else” are executed.

if(condition)

// Statements inside body of if

else

//Statements inside body of else

30
Page | 31

Figure 2: if else condition

Program Specification:

Write a C program to demonstrate the working the If-else condition.

Program:

#include <stdio.h>

int main()

int age;

printf("Enter your age:");

scanf("%d",&age);

if(age >=18)

printf("You are eligible for voting");

else

printf("\n You are not eligible for voting");

return 0;

31
Output:

Enter your age:14

You are not eligible for voting

Page | 32 Nested If..else statement

When an if else statement is present inside the body of another “if” or “else” then

this is called nested if else.

Syntax of Nested if else statement:

if(condition)

if(condition2)

//Statements inside the body of nested "if"

else

//Statements inside the body of nested "else"

else

//Statements inside the body of "else“

Example of nested if..else

#include <stdio.h>

int main()

int var1, var2;

32
printf("Input the value of var1:");

scanf("%d", &var1);

printf("Input the value of var2:");

Page | 33 scanf("%d",&var2);

if (var1 != var2)

printf("var1 is not equal to var2\n"); //Nested if else

if (var1 > var2)

printf("var1 is greater than var2\n");

else

printf("var2 is greater than var1\n");

else

printf("var1 is equal to var2\n");

return 0;

Output:

Input the value of var1:12

Input the value of var2:21

var1 is not equal to var2

var2 is greater than var1

33
Switch:

• The if..else..if ladder allows you to execute a block code among many alternatives. If you are
checking on the value of a single variable in if...else...if, it is better to use switchstatement.

• The switch statement is often faster than nested if...else (not always). Also, the syntax of
Page | 34
switch statement is cleaner and easy to understand

Syntax of switch case:

switch (n)

case constant1:

// code to be executed if n is equal to constant1;

case constant2:

// code to be executed if n is equal to constant2;

default:

// code to be executed if n doesn't match any constant

Example of Switch Case in C

#include <stdio.h>

int main()

int num=2;

switch(num+2)

case 1:

printf("Case1: Value is: %d", num);

case 2:

34
printf("Case2: Value is: %d", num);

case 3:

printf("Case3: Value is: %d", num);

Page | 35 default:

printf("Default: Value is: %d", num);

return 0;

Output:

Default: value is: 2

35
Looping statements
Loop :

loops are used in programming to repeat a block of code until specific condition is met.
Page | 36
Loops are of 3 types:

 For
 While
 Do while

For loop:

Syntax:

for(initializationStatement; test expression; update statement)

// code

 The initialization statement is executed only once.

 The test expression is evaluated if the test expression is true ,codes inside the body of for
loop is executed and the update expression is updated.

 This process repeats until the test expression is false.

 Flow chart for While loop:

Figure 3 flow chart of For loop

36
Program Specification:

Program to calculate the sum of first n natural numbers by using for loop

// Positive integers 1,2,3...n are known as natural numbers

Page | 37 Program:

#include <stdio.h>

int main()

int num, count, sum = 0;

printf("Enter a positive integer: ");

scanf("%d", &num);

for(count = 1; count <= num; ++count) // for loop terminates when n is less than count

sum =sum+ count;

printf("Sum = %d", sum);

return 0;

} Output:

Enter a positive integer: 5

Sum = 15

While loop :

Syntax:

while (testExpression)

//codes

37
DESCRIPTION:

• The while loop evaluates the test expression.

• If the test expression is true (nonzero), codes inside the body of while loop is executed. The
test expression is evaluated again. The process goes on until the test expression is false.
Page | 38
• When the test expression is false, the while loop is terminated.

Flow chart for While loop:

Figure 4: Flow chart of a While loop

Program specification:

write a C program to find Reverse of a Number in C by using While loop.

Program:

#include<stdio.h>

int main()

int n,a,r,s=0;

printf("\n Enter The Number:");

scanf("%d",&n);

a=n;

//LOOP FOR FINDING THE REVERSE OF A NUMBER

while(n>0)

38
r=n%10;

s=s*10+r;

n=n/10;

Page | 39 }

printf("\n The Reverse Number of %d is %d",s); OUTPUT:

return 0; Enter the Number: 4321

} The Reverse Number of 4321 is 1234

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 once, before checking the test expression. Hence, the do...while loop is
executed at least once.

Syntax:

do

// codes

} while (testExpression);

How do...while loop works?

• The code block (loop body) inside the braces is executed once.

• Then, the test expression is evaluated. If the test expression is true, the loop body is
executed again. This process goes on until the test expression is evaluated to 0 (false).

• When the test expression is false (nonzero), the do...while loop is terminated. Flow chart of

Figure 5 flow chart of do while:

39
Program specification:

Page | 40 Program to add numbers until user enters zero

Program:

#include <stdio.h>

int main()

double number, sum = 0; // body of loop is executed at least once

do

printf("Enter a number: ");

scanf("%lf", &number);

sum = sum+number;

while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;

Output

Enter a number: 1.5

Enter a number: 2.4

Enter a number: -3.4

Enter a number: 4.2

Enter a number: 0

Sum = 4.70

40
Break:

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

/* Break statement in C Programming example */

#include <stdio.h>

int main()

int i =0;

while(i<=10)

printf("\n The Value of the Variable = %d \n", i);

i++;

if (i==4)

break;

printf("\n This statement is from Outside the while Loop ");

return 0;

Output:

The value of the variable :0

The value of the variable :1

The value of the variable :2

The value of the variable :3

The statement is outside from while loop

41
Continue:

Continue statement are used to skips the rest of the current iteration in a loop

Page | 42 and returns to the top of the loop. The continue statement works like a shortcut

to the end of the loop body .

/* continue statement inside for loop*/

#include <stdio.h>

int main()

int j;

for ( j=0; j<=8; j++)

if (j==4)

{ /* The continue statement is encountered when * the value of j is equal to 4. */ continue;

/* This print statement would not execute for the * loop iteration where j ==4 because in that case
* this statement would be skipped. */

printf("%d ", j);

return 0;

Output:

01235678

Function calls
Function call by passing values:

call by value the actual arguments are copied to the formal arguments, hence any
operation performed by function on arguments doesn’t affect actual parameters.

42
Program Specification:

Program to demonstrate function calling by value (call by value).

Program:

Page | 43 #include <stdio.h>

int increment(int var)

var = var+1;

return var;

int main()

int num1=20;

int num2 = increment(num1);

printf("num1 value is: %d", num1);

printf("\nnum2 value is: %d", num2);

return 0;

Output:

num1 value is: 20

num2 value is: 21

Function passing call by reference:

When we call a function by passing the addresses of actual parameters then


this way of calling the function is known as call by reference. In call by reference, the operation
performed on formal parameters, affects the value of actual parameters because all the operations
performed on the value stored in the address of actual parameters.

Program Specification:

Write a C program to demonstrate function calling by reference (call by reference).

43
Program:

#include <stdio.h>

/*Function Prototype*/

Page | 44 void swapx(int*, int*);

int main()

int a = 10, b = 20;

swapx(&a, &b);

printf("a=%d b=%d\n", a, b);

return 0;

/* Function to swap two variables by references*/

void swapx(int* x, int* y)

int t;

t = *x;

*x = *y;

*y = t;

printf("x=%d y=%d\n", *x, *y);

Output:

x=20 y=10 a=20 b=10

Arrays:

Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more useful
to think of an array as a collection of variables of the same type.

44
Instead of declaring individual variables, such as number0, number1, ..., and number99,
you declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.

Declaring an array:
Page | 45
int data[100];

The size and type of arrays cannot be changed after its declaration.

Arrays are of two types:

1. One-dimensional arrays

2. Two-dimensional arrays

How to declare arrays?

data_type array_name[array_size];

For example,

float mark[5];

Elements of an Array and How to access them?

You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0], second element
is mark[1] and so on.

mark [0] mark [1] mark[2] mark [3]

Few key notes:

Arrays have 0 as the first index not 1. In this example, mark[0]

If the size of an array is n, to access the last element, (n-1) index is used. In this example, mark[4]

Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be 2124d,
address of a[2] will be 2128d and so on. It's because the size of a float is 4 bytes.

How to initialize an array?

It's possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

45
or

Another method to initialize array during declaration:

int mark[] = {19, 10, 8, 17, 9};

Page | 46

mark[0] mark[1] mark[2] mark[3] mark[4]

Here,

 mark[0] is equal to 19

 mark[1] is equal to 10

 mark[2] is equal to 8

 mark[3] is equal to 17

 mark[4] is equal to 9

Program Specification:

Write a C program to find the average of n (n < 10) numbers using arrays

Program:

#include <stdio.h>

int main()

int marks[10], i, n, sum = 0, average;

printf("Enter n: ");

scanf("%d", &n);

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

printf("Enter number%d: ",i+1);

scanf("%d", &marks[i]);

sum += marks[i];

average = sum/n;

46
printf("Average = %d", average); return 0;

} Output

Enter n: 5

Page | 47 Enter number1: 45

Enter number2: 35

Enter number3: 38

Enter number4: 31

Enter number5: 49 Average = 39

Two dimensional (2D) arrays in C programming with example

An array of arrays is known as 2D array. The two dimensional (2D) array in C programming is also
known as matrix. A matrix can be represented as a table of rows and columns.

Program specification:

Write a C program to demonstrate the two dimensional arrays .

Program:

#include<stdio.h>

int main()

{ /* 2D array declaration*/

int disp[2][3]; /*Counter variables for the loop*/

int i, j;

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

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

printf("Enter value for disp[%d][%d]:", i, j);

scanf("%d", &disp[i][j]);

//Displaying array elements

47
printf("Two Dimensional array elements:\n");

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

Page | 48 for(j=0;j<3;j++)

printf("%d ", disp[i][j]);

if(j==2)

printf("\n");

return 0;

Output:

Enter value for disp[0][0]:1

Enter value for disp[0][1]:2

Enter value for disp[0][2]:3

Enter value for disp[1][0]:4

Enter value for disp[1][1]:5

Enter value for disp[1][2]:6

Two Dimensional array elements: 1 2 3

456

48
Pointers
Pointers:

Pointers in C language is a variable that stores/points the address of another variable. A Pointer in C
Page | 49 is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to
any of the data type such as int, float, char, double, short etc.

Pointer Syntax : data_type *var_name; Example : int *p; char *p;

Where, * is used to denote that “p” is pointer variable and not a normal variable.

KEY POINTS TO REMEMBER ABOUT POINTERS IN C:

• Normal variable stores the value whereas pointer variable stores the address of the variable.

• The content of the C pointer always be a whole number i.e. address.

• Always C pointer is initialized to null, i.e. int *p = null.

• The value of null pointer is 0.

• & symbol is used to get the address of the variable.

• * symbol is used to get the value of the variable that the pointer is pointing to.

• If a pointer in C is assigned to NULL, it means it is pointing to nothing.

• Two pointers can be subtracted to know how many elements are available between these
two pointers.

• But, Pointer addition, multiplication, division are not allowed.

• The size of any pointer is 2 byte (for 16 bit compiler).

Program specification:

Program to demonstrate the working of pointers.

Program:

#include <stdio.h>

int main()

int *ptr, q;

q = 50;

/* address of q is assigned to ptr */

49
ptr = &q;

/* display q's value using ptr variable */

printf("%d", *ptr);

Page | 50 return 0;

OUTPUT:

50

Difference between pointer and an array:

• Array is a collection of variables belongings to the same data type. We can store group of
data of same data type in an array.

• Pointer is a single variable that stores the address of other object/variable

Program specification :

write a C program to add two number using pointers .

Program:

#include <stdio.h>

int main()

int num1, num2, sum;

int *ptr1, *ptr2;

ptr1 = &num1; // ptr1 stores the address of num1

ptr2 = &num2; // ptr2 stores the address of num2

printf("Enter any two numbers: ");

scanf("%d%d", ptr1, ptr2);

sum = *ptr1 + *ptr2;

printf("Sum = %d", sum);

return 0;

50
Output:

Enter any two variables: 5 4

Sum=9

Page | 51

Strings
Strings:

A string is an array of characters. a string is an array of characters terminated with a null


character \0.

For example:

"c string“

c s t r i n g \0

How to declare a string?

• Before you can work with strings, you need to declare them first. Since string is an array of
characters. You declare strings in a similar way like you do with arrays.

• If you don't know what arrays are, we recommend you to check C arrays.

Here's how you declare a string:

char s[5];

s[0] s[1] s[2] s[3] s[4]

How to initialize strings?

You can initialize strings in a number of ways.

char c[] = "abcd";

char c[5] = "abcd";

char c[] = {'a', 'b', 'c', 'd', '\0'};

char c[5] = {'a', 'b', 'c', 'd', '\0'};

51
c[0] c[1] c[2] c[3] c[4]

a b c d \0

Page | 52 Read String from the user

• You can use the scanf() function to read a string.

• The scanf() function reads the sequence of characters until it encounters


a whitespace(space, newline, tab etc.).

Program specification:

Write a C program to demonstrate the working of Strings.

Program:

#include <stdio.h>

int main()

char name[20];

printf("Enter name: ");

scanf("%s", name);

printf("Your name is %s.", name);

return 0;

Output:

Enter name: Rohith adapa

Your name is Rohith

How to read a line of text?

You can use gets() function to read a line of string. And, you can use puts() to display the string.

Program Specification:

Write a C program to demonstrate the gets() and puts() function.

52
Program:

#include <stdio.h>

int main()

Page | 53 {

char name[30];

printf("Enter name: ");

gets(name); // read string

printf("Name: ");

puts(name); // display string

return 0;

output :

Enter name: Roshini Adapa

Name: Roshini Adapa

Commonly Used String Functions

 strlen() - calculates length of a string

 strcpy() - copies a string to another

 strcmp() - compares two strings

 strcat() - concatenates two strings

C strlen()

The strlen() function calculates the length of a given string.

C strlen() Prototype

size_t strlen(const char *str);

 The function takes a single argument, i.e, the string variable whose length is to be found,
and returns the length of the string passed.

 The strlen() function is defined in <string.h> header file.

53
 Char c[ ]={‘p’,’r’,’o’,’g’,’r’,’a’,’m’,’\0’}

Temp=strlen(c);

The, temp will b e equal to 7 bacause , null character ‘\0’ is not counted

Page | 54
p r o g r a m \0

Program Specification :

write a C program to demonstrate strlen() function.

Program:

#include <stdio.h>

#include <string.h>

int main()

char a[20]="Program";

char b[20]={'P','r','o','g','r','a','m','\0'};

char c[20];

printf("Enter string: ");

gets(c);

printf("Length of string a = %d \n",strlen(a)); //calculates the length of string before null


charcter.

printf("Length of string b = %d \n",strlen(b));

printf("Length of string c = %d \n",strlen(c));

return 0;

Output

Enter string: String

Length of string a = 7

Length of string b = 7

54
Length of string c = 6

Page | 55 C strcpy()

The strcpy() function copies the string to the another character array.

strcpy() Function prototype

char* strcpy(char* destination, const char* source);

A. The strcpy() function copies the string pointed by source (including the null character) to the
character array destination.

B. This function returns character array destination.

C. The strcpy() function is defined in string.h header file.

Program specification:

Write a C program to demonstrate strcpy().

Program:

#include <stdio.h>

#include <string.h>

int main()

char str1[10]= "awesome";

char str2[10];

char str3[10];

strcpy(str2, str1);

strcpy(str3, "well");

puts(str2);

puts(str3);

return 0;

Output

55
Awesome

well

C strcmp()

Page | 56 The strcmp() function compares two strings and returns 0 if both strings are identical.

C strcmp() Prototype

int strcmp (const char* str1, const char* str2);

 The strcmp() function takes two strings and return an integer.

 The strcmp() compares two strings character by character.

 If the first character of two strings are equal, next character of two strings are compared.

 This continues until the corresponding characters of two strings are different or a null
character '\0' is reached.

 It is defined in string.h header file

Return Value from strcmp():

Return Value Remarks

0 if both strings are identical (equal)

Negative if the ASCII value of first unmatched character is less than second.

positive integer if the ASCII value of first unmatched character is greater than second

56
Program Specification:

Write a C program to demonstrate the strcmp().

Page | 57 Program:

#include <stdio.h>

#include <string.h>

int main()

char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";

int result; // comparing strings str1 and str2

result = strcmp(str1, str2);

printf("strcmp(str1, str2) = %d\n", result); // comparing strings str1 and str3

result = strcmp(str1, str3);

printf("strcmp(str1, str3) = %d\n", result);

return 0;

Output

strcmp(str1, str2) = 1

strcmp(str1, str3) = 0

Explanation:

The ASCII value of 'c' is 99 and the ASCII value of 'C' is 67. Hence, when strings str1 and str2 are
compared, the return value is 32

C strcat()

The function strcat() concatenates two strings.

 In C programming, strcat() concatenates (joins) two strings.

 The strcat() function is defined in <string.h> header file.

C strcat() Prototype

char *strcat(char *dest, const char *src)

57
 It takes two arguments, i.e, two strings or character arrays, and stores the resultant
concatenated string in the first string specified in the argument.

Program specification:
Page | 58
Write a C program to demostarte the working of strcat().

Program:

#include <stdio.h>

#include <string.h>

int main()

char str1[] = "This is ", str2[] = "programiz.com"; //concatenates str1 and str2 and resultant string is
stored in str1.

strcat(str1,str2);

puts(str1);

puts(str2);

return 0;

Output

This is programiz.com

programiz.com

58
Page | 59

59
Page | 60

60
Page | 61

61
Page | 62

62

You might also like