Programming in C
Programming in C
Objectives:
The objectives of this course is to make students to learn basic principles of Problem solving, implementing
through C programming language and to design & develop programming skills.
MODULE I
INTRODUCTION TO C LANGUAGE: Pseudocode solution to problem, Basic concepts of a C program,
I
Declaration, Assignment & Print statement, Types of operators and expressions, Programming examples and
R
exercise.
Text 1: Chapter 2 Text 2: 1.1, 1.2, 1.3 10 Hours
MODULE II
BRANCHING AND LOOPING: Two way selection (if, if-else, nested if-else, cascaded if-else), switch statement,
YS
ternary operator? Go to, Loops (For, do-while, while) in C, break and continue, programming examples and
exercises.
Text 1: Chapter 3 Text 2: 4.4 10 Hours
MODULE II
BRANCHING AND LOOPING: Two way selection (if, if-else, nested if-else, cascaded if-else), switch statement,
ternary operator? Go to, Loops (For, do-while, while) in C, break and continue, programming examples and
exercises.
MODULE III
SB
Text 1: Chapter 3 Text 2: 4.4 10 Hours
FUNCTIONS: Functions in C, Argument Passing – call by value, Functions and program structure, location of
functions, void and parameter less Functions, Recursion, programming examples and exercises.
Text 1: 1.7, 1.8, Chapter 4 Text 2: 5.1 to 5.4 10 Hours
O
MODULE IV
STRUCTURES AND FILE MANAGEMENT: Basic of structures, structures and Functions, Arrays of structures,
structure Data types, type definition, Defining, opening and closing of files, Input and output operations,
programming examples and exercises.
N
arrays, address arithmetic, character pointer and functions, pointers to pointer ,Initialization of pointers arrays,
Dynamic allocations methods, Introduction to Preprocessors, Complier control Directives, programming examples
and exercises.
Text 1: 5.1 to 5.6, 5.8 Text 2: 12.2, 12.3, 13.1 to 13.7
VT
Introduction to Data Structures: Primitive and non primitive data types, Definition and applications of Stacks,
Queues, Linked Lists and Trees.
Text 2: 14.1, 14.2, 14.11, 14.12, 14.13, 14.15, 14.16, 14.17, 15.1 08 Hours + 04 Hours
TEXT BOOK:
1. Brain W. Kernighan and Dennis M. Richie: The C programming Language, 2nd Edition, PHI, 2012.
2. Jacqueline Jones & Keith Harrow: Problem Solving with C, 1st Edition, Pearson 2011.
I
FUNCTIONS 49-57
R
MODULE IV: STRUCTURES & FILE MANAGEMENT 58-64
YS
MODULE V: POINTERS & PREPROCESSORS 65-76
WORKED EXAMPLES
SB
BASIC C PROGRAMS 90-93
TE
C PROGRAMS BASED ON BRANCHING 94-97
INTRODUCTION
• A computer is an electronic-device capable of manipulating numbers and symbols under the control
of a program.
• A program is a sequence of instructions written using a computer programming language to perform
a specified task.
I
A PSEUDOCODE SOLUTION TO PROBLEM
R
Algorithm
• An algorithm is a step by step procedure to solve a given problem in finite number of steps by
→ accepting a set of inputs and
YS
→ producing the desired output for the given problem
• Example: Write an algorithm to add 2 numbers entered by user.
Step 1: Start
Step 2: Declare variables num1, num2 & sum.
Step 3: Read values of num1 and num2.
Step 4: Add num1 & num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Pseudocode
SB
• Pseudocode is a method of describing the algorithm using a combination of
→ natural language (English like words) and
→ programming language
TE
• This is essentially an intermediate-step towards the development of the actual code.
• Although pseudocode is frequently used, there are no set of rules for its exact writing.
• Psuedocode is used in textbooks and scientific publications to describe various algorithms.
• For Example:
Problem 1: Input two numbers and display their sum.
1) read num1, num2
2) find sum = num1 + num2
O
3) display sum
Problem 2: Input the marks and display message “passed” or “failed” based on the marks.
1) read marks
2) if student's marks is greater than or equal to 35
N
print "passed"
else
print "failed"
U
endif
VT
A person who never made a mistake never tried anything new. -Albert Einstein
I
}
R
Preprocessor Directives
• The preprocessor accepts the source program and prepare the source program for
compilation.
• The preprocessor-statements start with symbol #.
YS
• The normal preprocessor used in all programs is include.
• The #include directive instructs the preprocessor to include the specified file-contents in the
beginning of the program.
• For ex:
#include<stdio.h>
main()
SB
• Every C program should have a function called as main().
• This the first function to be executed always.
• The statements enclosed within left and right brace is called body of the function. The main()
function is divided into 2 parts:
1) Declaration Section
• The variables that are used within the function main() should be declared in the
declaration-section only.
TE
• The variables declared inside a function are called local-variables.
Ex:
int p, t, r;
2) Executable Section
• This contains the instructions given to the computer to perform a specific task.
• The task may be to
O
→ display a message
→ read data or
→ add 2 numbers etc
• Comments are portions of the code ignored by the compiler. The comments allow the
N
{
printf(“Welcome to C”);
}
Output:
Welcome to C
Failure is simply the opportunity to begin again, this time more intelligently. -Henry Ford
I
Step 1: Before speaking any language, you should first learn alphabets. In the same way, to learn C
R
language, you should first learn alphabets in C.
Step 2: Then, you should learn how to group alphabets in particular sequence to form a meaningful
word. In the same way, in C language, you should learn tokens (i.e. words).
Step 3: Then, you should learn how to group the words in particular sequence to form a meaningful
YS
sentence. In the same way, in C language, you should learn instruction (i.e. sentence).
Step 4: Then, you should learn how to group the sentences in particular sequence to form a
meaningful paragraph. In the same way, in C language, you should learn program (i.e. paragraph).
CHARACTER SET
• Character-set refers to the set of alphabets, letters and some special characters that are valid in C
language.
• For example, the characters in C are:
SB
→ Letters A-X, a-z, both upper and lower
→ Digits 0-9
→ Symbols such as + - * / %
→ White spaces
TE
TOKENS
• A token is a smallest element of a C program.
• One or more characters are grouped in sequence to form meaningful words. These meaningful words
are called tokens.
• The tokens are broadly classified as follows
→ Keywords ex: if, for, while
O
Good actions are a guard against the blows of adversity. -Abu Bakr
I
typedef unsigned void while
R
IDENTIFIER
• As the name indicates, identifier is used to identify various entities of program such as variables,
constants, functions etc.
YS
• In other words, an identifier is a word consisting of sequence of
→ Letters
→ Digits or
→ "_"(underscore)
• For ex:
area, length, breadth
SB
TE
O
N
U
VT
Positive thinking will let you do everything better than negative thinking will.
I
ii) Octal constants (0 1 2 3 4 5 6 7)
R
For ex: 021, 077, 033
iii) Hexadecimal constants (0 1 2 3 4 5 6 7 8 9 A B C D E F)
For ex: 0x7f, 0x2a, 0x521
2) Floating Point Constant
YS
• The floating point constant is a real number.
• The floating point constants can be represented using 2 forms:
i) Fractional Form
• A floating point number represented using fractional form has an integer part followed
by a dot and a fractional part.
• For ex:
0.5, -0.99 SB
ii) Scientific Notation (Exponent Form)
• The floating point number represented using scientific notation has three parts namely:
mantissa, E and exponent.
• For ex:
9.86E3 imply 9.86*103
3) Character Constant
TE
• A symbol enclosed within a pair of single quotes(') is called a character constant.
• Each character is associated with a unique value called an ASCII (American Standard Code for
Information Interchange) code.
• For ex:
'9', 'a', '\n'
4) String Constant
O
• A sequence of characters enclosed within a pair of double quotes(“) is called a string constant.
• The string always ends with NULL (denoted by \0) character.
• For ex:
"9" "a" "sri" "\n"
N
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
You don't have to be great to start, but you have to start to be great -Zig Ziglar
I
• An int is a keyword which is used to define integers.
R
• Using int keyword, the programmer can inform the compiler that the data associated with this
keyword should be treated as integer.
• C supports 3 different sizes of integer:
→ short int
YS
→ int
→ long int
2) float
• A float is a keyword which is used to define floating point numbers.
3) double
• A double is a keyword used to define long floating point numbers.
4) char SB
• A char is a keyword which is used to define single character.
5) void
• void is an empty data type. Since no value is associated with this data type, it does not
occupy any space in the memory.
• This is normally used in functions to indicate that the function does not return any value.
Range of data types
TE
Data type Bytes Range of data type
char 1 bytes -128 to 127
int 2 bytes -32, 768 to 32,767
float 4 bytes 3.4E-38 to 3.4E38
double 8 bytes 1.7E-308 to 1.7E308
O
Qualifiers
• Qualifiers alter the meaning of primary data types to yield a new data type.
Size Qualifiers
• Size qualifiers alter the size of primary data type.
N
short int i; //The size of int is 2 bytes but, when short keyword is
//used, that variable will be of 1 byte
Sign Qualifiers
VT
• Whether a variable can hold positive value, negative value or both values is specified
by sign qualifiers.
• Keywords signed and unsigned are used for sign qualifiers.
unsigned int a; //unsigned variable can hold zero & positive values only
signed int b; //signed variable can hold zero , positive and negative values
Constant Qualifiers
• Constant qualifiers can be declared with keyword const.
• An object declared by const cannot be modified.
const int p=20; //the value of p cannot be changed in the program.
You have enemies? Good. That means you've stood up for something, sometime in your life. -Winston Churchill
I
5) Keywords should not be used as variable-names
R
• Valid variables:
a, principle_amount, sum_of_digits
Invalid variables:
3fact //violates rule 1
YS
sum= sum-of-digits 62$ //violates rule 3
for int if //violates rule 5
Declaration of Variable
• The declaration tells the complier
→ what is the name of the variable used
→ what type of date is held by the variable
• The syntax is shown below:
data_type v1,v2,v3;
SB
where v1,v2,v3 are variable-names
data_type can be int, float or char
• For ex:
int a, b, c;
float x, y, z;
TE
Initialization of Variable
• The variables are not initialized when they are declared. Hence, variables normally contain garbage
values and hence they have to be initialized with valid data.
• Syntax is shown below:
data_type var_name=data;
where data_type can be int, float or char
O
int a=10;
float pi=3.1416;
char c='z';
U
VT
Once you replace negative thoughts with positive ones, you'll start having positive results. -Willie Nelson
I
• For ex:
R
printf(), putchar(), putch(), puts()
Types of I/O Functions
• There are 2 types of I/O Functions as shown below:
YS
SB
TE
UNFORMATTED I/O
getchar() and putchar()
• getchar() is used to
→ read a character from the keyboard and
O
• For ex:
char z;
z= getchar( );
U
char x;
char y=‟n‟;
printf(“enter one letter terminated by ENTER key \n”);
x = getchar();
putchar(y); // same as printf(“%c”, z);
}
Output:
enter one letter terminated by ENTER key
m
n
When obstacles arise, u change ur direction to reach ur goal; u do not change ur decision to get there. -Zig Ziglar
I
}
R
Output:
enter one letter
m //m is not visible
m
YS
getche()
• getche() is used to read a character from the keyboard with echo(i.e. typed character will be visible
on the screen). The character thus entered will be stored in the memory-location.
#include<stdio.h>
void main()
{
int z;
z = getche();
putch( z);
SB
printf(“enter one letter \n”);
// same as printf(“%c”, z)
}
Output:
enter one letter
TE
m //m is visible
m
gets() and puts()
• gets() is used to
→ read a string from the keyboard and
→ store the string in memory-locations
O
char string[20];
printf("enter a string \n");
gets(string);
U
vtunotesbysri
vtunotesbysri
Expect the best. Prepare for the worst. Capitalize on what comes. -Zig Ziglar
I
• For ex:
R
n=scanf("%d %f %c", &x, &y, &z);
Format specifiers Meaning
%d an int argument in decimal
%ld a long int argument in decimal
YS
%c a character
%s a string
%f a float or double argument
%e same as %f, but use exponential notation
%o an int argument in octal (base 8)
%x an int argument in hexadecimal (base 16)
printf
The printf function does following tasks:
→ Accept a series of arguments
SB
→ Apply to each argument a format-specifier contained in the format-string
→ Output the formatted data to the screen
• The syntax is shown below:
TE
n=printf("format-string", variable-list);
where format-string contains one or more format-specifiers
variable-list contains names of variables
• For ex:
n=printf("%d %f %c", x, y, z );
• Example: Program to read your age and display the same on the screen.
O
#include<stdio.h>
void main()
{
int age;
N
Output:
enter your age:
21
VT
10
I
// Prints the number rounded to two decimal places
R
printf("Case 4:%.f \n",987.6543);
// Prints the number rounded to 0 decimal place, i.e., rounded to integer
printf("Case 5:%e ",987.6543);
// Prints the number in exponential notation(scientific notation)
YS
}
Output:
Case 1: 9876
Case 2:9876
Case 3:987.65
Case 4:988
Case 5:9.876543e+002
OPERATOR
SB
• An operator can be any symbol like + - * / that specifies what operation need to be performed on the
data.
• For ex:
+ indicates add operation
TE
* indicates multiplication operation
Operand
• An operand can be a constant or a variable.
Expression
• An expression is combination of operands and operator that reduces to a single value.
• For ex:
O
CLASSIFICATION OF OPERATORS
Operator Name For Example
Arithmetic operators +-*/%
Increment/decrement operators ++ --
U
Assignment operators =
Relational operators < > ==
Logical operators && || ~
VT
Conditional operator ?:
Bitwise operators & | ^
Special operators []
In order to succeed, your desire for success should be greater than your fear of failure. -Bill Cosby
11
I
→ returns the quotient.
R
Quotient is the result obtained after division operation.
• Modulus symbol (%)
→ divides the first operand by second operand and
→ returns the remainder.
YS
Remainder is the result obtained after modulus operation.
• To perform modulus operation, both operands must be integers.
• Program to demonstrate the working of arithmetic operators.
#include<stdio.h>
void main()
{
int a=9,b=4,c;
c=a+b;
printf("a+b=%d \n", c);
c=a-b;
SB
printf("a-b=%d \n", c);
c=a*b;
printf("a*b=%d \n", c);
TE
c=a/b;
printf("a/b=%d \n", c);
c=a%b;
printf("Remainder when a divided by b=%d ", c);
}
Output:
O
a+b=13
a-b=5
a*b=36
a/b=2
N
Too many of us are not living our dreams because we are living our fears. -Les Brown
12
I
then increase the value of variable by 1.
R
• As the name indicates, pre-increment means first increase the value of variable by 1 and
then use the updated value of variable.
• For ex:
If x is 10,
YS
then z= x++; sets z to 10
but z = ++x; sets z to 11
Example: Program to illustrate the use of increment operators.
#include<stdio.h>
void main()
{
int x=10,y = 10, z ;
z= x++;
SB
printf(“ z=%d x= %d\n”, z, x);
z = ++y;
printf(“ z=%d y= %d”, z, y);
}
Output:
TE
z=10 x=11
z=11 y=11
DECREMENT OPERATOR
• -- is a decrement operator.
• As the name indicates, decrement means decrease, i.e. this operator is used to decrease the value of
a variable by 1.
O
• For example:
If b=5
then b-- or --b; // b becomes 4
• Similar to increment operator, the decrement operator is classified into 2 categories:
N
void main()
{
int x=10,y = 10, z ;
z= x--;
printf(“ z=%d x= %d\n”, z, x);
z = --y;
printf(“ z=%d y= %d”, z, y);
}
Output:
z=10 x=9
z=9 y=9
If the only prayer you ever say in your entire life is thank you, it will be enough. -Meister Eckhart
13
I
a=a+10: can be written as a+=10;
R
• In the same way, we have:
Operator Example Same as
-= a-=b a=a-b
*= a*=b a=a*b
YS
/= a/=b a=a/b
%= a%=b a=a%b
RELATIONAL OPERATORS
• Relational operators are used to find the relationship between two operands.
• The output of relational expression is either true(1) or false(0).
• For example SB
a>b //If a is greater than b, then a>b returns 1 else a>b returns 0.
• The 2 operands may be constants, variables or expressions.
• There are 6 relational operators:
Operator Meaning of Operator Example
> Greater than 5>3 returns true (1)
< Less than 5<3 returns false (0)
TE
>= Greater than or equal to 5>=3 returns true (1)
<= Less than or equal to 5<=3 return false (0)
== Equal to 5==3 returns false (0)
!= Not equal to 5!=3 returns true(1)
• For ex:
Condition Return values
O
#include<stdio.h>
void main()
{
printf(“4>5 : %d \n”, 4>5);
U
Failure is not the opposite of success; it's part of success. -Arianna Huffington
14
I
A B A&&B A||B !A
R
0 0 0 0 1
0 1 0 1
1 0 0 1 0
1 1 1 1
YS
• Example: Program to illustrate the use of all logical operators.
#include<stdio.h>
void main()
{
clrscr ( );
printf(“7 && 0 : %d \n”, 7 && 0 );
}
SB
printf(“7 || 0 : %d \n”, 7 || 0 );
printf(“ !0 : %d”, !0 );
Output:
7 && 0 : 1
7 || 0 : 1
TE
!0 : 1
• Example: Program to illustrate the use of both relational & Logical operators.
#include<stdio.h>
void main()
{
printf(“5>3 && 5<10 : %d \n”, 5>3 && 5<10);
O
15
I
{
R
int a,b, max ;
printf(“ enter 2 distinct numbers \n”);
scanf(“%d %d”, &a, &b);
max=(a>b)? a : b;
YS
printf(“ largest number =%d ”, max);
}
Output:
enter 2 distinct numbers
34
largest number = 4
BITWISE OPERATORS
SB
• These operators are used to perform logical operation (and, or, not) on individual bits of a binary
number.
• There are 6 bitwise operators:
Operators Meaning of operators
& Bitwise AND
TE
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Truth Table
O
1 1 1 1 0
• Ex for ~ (bitwise complement) Ex for & (bitwise AND)
a = 13 0000 1101 a = 13 0000 1101
U
16
I
R
YS
IMPLICIT CONVERSION
SB
• If a compiler converts one type of data into another type of data automatically, it is known as implicit
conversions.
• There is no data loss in implicit conversion.
• The conversion always takes place from lower rank to higher rank.
TE
For ex, int to float as shown in the above datatype hierarchy.
• For ex:
int a = 22, b=11;
float c = a; //c becomes 21.000000
float d=b/c=11/22.000000=11.000000/22.000000=0.500000
• If one operand type is same as other operand type, no conversion takes place and type of result
O
{
int a = 22, b=11;
float d ;
d=b/c;
printf("d Value is : %f ", d );
}
Output:
d Value is : 0.500000
No matter what people tell you, words and ideas can change the world. -Robin Williams
17
I
float d=b/(float)c=11.000000/22.000000=0.500000
R
• Example: Program to illustrate explicit conversion.
#include<stdio.h>
void main()
{
YS
float b=11.000000;
int c = 22;
float d;
d=b/(float)c;
printf("d Value is : %f ", d );
}
Output:
d Value is : 0.500000
SB
TE
O
N
U
VT
Those who dare to fail miserably can achieve greatly. -John F. Kennedy
18
I
R
YS
#include<stdio.h>
void main()
SB
• Example to understand the operator precedence available in C programming language.
{
int a = 20;
TE
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d \n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
O
e = a + (b * c) / d; // 20 + (150/5)
printf("Value of a + (b * c) / d is : %d " , e );
}
Output:
U
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
VT
Value of a + (b * c) / d is : 50
The two most important days in your life are the day you are born and the day you find out why. -Mark Twain
19
STATEMENT
• A statement is also called instruction.
• As the name indicates, instruction is used to instruct computer to perform a particular task like
→ adding two numbers
→ reading data from keyboard or
I
• For ex:
sum=a+b;
R
scanf("%d ", &n);
• In C, the semicolon(;) is a statement terminator.
Compound Statement
YS
• The sequence of statement enclosed within a pair of braces { and } is called a compound statement.
• For ex:
{
a=l*b;
printf("area =%d", a);
}
CONTROL STRUCTURES SB
• A program is nothing but the execution of sequence of one or more instructions.
• Quite often, it is desirable to change the order of execution of statements based on certain conditions
or
• This involves a kind of decision making to see whether a particular condition has occurred or not and
direct the computer to execute certain statements accordingly.
TE
• Based on application, it is necessary / essential
i) To alter the flow of a program
ii) Test the logical conditions
iii) Control the flow of execution as per the selection these conditions can be placed in the
program using decision-making statements.
i) while loop
ii) for loop
iii) do-while loop
3) Unconditional control statements
VT
i) break statement
ii) continue statement
Dont let the noise of others opinions drown out your own inner voice. -Steve Jobs
20
I
4. If given marks are less than 30 then
R
5. Student is poor
YS
• Now, question is how to write programming code to handle such situation. C language provides
conditional i.e., decision making statements which work based on the following flow diagram:
SB
TE
O
If you have good thoughts they will shine out of your face like sunbeams and you will always look lovely. -Roald Dahl
21
I
• The flow diagram is shown below:
R
YS
SB
• Example: Program to illustrate the use of if statement.
TE
#include<stdio.h>
void main()
{
int n;
printf(“Enter any non zero integer: \n”) ;
scanf(“%d”, &n)
if(n>0)
O
}
Output:
Enter any non zero integer:
7
U
I have found that if you love life, life will love you back. -Arthur Rubinstein
22
I
}
R
• Firstly, the expression is evaluated to true or false.
If the expression is evaluated to true, then statement1 is executed.
If the expression is evaluated to false, then statement2 is executed.
• The flow diagram is shown below:
YS
SB
TE
else
printf(“Number is negative number”);
}
Output:
U
Change your thoughts and you change your world. -Norman Vincent Peale
23
I
}
R
else
{
if(expr3)
statement3
YS
else
statement4
}
• Here, firstly expr1 is evaluated to true or false.
If the expr1 is evaluated to true, then expr2 is evaluated to true or false.
If the expr2 is evaluated to true, then statement1 is executed.
SB
If the expr2 is evaluated to false, then statement2 is executed.
If the expr1 is evaluated to false, then expr3 is evaluated to true or false.
If the expr3 is evaluated to true, then statement3 is executed.
If the expr3 is evaluated to false, then statement4 is executed.
• The flow diagram is shown below:
TE
O
N
U
VT
24
I
printf(“ %d ”, a);
R
else
printf(“ %d ”, c);
}
else
YS
{
if(b>c)
printf(“ %d”, b);
else
printf(“ %d”, c);
}
}
Output:
Enter Three Values:
786
SB
Largest Value is: 8
TE
O
N
U
VT
A dream doesnt become reality through magic; it takes sweat, determination and hard work. -Colin Powel
25
I
statement4
R
else
default statement5
• The expressions are evaluated in order (i.e. top to bottom).
• If an expression is evaluated to true, then
YS
→ statement associated with the expression is executed &
→ control comes out of the entire else if ladder
• For ex, if exprression1 is evaluated to true, then statement1 is executed.
If all the expressions are evaluated to false, the last statement4(default case) is executed.
SB
TE
O
N
int n;
printf(“Enter any integer:”) ;
scanf(“%d”, &n)
if(n>0)
VT
Its better to be a lion for a day than a sheep all your life. -Elizabeth Kenny
26
I
R
YS
• Here, choice can be either any integer value or a character.
• Based on this integer value, the control is transferred to a particular case-value where necessary
statements are executed. SB
• During executing, if break statement is encountered, then the control comes out of the switch block.
• If the value of the choice does not match with any of the case values (i.e. value1, value2, value3)
then control goes to default label.
• All case-values must be different.
• Example: Program to illustrate the use of switch statement.
void main()
TE
{
char grade; // local variable definition
printf(“enter grade A to D: \n”);
scanf(“%c”,&grade);
switch(grade)
{
O
27
I
R
}
Output:
Welcome to C language
Welcome to C language
YS
Welcome to C language
Welcome to C language
Welcome to C language
• When the program is executed, it produces the above result.
• It was simple, but again let's consider another situation when you want to write the same message
thousand times, what you will do in such situation?
SB
• Are we going to write printf() statement thousand times? No, not at all.
• C language provides a concept called loop, which helps in executing one or more statements up to
desired number of times.
• Loops are used to execute one or more statements repeatedly.
• The flow diagram is shown below:
TE
O
1) while loop
2) for loop
3) do while loop
U
VT
Tell me and I forget. Teach me and I remember. Involve me and I learn. -Benjamin Franklin
28
I
of the loop.
R
• If the expression is evaluated to true, the body of the loop (i.e. statement1) is executed.
• After executing the body of the loop, control goes back to the beginning of the while statement and
expression is again evaluated to true or false. This cycle continues until expression becomes false.
• The flow diagram is shown below:
YS
SB
TE
while(i<=5)
{
printf(“Welcome to C language \n”);
i=i+1;
N
}
}
Output:
Welcome to C language
U
Welcome to C language
Welcome to C language
Welcome to C language
VT
Welcome to C language
Do not be embarrassed by your failures, learn from them and start again. -Richard Branson
29
I
• Firstly, expr1 is evaluated. It is executed only once.
R
• Then, expr2 is evaluated to true or false.
• If expr2 is evaluated to false, the control comes out of the loop without executing the body of the
loop.
• If expr2 is evaluated to true, the body of the loop (i.e. statement1) is executed.
YS
• After executing the body of the loop, expr3 is evaluated.
• Then expr2 is again evaluated to true or false. This cycle continues until expression becomes false.
• The flow diagram is shown below:
SB
TE
O
#include<stdio.h>
void main()
{
U
int i;
for(i=1;i<=5;i++)
{
printf(“Welcome to C language \n”);
VT
}
}
Output:
Welcome to C language
Welcome to C language
Welcome to C language
Welcome to C language
Welcome to C language
30
I
• After executing the body of the loop, the expression is again evaluated to true or false. This cycle
R
continues until expression becomes false.
• The flow diagram is shown below:
YS
SB
Example: Program to display a message 5 times using do while statement.
#include<stdio.h>
void main()
TE
{
int i=1;
do
{
printf(“Welcome to C language \n”);
i=i+1;
O
}while(i<=5);
}
Output:
N
Welcome to C language
Welcome to C language
Welcome to C language
U
Welcome to C language
Welcome to C language
VT
Don't aim for success if you want it; just do what you love and believe in, and it will come naturally. -David Frost
31
I
R
YS
SB
Example: Write the program given in switch statement.
TE
O
N
U
VT
The hunger for love is much more difficult to remove than the hunger for bread. -Mother Teresa
32
I
R
YS
Example: Program to read and add only positive numbers using continue statement.
#include<stdio.h>
void main()
{
int i=1, num, sum =0;
for(i=0; i < 5; i ++)
{
SB
printf(“ Enter an integer:”);
scanf( “%d”, &num);
if(num < 0)
TE
{
printf(“you have entered a negative number \n”);
continue ; // skip the remaining part of loop
}
sum=sum+num;
}
O
Enter an integer:-15
You have entered a negative number
Enter an integer: 15
U
33
I
R
• Example: Program to detect the entered number as to whether it is even or odd. Use goto statement.
#include<stdio.h>
void main()
YS
{
int x;
printf(“Enter a Number: \n”);
scanf(“%d”, &x);
if(x % 2 = = 0)
goto even;
else
goto odd;
SB
even: printf(“%d is Even Number”);
return;
odd: printf(“ %d is Odd Number”);
}
Output:
TE
Enter a Number:
5
5 is Odd Number.
O
N
U
VT
Life's most persistent and urgent question is, What are you doing for others?
34
I
void main()
{
R
int number1;
int number2;
int number3;
YS
int number4;
int number5;
number1 = 10;
number2 = 20;
number3 = 30;
number4 = 40;
number5
printf(
printf(
= 50;
"number1:
"number2:
%d
%d
SB
\n", number1);
\n", number2);
printf( "number3: %d \n", number3);
printf( "number4: %d \n", number4);
TE
printf( "number5: %d ", number5);
}
Output:
number1: 10
number2: 20
number3: 30
number4: 40
O
number5: 50
• It was simple, because we had to store just 5 integer numbers. Now let's assume we have to store
5000 integer numbers, so what is next? Are we going to use 5000 variables?
N
ARRAY
VT
Success consists of going from failure to failure without loss of enthusiasm. -Winston Churchill
35
I
• The above code can be pictorially represented as shown below:
R
YS
• Note that, the first element is numbered 0 and so on.
• Here, the size of array „age‟ is 5 times the size of int because there are 5 elements.
Storing Values in Arrays
• The values can be stored in array using following three methods:
1) Initialization
2) Assigning values
3) Input values from keyboard
#include<stdio.h>
void main()
{
int age[5]={2,4,34,3,4};
N
Run when you can, walk if you have to, crawl if you must; just never give up. -Dean Karnazes
36
I
{
R
int age[5];
age[0]=2;
age[1]=4;
age[2]=34;
YS
age[3]=3;
age[4]=4;
}
Output:
printf("Value
printf("Value
in
in
SB
array
array
age[3]
age[4]
:
:
%d
%d
\n", age[3]);
",age[4]);
There are no secrets to success. It is the result of preparation, hard work, and learning from failure. -Colin Powell
37
I
scanf("%d", &age[i]);
R
}
• Similarly, to display 5 elements stored in the array, we can write:
for(i=0;i<5;i++)
{
YS
printf("%d", age[i]);
}
• Example: Program to illustrate reading/writing to one-dimensional array.
#include<stdio.h>
void main()
{
int age[5], i; SB
printf("enter 5 numbers:\n”);
for(i=0;i<5;i++)
{
scanf("%d", &age[i]);
}
TE
for(i=0;i<5;i++)
{
printf("Value in array age[%d] : %d \n ", i, age[i]);
}
}
O
Output:
enter 5 numbers:
2 4 34 3 4
Value in array age[0] :2
N
Never worry about numbers. Help one person at a time and always start with the person nearest you. -Mother Teresa
38
I
• A two dimensional array is used when elements are arranged in a tabular fashion.
R
• Here, to identify a particular element, we have to specify 2 indices:
→ First index identifies the row number of the element and
→ Second index identifies the column number of the element
Declaration of Two Dimensional Arrays
YS
• The syntax is shown below:
data_type array_name[array_size][array_size];
• For ex:
int matrix[2][3];
• The above code can be pictorially represented as shown below:
SB
Initialization of Two Dimensional Arrays
• For ex:
int matrix[2][3]= {1, 23, 11, 44, 5, 6};
TE
• The above code can be pictorially represented as shown below:
O
N
U
VT
The only place success comes before work is in the dictionary. -Vince Lombardi
39
I
{
R
for(j=0;j<3;j++)
{
scanf("%d", &matrix[i][j]);
}
YS
}
• Similarly to display 6 elements stored in the matrix, we can write:
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
}
}
SB
printf("%d ", matrix[i][j]);
scanf("%d", &matrix[i][j]);
}
}
printf("elements of the matrix are: \n”);
N
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
U
}
}
Output:
enter elements of 2*3 matrix:
1 23 11
44 5 6
elements of the matrix are:
1 23 11
44 5 6
Be faithful in small things because it is in them that your strength lies. -Mother Teresa
40
I
}
R
void main()
{
int c[3]={2,3,4};
YS
display(c[2]); //Passing array-element c[2] only.
}
Output:
4
2) Passing the Whole Array
• Here, the parameter passing is similar to pass by reference.
SB
• In pass by reference, the formal parameters are treated as aliases for actual parameters.
• So, any changes in formal parameter imply there is a change in actual parameter.
• Example: Program to find average of 6 marks using pass by reference.
#include <stdio.h>
void average(int m[])
{
int i ,avg;
TE
int avg, sum=0;
for(i=0;i<6;i++)
{
sum= sum+ m[i];
}
avg =(sum/6);
O
void main()
N
{
int m[6]={60, 50, 70, 80, 40, 80, 70};
average(m); // Only name of array is passed as argument
}
U
Output:
aggregate marks= 70
VT
41
STRING VARIABLE
• There is no separate data type for strings in C.
I
• They are treated as arrays of type „char‟.
R
• So, a variable which is used to store an array of characters is called a string variable.
Declaration of String
• Strings are declared in C in similar manner as arrays.
YS
Only difference is that, strings are of „char‟ type.
• For ex:
char s[5]; //string variable name can hold maximum of 5 characters including NULL character
• The above code can be pictorially represented as shown below:
Initialization of String
• For ex:
char s[5]={'r', 'a', 'm', 'a' };
char s[9]="rama";
SB
• The above code can be pictorially represented as shown below:
TE
• Example: Program to illustrate the initialization of string.
#include<stdio.h>
void main()
{
char s[5]={'r','a','m','a'}; //or char s[5]="rama";
printf("Value in array s[0] : %c \n", s[0]);
O
Output:
Value in array s[0] : r
Value in array s[1] : a
Value in array s[2] : m
U
When you have a dream, you've got to grab it and never let go. -Carol Burnett
42
I
scanf(“%s”, name);
R
printf(“welcome: ”);
printf(“%s”, name);
}
Output:
YS
enter your name:
rama
welcome: rama
Output:
enter your name:
rama
welcome: rama
N
U
VT
Worry does not empty tomorrow of its sorrow. It empties today of its strength. -Corrie Ten Boom
43
I
R
YS
strlen() SB
• This function calculates the length of string. It takes only one argument, i.e., string-name.
• The syntax is shown below:
temp_variable = strlen(string_name);
TE
#include<string.h>
#include<stdio.h>
void main()
{
N
char c[20];
int len;
printf("Enter string whose length is to be found:");
U
gets(c);
len=strlen(c);
printf("\n Length of the string is %d ", len);
}
VT
Output:
Enter string whose length is to be found: program
Length of the string is 7
He is happiest, be he king or peasant, who finds peace in his home. -Johann Wolfgang von Goethe
44
I
printf("Enter string: ");
R
gets(src);
strcpy(dest, src); //Content of string src is copied to string dest
printf("Copied string: ");
puts(dest);
YS
}
Output:
Enter string: vtunotesbysri
Copied string: vtunotesbysri
strcat()
gets(str2);
strcat(str1,str2); //concatenates str1 and str2 and
printf("\n Concatenated String is ");
puts(str1); //resultant string is stored in str1
N
}
Output:
Enter First String: rama
Enter Second String: krishna
U
If you cant make it good, at least make it look good. -Bill Gates
45
I
printf("Enter first string: ");
R
gets(str1);
printf("Enter second string: ");
gets(str2);
if(strcmp(str1,str2)==0)
YS
printf("Both strings are equal");
else
printf("Strings are unequal");
}
Output:
Enter first string: rama
Enter second string: rama
Both strings are equal
SB
TE
O
N
U
VT
A successful man is one who can lay a firm foundation with the bricks others have thrown at him. -David Brinkley
46
while(str1[len]!='\0')
I
len++; //here the length of string is calculated.
R
printf("Length of the string is %d", len);
}
Output:
YS
Enter string whose length is to be found: vtunotesbysri
Length of the string is 13
}
str1[i]='\0';
printf("\n Concatenated String is ");
puts(str1);
N
}
Output:
Enter First String: rama
Enter Second String: krishna
U
Love begins by taking care of the closest ones - the ones at home. -Mother Teresa
47
I
dest[i] = src[i];
R
i++;
}
dest[i] = '\0';
printf("Copied String ; %s ", dest);
YS
}
Output:
Enter string : vtunotesbysri
Copied String : vtunotesbysri
flag=1;
break;
}
i++;
N
}
if (flag==0 && str1[i]=='\0' && str2[i]=='\0')
flag=1;
else
U
flag=0;
if(flag == 1)
printf("Both strings are equal");
VT
else
printf("Both strings are not equal");
}
Output:
Enter first string: rama
Enter second string: rama
Both strings are equal
48
FUNCTION IN C
• A function is a block of code to perform a specific task.
• Every C program has at least one function main( ). Without main() function, there is technically no C
program.
• Program to print a sentence using function is shown below.
I
R
YS
SB
TE
TYPES OF C FUNCTIONS
• There are 2 types of functions in C programming:
→ Library function
→ User defined function
Library Function
• Library functions are the in-built function in C compiler.
O
For example:
→ main() //The execution of every C program starts from this main() function
→ printf() //prinf() is used for displaying output in C
→ scanf() //scanf() is used for taking input in C
N
same program. Then, he can create two separate user-defined functions in that program:
→ one for finding factorial and
→ other for checking whether it is prime or not
VT
Don't judge each day by the harvest you reap but by the seeds that you plant. -Robert Louis Stevenson
49
I
R
void function_name() //function definition
{
................
................
YS
}
• As mentioned earlier, every C program begins from main() and program starts executing the codes
inside main() function.
• When the control of program reaches to function_name() inside main() function, the control of
program jumps to void function_name() and executes the codes inside it.
• When all the codes inside that user-defined function are executed, control of the program jumps to
the statement just after function_name() from where it is called.
Function Declaration SB
• Every function in C program should be declared before they are used.
• Function declaration gives compiler information about
→ function name
→ type of arguments to be passed and
→ return type
• The syntax is shown below:
TE
return_type function_name(type(1) argument(1),....,type(n) argument(n));
Function Call
• Control of the program cannot be transferred to user-defined function unless it is called
invoked.
• The syntax is shown below:
function_name(argument(1),....argument(n));
O
Function Definition
• Function definition contains programming codes to perform specific task.
• The syntax is shown below:
return_type function_name(type(1) argument(1),..,type(n) argument(n))
N
{
//body of function
}
U
void main()
{
display(); //function call
}
void display() //function definition
{ printf("C Programming");
return;
}
Output:
C Programming
You are always a student, never a master. You have to keep moving forward. -Conrad Hall
50
I
int add(int a, int b);
R
int main()
{
int a,b,sum;
printf("Enters two number to add \n");
YS
scanf("%d %d", &a,&b); //actual arguments
sum=add(a,b);
printf("\n sum=%d", sum);
return 0;
}
int add(int a,int b) //formal arguments
{
int sum;
sum=a+b;
return sum;
SB
}
Output:
Enters two number to add
TE
23
sum=5
O
N
U
VT
Optimism is a happiness magnet. If you stay positive, good things and good people will be drawn to you. -Mary Lou Retton
51
I
printf(“enter values of x & y : “);
R
scanf(“%d %d “, &x, &y);
printf(“\n old values x=%d y =%d”, x, y);
change(x,y) ;
printf(“\n new values x=%d y =%d”, x, y);
YS
}
void change(int a, int b)
{
k=a;
a=b;
b=k;
}
Output:
return;
Dont wait. The time will never be just right. -Napoleon Hill
52
I
add();
R
}
void add()
{
int a, b, sum;
YS
printf("Enters two number to add : ");
scanf("%d %d", &a, &b);
sum=a+b;
printf("\n sum=%d", sum);
return;
}
Output:
Enters two number to add : 2 3
sum=5
SB
Example: Program to illustrate function with no arguments and return value.
#include <stdio.h>
int add();
TE
void main()
{
int sum;
sum=add();
printf("\n sum=%d", sum);
O
}
int add()
{
int a, b, sum;
N
}
Output:
Enters two number to add
VT
23
sum=5
53
I
{
R
sum= a+ b;
printf("\n sum=%d", sum);
return;
}
YS
Output:
Enters two number to add
23
sum=5
{
int sum;
sum=a+b;
return sum; //return statement of function
N
}
Output:
Enters two number to add
23
U
sum=5
VT
I'd rather attempt to do something great and fail than to attempt to do nothing and succeed. -Robert H. Schuller
54
int add(int n)
{
if(n==0)
return n;
else
return n+add(n-1); /*self call to function add() */
I
}
R
void main()
{
int num, sum;
YS
printf("Enter a positive integer: ");
scanf("%d",&num);
sum=add(num);
printf("sum=%d", sum);
}
Output:
Explanation:
Enter a positive integer: 5
15
SB
• Here, add() function is invoked from the same function.
• If n is not equal to 0 then, the function calls itself passing argument 1 less than the previous
argument it was called with.
• Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function and the value of
TE
argument decreases by 1 in each recursive call.
• When, n becomes equal to 0, the value of n is returned which is the sum numbers from 5 to 1.
• Observe the following for better visualization of recursion in this example:
add(5)
=5+ add(4)
=5+4+ add(3)
O
=5+4+3+ add(2)
=5+4+3+2+ add(1)
=5+4+3+2+1+ add(0)
=5+4+3+2+1+0
N
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
U
=15
• Every recursive function must be provided with a way to end the recursion. In this example when, n
is equal to 0, there is no recursive call and recursion ends.
VT
Opportunity is missed by most people because it is dressed in overalls and looks like work. -Thomas A. Edison
55
AUTOMATIC VARIABLE
I
• Variables declared inside the function body are automatic by default.
R
• These variables are also known as local variables as they are local to the function and doesn't have
meaning outside that function.
• For example:
int a,b; or auto int a,b;
YS
• Since, variable inside a function is automatic by default, keyword auto are rarely used.
EXTERNAL VARIABLES
• External variable can be accessed by any function. They are also known as global variables.
• Variables declared outside every function are external variables.
• In case of large program, containing more than one file, if the global variable is declared in file 1 and
SB
that variable is used in file 2 then, compiler will show error.
• To solve this problem, keyword extern is used in file 2 to indicate that, the variable specified is global
variable and declared in another file.
• Example: Program to demonstrate working local and global variables.
#include <stdio.h>
int z; // z is a global variable
TE
void display()
{
printf("\n sum=%d", z);
}
void main()
O
z=a+b;
display();
}
U
Output:
Enters two number to add: 2 3
sum=5
VT
REGISTER VARIABLES
• Register variables are similar to automatic variable and exists inside that particular function only.
• For example:
register int z;
where z is register variable
• If the compiler encounters register variable, it tries to store variable in microprocessor's register
rather than memory.
• Value stored in register are much faster to access than that of memory.
• In case of larger program, variables that are used in loops and function parameters are declared
register variables.
Beware of false knowledge; it is more dangerous than ignorance. -George Bernard Shaw
56
I
Output:
R
Enters two number to add
23
sum=5
YS
STATIC VARIABLE
• The value of static variable persists until the end of the program.
• For example:
static int c;
where c is a static variable
• Example: Program to demonstrate working of static variable.
#include <stdio.h>
void Check()
{
static int c=0;
SB
printf("%d \t",c);
c=c+5;
}
TE
int main()
{
Check();
Check();
Check();
O
}
Output:
0 5 10
Explanation:
N
Optimism is a happiness magnet. If u stay positive, gud things & gud people will be drawn to u. -Mary Lou Retton
57
INTRODUCTION
• Suppose, you want to store the information about person about his name, citizenship number and
salary.
• You can create these information separately but, better approach will be collection of these
information under single name because all these information are related to person.
I
• For this purpose, structure can be used.
R
STRUCTURES
• Structure is a collection of elements of different data type.
• The syntax is shown below:
YS
struct structure_name
{
data_type member1;
data_type member2;
data_type member3;
};
• The variables that are used to store the data are called members of the structure.
struct person
{
char name[50];
SB
• We can create the structure for a person as shown below:
int cit_no;
float salary;
TE
};
• This declaration above creates the derived data type struct person.
O
N
U
VT
58
I
Inside main function:
R
struct person p1, p2;
• Here the above statement declares that the variables p1 and p2 are variables of type struct
person.
• Once the structure variable is declared, the compiler allocates memory for the structure
YS
variables.
• The size of the memory allocated is the sum of size of individual members.
2) Type Defined Structure
• Another way of creating sturcture variable using the keyword typedef is:
typedef struct person
{
char name[50];
int cit_no;
float salary;
}EMP;
SB
Inside main function:
EMP p1 ,p2 ;
• Here the above statement declares that the variables p1 and p2 are variables of type
TE
EMP(which is of type as struct person)..
Structure Variable Initialization
• For ex:
struct person
{
char name[50];
O
int cit_no;
float salary;
};
struct person p1={"ram", 24, 23000};
N
structure_variable_name.member_name
• By specifying p1.name, we can access the name „ram‟.
By specifying p1.salary, we can access the value „23000‟.
VT
Build your own dreams, or someone else will hire you to build theirs. -Farrah Gray
59
struct person
{
I
char name[50];
R
int cit_no;
float salary;
struct dob d1;
};
YS
Inside main:
struct person p1 ,p2 ;
• Suppose you want to access month for p1 structure-variable then, structure-member p1.d1.month is
used.
item3.data='c';
item1.link=item2.link=item3.link=NULL;
• We can attach these structures together as follows:
item1.link=&item2;
N
tem2.link=&item3;
U
VT
If ur actions inspire others to dream more, learn more, do more & become more, u are a leader. -John Quincy Adams
60
I
#include<stdio.h>
R
struct student
{
char name[50];
int roll;
YS
};
void main()
{
SB
struct student s1;
printf("Enter student's name: ");
scanf("%s", &s1.name);
TE
printf("Enter roll number: ");
scanf("%d", &s1.roll);
Display(s1); //passing structure variable s1 as argument
}
Output:
O
61
I
float img;
R
};
YS
// Adding complex numbers c1 and d2 and storing it in c3
c3->real=c1.real+c2.real;
c3->img=c1.img+c2.img;
}
void main()
{
struct comp c1, c2, c3;
SB
printf("First complex number \n");
printf("Enter real part: ");
scanf("%d",&c1.real);
printf("Enter imaginary part: ");
scanf("%f",&c1.img);
TE
printf("Second complex number \n");
printf("Enter real part: ");
scanf("%d",&c2.real);
printf("Enter imaginary part: ");
scanf("%f",&c2.img);
Add(c1, c2, &c3);
O
}
Output:
First complex number
Enter real part: 3
U
Your most unhappy customers are your greatest source of learning. -Bill Gates
62
INTRODUCTION
• A computer file is used to store data in digital format like plain text, image data or any other content.
• Computer files can be considered as the digital counterpart of paper documents, which traditionally
are kept in office.
• While doing programming, you keep your source code in text files with different extensions.
I
• For example, C programming files have .c extension, Java programming files have .java extension.
File Operations
R
1) Creating a new file
2) Opening an existing file
3) Reading from and writing information to a file
YS
4) Closing a file
Life isn't about finding yourself. Life is about creating yourself. -George Bernard Shaw
63
I
int fprintf(FILE *fp, const char *format, ...)
R
#include <stdio.h>
void main()
{
FILE *fp;
YS
fp = fopen("/tc/bin/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
• When the above code is compiled and executed, it creates a new file test.txt in /tc/bin directory and
• You can use the following function to read a text file character by character:
int fgetc( FILE * fp );
• The fgetc() function reads a character from the input file referenced by fp.
• This function returns the character being read on success; otherwise returns EOF if there is an error.
• You can use the following function to read a string from a stream:
TE
char *fgets( char *buf, int n, FILE *fp );
• The functions fgets() reads up to n-1 characters from the input stream referenced by fp.
• It copies the read string into the buffer buf, appending a null character to terminate the string.
• If this function encounters a newline character '\n‟, then it returns only the characters read up to that
point including new line character.
• You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file but it
O
FILE *fp;
char buff[255];
fp = fopen("/tc/bin/test.txt", "r");
fscanf(fp, "%s", buff);
U
64
INTRODUCTION
• As you know, every variable is a memory-location and every memory-location has its address defined
which can be accessed using ampersand(&) operator, which denotes an address in memory.
• Consider the following example, which will print the address of the variables defined:
#include<stdio.h>
I
void main()
{
R
int var1;
char var2;
printf("Address of var1 variable: %d \n", &var1 );
YS
printf("Address of var2 variable: %d", &var2 );
return 0;
}
Output:
Address of var1 variable: 1266
Address of var2 variable: 1268
POINTER
SB
• A pointer is a variable which holds address of another variable or a memory-location.
• For ex:
c=300;
pc=&c;
Here pc is a pointer; it can hold the address of variable c
TE
& is called reference operator
O
N
U
VT
65
I
4) Access data using pointer-variable ex: printf("%d",*pc);
R
• Example: Program to illustrate working of pointers.
#include<stdio.h>
void main()
{
YS
int *pc;
int c;
c=22;
printf("Address of c: %d \n", &c);
printf("Value of c: %d \n", c);
pc=&c;
}
SB
printf("Address of pointer pc: %d \n", pc);
printf("Content of pointer pc: %d",*pc);
Output:
Address of c: 1232
Value of c: 22
TE
Address of pointer pc: 1232
Content of pointer pc: 22
O
NULL POINTER
VT
• A NULL pointer is defined as a special pointer value that points to '\0'(nowhere) in the memory. In
other words, NULL pointer does not point to any part of the memory.
• For ex:
int *p=NULL;
The future belongs to those who believe in the beauty of their dreams. -Eleanor Roosevelt
66
• The name of the array always points to the first element of an array.
• Here, address of first element of an array is &arr[0].
I
• Also, arr represents the address of the pointer where it is pointing. Hence, &arr[0] is equivalent to
R
arr.
• Also, value inside the address &arr[0] and address arr are equal. Value in address &arr[0] is arr[0]
and value in address arr is *arr. Hence, arr[0] is equivalent to *arr.
• Similarly,
YS
&a[1] is equivalent to (a+1) AND, a[1] is equivalent to *(a+1).
&a[2] is equivalent to (a+2) AND, a[2] is equivalent to *(a+2).
&a[3] is equivalent to (a+1) AND, a[3] is equivalent to *(a+3).
.
.
&a[i] is equivalent to (a+i) AND, a[i] is equivalent to *(a+i).
SB
• You can declare an array and can use pointer to alter the data of an array.
• Example: Program to access elements of an array using pointer.
#include<stdio.h>
void main()
{
int data[5], i;
printf("Enter elements: ");
TE
for(i=0;i<5;++i)
scanf("%d", data+i);
printf("You entered: ");
for(i=0;i<5;++i)
printf("%d ",*(data+i) );
}
O
Output:
Enter elements: 1 2 3 5 4
You entered: 1 2 3 5 4
• Example: Program to find sum of all the elements of an array using pointers.
N
#include<stdio.h>
void main()
{
U
for(i=0;i<n;i++)
scanf("%d ",&a[i]);
for(i=0;i<n;i++)
sum+=*(a+i);
printf("Sum --> %d ",sum);
}
Output:
Enter the size of the array:5
Enter the elements into the array: 2 4 6 10 15
Sum --> 37
Action may not always bring happiness; but there is no happiness without action. -Benjamin Disraeli
67
I
}
R
void main()
{
int num1=5,num2=10;
YS
swap(&num1, &num2); //address of num1 & num2 is passed to swap function
printf("Number1 = %d \n",num1);
printf("Number2 = %d",num2);
}
Output:
Number1 = 10
Number2 = 5
Explanation
SB
• The address of memory-location num1 and num2 are passed to function and the pointers *a
and *b accept those values.
• So, the pointer a and b points to address of num1 and num2 respectively.
• When, the value of pointer is changed, the value in memory-location also changed
correspondingly.
TE
• Hence, change made to *a and *b was reflected in num1 and num2 in main function.
• This technique is known as call by reference.
O
N
U
VT
I have decided to stick with love. Hate is too great a burden to bear. -Martin Luther King, Jr.
68
I
• We prefer using a pointer in our program instead of an array because the variable pointer can be
R
incremented, unlike the array name which cannot be incremented because it is a constant pointer.
• Example: Program to increment the variable pointer to access each succeeding element of the array.
#include<stdio.h>
void main()
YS
{
int var[] = {10, 100, 200};
int i, *ptr;
ptr = var;
for ( i = 0; i < 3; i++)
{
}
ptr++;
SB
printf("Address of var[%d] = %x \n", i, ptr );
printf("Value of var[%d] = %d \n", i, *ptr );
//move to the next location
}
Output:
Address of var[0] = 1130
TE
Value of var[0] = 10
Address of var[1] = 1132
Value of var[1] = 100
Address of var[2] = 1134
Value of var[2] = 200
O
N
U
VT
Coming together is a beginning; keeping together is progress; working together is success. -Henry Ford
69
• A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name.
• For example, following is the declaration to declare a pointer to a pointer of type int:
int **var;
• When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires
I
that the asterisk operator be applied twice, as is shown below in the example:
R
#include<stdio.h>
void main()
{
YS
int var;
int *ptr;
int **pptr;
var = 3000; // take the address of var
ptr = &var; // take the address of ptr using address of operator &
pptr = &ptr; // take the value using pptr
printf("Value of var = %d \n", var );
}
SB
printf("Value available at *ptr = %d \n", *ptr );
printf("Value available at **pptr = %d ", **pptr);
return 0;
Output:
Value of var = 3000
Value available at *ptr = 3000
TE
Value available at **pptr = 3000
O
N
U
VT
Monsters are real, and ghosts are real too. They live inside us, and sometimes, they win. -Stephen King
70
I
These are used to conditionally skip sections of source code.
R
#error
This is used to issue errors for the current program.
Use of #include
YS
• Let us consider very common preprocessing directive as below:
#include <stdio.h>
• Here, "stdio.h" is a header file and the preprocessor replace the above line with the contents of
header file.
• Example: Program to illustrate use of #include
#include <stdio.h>
int main()
{
printf("VTUNOTESBYSRI");
return 0;
SB
}
Output:
VTUNOTESBYSRI
TE
Use of #define
• Analyze following examples to understand this directive.
#define PI 3.1415
• The string 3.1415 is replaced in every occurrence of symbolic constant PI,
• Example: Program to find area of a circle using #define.
O
#include<stdio.h>
#define PI 3.1415
int main()
{
N
int radius;
float area;
printf("Enter the radius: ");
scanf("%d", &radius);
U
area=PI*radius*radius;
printf("Area=%.2f",area);
return 0;
VT
}
Output:
Enter the radius: 3
Area=28.27
The way to get started is to quit talking and begin doing. -Walt Disney
71
I
printf ("MAX is not defined");
R
#endif
}
Output:
MAX is defined
YS
Use of #error
• The #error directives allow instructing the compiler to generate an error.
• For example, we wish to issue a warning when a symbol is defined in the current project.
• Example: Program to illustrate use of #error.
#include<stdio.h>
#define MAX 100
void main()
{
#if(MAX)
SB
#error: MAX is defined by me!!!
..
..
TE
..
#endif
}
Output:
#error: MAX is defined by me!!!
O
Use of #undef
• Consider an example shown below:
#undef FILE_SIZE
#define FILE_SIZE 42
N
• This tells the preprocessor to undefine existing FILE_SIZE and define it as 42.
U
VT
72
I
• Dynamic memory allocation is the process of allocating memory-space during execution-time
R
i.e. run time.
• If there is an unpredictable storage requirement, then the dynamic allocation technique is
used.
• This allocation technique uses predefined functions to allocate and release memory for data
YS
during execution-time.
• There are 4 library functions for dynamic memory allocation:
1) malloc()
2) calloc()
3) free()
4) realloc()
SB
• These library functions are defined under "stdlib.h"
TE
O
N
U
VT
73
I
• For ex:
R
ptr=(int*)malloc(100*sizeof(int));
• The above statement will allocate 200 bytes assuming sizeof(int)=2 bytes.
• Example: Program to find sum of n elements entered by user. Allocate memory dynamically using
malloc() function.
YS
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n, i, *ptr, sum=0;
printf("Enter number of elements: ");
scanf("%d",&n); SB
ptr=(int*)malloc(n*sizeof(int));
printf("Enter elements of array: ");
for(i=0;i<n;++i)
//memory allocated using malloc
{
scanf("%d ",ptr+i);
sum+=*(ptr+i);
TE
}
printf("Sum=%d",sum);
free(ptr);
}
Output:
Enter number of elements: 3
O
Laziness may appear attractive, but work gives satisfaction. -Anne Frank
74
I
ptr=(int*)calloc(25,sizeof(int));
R
• The above statement allocates contiguous space in memory for an array of 25 elements each of size
of int, i.e., 2 bytes.
• Example: Program to find sum of n elements entered by user. Allocate memory dynamically using
calloc() function.
YS
#include <stdio.h>
#include <stdlib.h>
void main()
{
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n); SB
ptr=(int*)calloc(n,sizeof(int));
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d ",ptr+i);
sum+=*(ptr+i);
TE
}
printf("Sum=%d",sum);
free(ptr);
}
Output:
Enter number of elements: 3
O
free()
N
• Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The
programmer must use free() explicitly to release space.
• The syntax is shown below:
free(ptr);
U
Before anything else, preparation is the key to success. -Alexander Graham Bell
75
I
printf("Enter size of array: ");
R
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;i++)
YS
printf("%u \n", ptr+i);
printf("\n Enter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
printf("Address of newly allocated memory: ");
for(i=0;i<n2;i++)
}
Output:
printf("%u \n", ptr+i);
1028
1030
N
U
VT
Formal education will make you a living; self-education will make you a fortune. -Jim Rohn
76
I
• The primitive data types are the basic data types that are available in most of the programming
R
languages.
• The primitive data types are used to represent single values.
Integer: This is used to represent a number without decimal point.
Eg: 12, 90
YS
Float: This is used to represent a number with decimal point.
Eg: 45.1, 67.3
Character: This is used to represent single character
Eg: „C‟, „a‟
String: This is used to represent group of characters.
Eg: "M.S.P.V.L Polytechnic College"
• The data types that are derived from primary data types are known as non-Primitive data types.
• These datatypes are used to store group of values.
• The non-primitive data types are
Arrays
Structure
TE
Stacks
Linked list
Queue
Binary tree
O
N
U
VT
77
I
R
YS
APPLICATIONS OF STACK
SB
1) Conversion of expressions: The compiler converts the infix expressions into postfix expressions
using stack.
2) Evaluation of expression: An arithmetic expression represented in the form of either postfix or prefix
can be easily evaluated using stack.
3) Recursion: A function which calls itself is called recursive function.
TE
4) Other applications: To find whether the string is a palindrome, to check whether a given expression
is valid or not.
O
N
U
VT
If you take responsibility for yourself you will develop a hunger to accomplish your dreams. -Les Brown
78
if (top==(MAXSIZE-1))
I
{
R
printf ("Error: Overflow ");
}
else
{
YS
printf ("Enter the element to be pushed \n");
scanf ("%d", &num);
top = top + 1;
stack[top] = num;
}
}
void pop()
{
int num;
SB
//Function to delete an element from the stack
if (top==-1)
{
printf ("Error: Stack Empty\n");
TE
}
else
{
num = stack[top];
printf ("popped element is = %d \n", num);
top=top-1;
O
}
}
{
int i;
if (top == -1)
{
U
{
printf ("\n Items in Stack \n");
for (i = top; i >= 0; i--)
{
printf ("%d \n", stack[i]);
}
}
}
Yesterday is not ours to recover, but tomorrow is ours to win or lose. -Lyndon B. Johnson
79
I
scanf ("%d", &choice);
R
switch (choice)
{
case 1: push();
break;
YS
case 2: pop();
break;
case 3: display();
break;
case 4: return;
}
}
}
Output:
SB
1. PUSH
2. POP
TE
3. DISPLAY
4. EXIT
Enter your choice
1
Enter the element to be pushed
11
O
1. PUSH
2. POP
N
3. DISPLAY
4. EXIT
Enter your choice
1
U
1. PUSH
2. POP
3. DISPLAY
4. EXIT
Enter your choice
1
Enter the element to be pushed
33
What can you do to promote world peace? Go home and love your family. -Mother Teresa
80
I
1. PUSH
R
2. POP
3. DISPLAY
4. EXIT
Enter your choice
YS
2
popped element is = 33
1. PUSH
2. POP
3. DISPLAY
4. EXIT
Enter your choice
2
popped element is = 22
SB
TE
O
N
U
VT
81
I
4) Underflow: If queue is empty and try to delete an item, underflow condition occurs.
R
• This can be pictorially represented as shown below:
YS
Program to implement a queue using an array.
#include <stdio.h>
#define MAX 50
SB
int queue_array[MAX], rear = - 1, front = - 1;
insert()
TE
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow ");
else
{
if (front == - 1) //If queue is initially empty
O
front = 0;
printf("Insert the element in queue : ");
scanf("%d", &add_item);
rear=rear+1;
N
queue_array[rear]=add_item;
}
} //End of insert()
U
delete()
{
if (front == - 1 || front > rear)
VT
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} //End of delete()
The soul always knows what to do to heal itself. The challenge is to silence the mind -Caroline Myss
82
I
}
R
}
main()
{
YS
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n"); SB
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1: insert();
break;
TE
case 2: delete();
break;
case 3: display();
break;
case 4: exit(1);
default: printf("Wrong choice \n");
O
} //End of switch
} //End of while
} //End of main()
N
Output:
83
I
Enter your choice : 1
R
Inset the element in queue : 30
YS
3.Display all elements of queue
4.Quit
Enter your choice : 2
Element deleted from queue is : 10
You don't have to see the whole staircase, just take the first step. -Martin Luther King, Jr.
84
I
4) Display the contents of list
R
SINGLY LINKED LIST
• This is a collection of zero or more nodes where each node has two or more fields and only one link
field which contains address of the next node.
YS
• This can be pictorially represented as shown below:
{
int value;
// Node Declaration
SB
• In C, this can be represented as shown below:
struct node
The amount of good luck coming your way depends on your willingness to act. -Barbara Sher
85
I
R
typedef struct node snode;
snode *newnode, *ptr, *prev, *temp;
snode *first = NULL, *last = NULL;
YS
snode* create_node(int val) // Creating Node
{
newnode = (snode *)malloc(sizeof(snode));
if (newnode == NULL)
{
}
else
return 0;
SB
printf("\nMemory was not allocated");
{
newnode->value = val;
newnode->next = NULL;
TE
return newnode;
}
}
{
int val;
printf("\nEnter the value for the node:");
scanf("%d", &val);
N
newnode = create_node(val);
if (first == last && first == NULL)
{
first = last = newnode;
U
first->next = NULL;
last->next = NULL;
}
VT
else
{
temp = first;
first = newnode;
first->next = temp;
}
}
It does not matter how slowly you go as long as you do not stop. -Confucius
86
I
}
R
}
}
int main()
YS
{
int ch;
char ans = 'Y';
while (1)
{
SB
printf("\n Operations on singly linked list\n");
printf("\n 1.Insert node at first");
printf("\n 2.Display List from Beginning to end");
printf("\n 3.Exit\n");
printf("\n Enter your choice: ");
scanf("%d", &ch);
TE
switch (ch)
{
case 1: printf("\n...Inserting node at first...\n");
insert_node_first();
break;
case 2: printf("\n...Displaying List From Beginning to End...\n");
O
display();
break;
case 3: printf("\n...Exiting...\n");
return 0;
N
break;
default: printf("\n...Invalid Choice...\n");
break;
}
U
}
return 0;
}
VT
Output:
Happiness is not something you postpone for the future; it is something you design for the present. -Jim Rohn
87
I
3.Exit
R
Enter your choice: 1
...Inserting node at first...
Enter the value for the node: 300
YS
Operations on singly linked list
1.Insert node at first
2.Delete Node from any Position
3.Exit
Enter your choice: 2
...Displaying List From Beginning to End...
100 200 300 SB
TE
O
N
U
VT
Love is a fruit in season at all times, and within reach of every hand. -Mother Teresa
88
I
R
YS
BINARY TREE APPLICATIONS
SB
• Tree traversal refers to process of visiting all nodes of a tree exactly once (Figure 5.16).
• There are 3 techniques, namely:
1) Inorder traversal(LVR);
2) Preorder traversal(VLR);
TE
3) Postorder traversal(LRV). (Let L= moving left, V= visiting node and R=moving right).
• In postorder, we visit a node after we have traversed its left and right subtrees.
In preorder, the visiting node is done before traversal of its left and right subtrees.
In inorder, firstly node‟s left subtrees is traversed, then node is visited and
• For above tree, tree traversal is as follows
Inorder traversal → DBEACGFH
Preorder traversal → ABDECFGH
O
You may be disappointed if you fail, but you are doomed if you don't try. -Beverly Sills
89
WORKED EXAMPLES
BASIC C PROGRAMS
I
{
R
printf("C Programming"); //displays the content inside quotation
return;
}
Output:
YS
C Programming
{
int num1, num2, sum;
printf("Enter two integers: ");
scanf("%d %d",&num1,&num2); // Stores the two integer entered by user in
N
return;
}
Output:
Enter two integers: 12
VT
11
Sum: 23
Don't be pushed by your problems. Be led by your dreams. -Ralph Waldo Emerson
90
I
}
R
Output:
Enter two numbers: 2.4
1.1
Product: 2.640000
YS
PROGRAM TO FIND QUOTIENT AND REMAINDER OF TWO INTEGERS ENTERED BY USER
#include <stdio.h>
void main()
{
int dividend, divisor, quotient, remainder;
printf("Enter dividend: ");
scanf("%d",÷nd);
printf("Enter divisor: ");
scanf("%d",&divisor);
SB
quotient=dividend/divisor; // Computes quotient
remainder=dividend%divisor; // Computes remainder
printf("Quotient = %d\n",quotient);
TE
printf("Remainder = %d",remainder);
return;
}
Output:
Enter dividend: 25
Enter divisor: 4
O
Quotient = 6
Remainder = 1
N
main( )
{
int l, b, area;
printf(“enter length and breadth”);
VT
The only person you are destined to become is the person you decide to be. -Ralph Waldo Emerson
91
I
Output:
R
enter radius
4
area of circle=12.58
YS
PROGRAM TO FIND THE SIMPLE INTEREST
#include<stdio.h>
void main()
{
int amount, rate, time, si;
scanf("%d", &amount);
SB
printf("\nEnter Principal Amount : ");
return(0);
O
}
Output:
Enter Principal Amount : 500
Enter Rate of interest : 5
N
#include<stdio.h>
main()
{
VT
int n, p;
printf(“enter a number”);
scanf(“%d”,&n);
p=n*n;
printf(“The square of the number is %d”,p);
}
Output:
enter a number
4
The square of the number is 16
If you are not willing to risk the unusual, you will have to settle for the ordinary. -Jim Rohn
92
I
enter a number
R
4
The cube of the number is 64
YS
#include <stdio.h>
void main()
{
float a, b, temp;
printf("Enter value of a: ");
scanf("%f",&a);
printf("Enter value of b: ");
scanf("%f",&b);
SB
temp = a; // Value of a is stored in variable temp
a = b; // Value of b is stored in variable a
b = temp; //Value of temp is stored in variable b
printf("\nAfter swapping, value of a = %.2f\n", a);
printf("After swapping, value of b = %.2f", b);
TE
return;
}
Output:
Enter value of a: 1.20
Enter value of b: 2.45
After swapping, value of a = 2.45
O
PROGRAM TO FIND RATIO OF NUMBER OF FEMALE AND MALE STUDENTS IN A CLASS USING
EXPLICIT CONVERSION.
N
#include <stdio.h>
void main()
{
U
Setting goals is the first step in turning the invisible into the visible. -Tony Robbins
93
I
scanf("%f %f", &a, &b);
if(a>b)
R
printf("Largest number = %.2f", a);
if(b>a)
printf("Largest number = %.2f", b);
YS
return;
}
Output:
Enter three numbers:
13.452
10.193
Largest number = 13.45 SB
PROGRAM TO FIND THE LARGEST NUMBER AMONG THREE NUMBERS USING IF STATEMENT.
#include <stdio.h>
void main()
{
TE
float a, b, c;
printf("Enter three numbers: ");
scanf("%f %f %f", &a, &b, &c);
if(a>=b && a>=c)
printf("Largest number = %.2f", a);
if(b>=a && b>=c)
printf("Largest number = %.2f", b);
O
Output:
Enter three numbers: 12.2
13.452
U
10.193
Largest number = 13.45
VT
Define success on ur own terms, achieve it by ur own rules, & build a life u'r proud to live. -Anne Sweeney
94
I
}
R
Output:
Enter an integer you want to check: 25
25 is odd.
YS
PROGRAM TO CHECK WHETHER A CHARACTER IS AN ALPHABET OR NOT USING IF ELSE
STATEMENT.
#include <stdio.h>
void main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
SB
if( (c>='a'&& c<='z') || (c>='A' && c<='Z'))
printf("%c is an alphabet.",c);
else
printf("%c is not an alphabet.",c);
TE
}
Output:
Enter a character: *
* is not an alphabet
#include <stdio.h>
void main()
{
char c;
N
printf("%c is a vowel.",c);
else
printf("%c is a consonant.",c);
return;
VT
}
Output:
Enter an alphabet: i
i is a vowel.
Dont watch the clock; do what it does. Keep going. -Sam Levenson
95
I
if ( year%400 == 0)
R
printf("%d is a leap year.", year);
else
printf("%d is not a leap year.", year);
}
YS
else
printf("%d is a leap year.", year );
}
else
printf("%d is not a leap year.", year);
}
Output:
Enter year: 1900
1900 is not a leap year.
SB
PROGRAM TO CHECK WHETHER A NUMBER IS POSITIVE OR NEGATIVE USING NESTED
IF ELSE STATEMENT.
#include <stdio.h>
TE
void main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num<=0)
O
{
if (num==0)
printf("You entered zero.");
else
N
}
Output:
Enter a number: -7
VT
-7 is negative
Strength does not come from physical capacity. It comes from an indomitable will. -Mahatma Gandhi
96
I
{
R
printf(" You got B grade");
}
else if(num>=40)
{
YS
printf(" You got C grade");
}
else if(num<40)
{
printf(" You Failed in this exam");
}
}
Output:
Enter your mark: 89
You got A grade
SB
PROGRAM TO FIND ALL ROOTS OF A QUADRATIC EQUATION USING ELSE IF LADDER.
#include <stdio.h>
TE
#include <math.h> // This is needed to use sqrt() function.
void main()
{
float a, b, c, determinant, r1,r2, real, imag;
printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
O
determinant=b*b-4*a*c;
if (determinant>0)
{
r1= (-b+sqrt(determinant))/(2*a);
N
r2= (-b-sqrt(determinant))/(2*a);
printf("Roots are: %.2f and %.2f",r1 , r2);
}
else if (determinant==0)
U
{
r1 = r2 = -b/(2*a);
printf("Roots are: %.2f and %.2f", r1, r2);
VT
}
else
{
real= -b/(2*a);
imag = sqrt(-determinant)/(2*a);
printf("Roots are: %.2f+%.2fi and %.2f-%.2fi",real,imag,real, imag);
}
}
Output:
Enter coefficients a, b and c: 2.3 4 5.6
Roots are: -0.87+1.30i and -0.87-1.30i
The primary cause of unhappiness is never the situation but your thoughts about it. -Eckhart Tolle
97
I
{
printf(" %d ", num);
R
}
}
YS
Output:
1 2 3 4 5 6 7 8 9 10
Output:
1 2 3 4 5 6 7 8 9 10
#include <stdio.h>
void main()
{
N
Output:
1 2 3 4 5 6 7 8 9 10
Patience, persistence and perspiration make an unbeatable combination for success. -Napoleon Hill
98
I
R
Output:
Sum = 1275
YS
#include <stdio.h>
void main()
{
int num, sum = 0;
num = 1
while(num <= 50)
{
}
sum = sum + num;
num++;
SB
printf("Sum = %4d\n", sum);
}
TE
Output:
Sum = 1275
{
int num, sum = 0;
num = 1
N
do
{
sum = sum + num;
U
num++;
}while(num <= 50);
Output:
Sum = 1275
Dont give up at half time. Concentrate on winning the second half. -Bear Bryant
99
I
}
R
printf("Sum=%d",sum);
}
Output:
Enter the value of n: 19
YS
Sum=190
void main()
{
int i,n;
U
float x,sum=0;
printf(" Enter the value of x and n:");
scanf("%f %d", &x,&n);
for(i=1;i<=n;++i)
VT
sum+=pow(x,i)/i;
printf(" Sum= %f ",sum);
}
Output:
Enter the value of x and n:
35
Sum= 85.349998
Only I can change my life. No one can do it for me. -Carol Burnett
100
a = x;
b = y;
I
R
while (b != 0)
{
t = b;
b = a % b;
YS
a = t;
}
gcd = a;
lcm = (x*y)/gcd;
}
SB
printf("Greatest common divisor of %d and %d = %d\n", x, y, gcd);
printf("Least common multiple of %d and %d = %d\n", x, y, lcm);
Output:
Greatest common divisor of 9 and 24 = 3
Least common multiple of 9 and 24 = 72
TE
n/=10; // n=n/10
++count;
}
printf("Number of digits: %d",count);
U
Output:
VT
I didn't fail the test, I just found 100 ways to do it wrong. -Benjamin Franklin
101
I
n/=10;
R
}
printf("Reversed Number = %d",reverse);
return;
}
YS
Output:
Enter an integer: 2345
Reversed Number = 5432
if(reverse==n)
printf("%d is a palindrome.",n);
else
printf("%d is not a palindrome.",n);
N
return;
}
Output:
Enter an integer: 12321
U
12321 is a palindrome.
VT
How people treat you is their karma; how you react is yours. -Wayne Dyer
102
I
{
R
for(count=1;count<=n;++count) // for loop terminates if count>n
{
factorial*=count; // factorial=factorial*count
}
YS
printf("Factorial = %lu",factorial);
}
}
Output:
Enter an integer: 10
Factorial = 3628800
t1=t2;
t2=display;
++count;
printf("%d+",display);
N
}
return;
}
Output:
U
Love is a fruit in season at all times, and within reach of every hand. -Mother Teresa
103
I
}
R
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
YS
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
}
}
count++;
i++;
SB
return;
}
Output:
TE
Enter the number of prime numbers required
5
First %d prime numbers are :
2 3 5 7 11
#include <stdio.h>
void main()
{
int n, i, flag=0;
N
if(n%i==0)
{
flag=1;
VT
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
}
Output:
Enter a positive integer: 29
29 is a prime number.
We all have ability. The difference is how we use it. -Stevie Wonder
104
I
x=y;
R
deno=3;
for(i=2;i<=n;i++)
{
val=1;
YS
for(j=1;j<=deno;j++)
val=val*j;
if((i%2)==1)
x=x+(pow(x,deno))/val;
else
}
deno+=2;
SB
x=x-(pow(x,deno))/val;
Our prime purpose in this life is to help others. And if you can't help them, at least don't hurt them. -Dalai Lama
105
I
{
R
case '+': printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-': printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
YS
case '*': printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/': printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default: printf("Error! operator is not correct");
break;
}
}
return;
Output:
SB
Enter operator either + or - or * or divide : -
Enter two operands: 3.4
8.4
TE
3.4 - 8.4 = -5.0
char grade ;
printf(“enter grade of a student: ”)
scanf(“%c”, &grade);
switch(grade)
N
{
case 'A' : printf( "Excellent\n" );
break;
case 'B' : printf( "Good\n" );
U
break;
case 'C' : printf( "OK\n" );
break;
VT
I wasn't afraid to fail. Something good always comes out of failure. -Anne Baxter
106
I
float total = 0.0, average;
R
printf ("Enter the value of N \n");
scanf("%d", &num);
printf("Enter %d numbers (-ve, +ve and zero) \n", num);
YS
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
// Summation starts
for (i = 0; i < num; i++)
{
if (array[i] < 0)
{
SB
negative_sum = negative_sum + array[i];
}
else if (array[i] > 0)
{
TE
positive_sum = positive_sum + array[i];
}
else if (array[i] == 0)
{
;
}
O
Output:
Enter the value of N
10
Enter 10 numbers (-ve, +ve and zero)
VT
Opportunities are usually disguised as hard work, so most people don't recognize them. -Ann Landers
107
I
printf("Enter Number %d: ",i+1);
R
scanf("%f",&arr[i]);
}
for(i=1;i<n;++i) // Loop to store largest number to arr[0]
{
YS
if(arr[0]<arr[i]) // Change < to > if you want to find smallest element
arr[0]=arr[i];
}
printf("Largest element = %.2f",arr[0]);
}
Output:
main()
{
int fib[100];
int i, n;
N
fib[0] = 0;
fib[1] = 1;
printf("enter n value: “);
scanf(“%d”. &n);
U
}
printf("fibo series is ….. \n”);
for(i = 0; i < n; i++)
{
printf(“%d ", fib[i]);
}
}
Output:
enter n value:7
fibo series is …..
0 1 1 2 3 5 8
To change a habit, make a conscious decision, then act out the new behavior. -Maxwell Maltz
108
I
{
R
scanf("%f",&a[i]);
}
printf("Enter the value of x:");
scanf("%f",&x);
YS
for(i=n;i>0;i--)
{
sum=(sum+a[i])*x;
}
sum=sum+a[0];
printf(" Value of the polynomial is =%f",sum);
}
Output:
Enter the degree of the polynomial:
4
SB
Enter the coefficients into the array:
3 2 1 1 2
Enter the value of x:
TE
2
Value of the polynomial is:72.000000
O
N
U
VT
Don't worry about failure; you only have to be right once. -Drew Houston
109
I
for (i = 0; i < num; i++)
R
{
scanf("%d", &array[i]);
}
printf("Input array is: \n");
YS
for (i = 0; i < num; i++)
{
printf("%d ", array[i]);
}
// Bubble sorting begins
for (i = 0; i < num; i++)
{ SB
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
TE
array[j + 1] = temp;
}
}
}
printf("Sorted array is :\n ");
for (i = 0; i < num; i++)
O
{
printf("%d ", array[i]);
}
}
N
Output:
Enter the value of num:
6
Enter the elements one by one:
U
23 45 67 89 12 34
Input array is:
23 45 67 89 12 34
VT
Be happy in the moment, that's enough. Each moment is all we need, not more. -Mother Teresa
110
I
{
R
scanf("%d", &array[i]);
}
YS
scanf("%d", &keynum);
// Linear search begins
for (i = 0; i < num ; i++)
{
if (keynum == array[i] )
{
}
}
found = 1;
break;
SB
if (found == 1)
printf("Element is present in the array\n");
else
TE
printf("Element is not present in the array\n");
}
Output:
Enter the value of num
5
Enter the elements one by one
O
23 90 56 15 58
Enter the element to be searched
56
Element is present in the array
N
U
VT
The most important thing is to enjoy your life - to be happy - it's all that matters. -Audrey Hepburn
111
I
scanf("%d", &array[i]);
R
printf("Input array elements \n");
for (i = 0; i < num; i++)
printf("%d ", array[i]);
YS
for (i = 0; i < num; i++) // Bubble sorting begins
for (j = 0; j < (num - i - 1); j++)
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
}
SB
array[j + 1] = temp;
low = mid + 1;
} while (keynum != array[mid] && low <= high);
if (keynum == array[mid])
U
}
Output:
Enter the value of num: 5
Enter the elements one by one
23 90 56 15 58
Input array elements
23 90 56 15 58
Sorted array is...
15 23 56 58 90
Enter the element to be searched: 58
SEARCH SUCCESSFUL
112
I
for (i = 0; i < m; i++)
R
{
for (j = 0; j < n; j++)
{
scanf("%d", &array1[i][j]);
YS
}
}
printf("Enter the elements of matrix array2 \n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
}
{
}
SB
scanf("%d", &array2[i][j]);
printf("%3d", arraysum[i][j]) ;
}
printf("\n");
VT
}
break;
case 2:
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
arraydiff[i][j] = array1[i][j] - array2[i][j];
}
}
113
I
R
}
Output:
Enter the order of the matrix array1 and array2
33
YS
Enter the elements of matrix array1
234
789
568
Enter the elements of matrix array2
333
346
847
SB
Enter your option: 1 for Addition and 2 for Subtraction
1
Sum matrix is
5 6 7
10 12 15
TE
13 10 15
O
N
U
VT
Only those who will risk going too far can possibly find out how far one can go. -T. S. Eliot
114
I
printf("Enter Matrix array1 \n");
R
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &arr[i][j]);
YS
printf("Enter Matrix array2 \n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &arr[i][j]);
printf("%3d", arr[i][j]);
}
printf("\n");
}
N
}
Output:
Enter the value of m and n
33
U
378
Enter matrix array2
569
853
291
The product matrix is
72103 57
27 43 18
87125 56
Set your goals high, and don't stop till you get there. -Bo Jackson
115
I
{
R
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
YS
}
printf("Transpose of matrix is \n");
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
}
}
printf("\n");
SB
printf(" %d", array[i][j]);
}
Output:
Enter the order of the matrix
TE
33
Enter the coefiicients of the matrix
379
275
634
Transpose of matrix is
O
326
773
954
N
U
VT
If you judge people, you have no time to love them. -Mother Teresa
116
I
void main()
{
R
int n, p;
printf(“enter a number”);
scanf(“%d”,&n);
YS
p= square(n);
printf(“The square of the number is %d”,p);
}
Output:
enter a number
4
The square of the number is 16 SB
PROGRAM TO FIND CUBE OF A NUMBER USING FUNCTION.
#include<stdio.h>
int cube()
{
TE
return n*n*n;
}
void main()
{
int n, p;
printf(“enter a number”);
scanf(“%d”,&n);
O
p=cube(n);
printf(“The cube of the number is %d”,p);
}
N
Output:
enter a number
4
U
You don't learn to walk by following rules. You learn by doing, and by falling over. -Richard Branson
117
void main()
{
I
int base, exp;
R
printf("Enter base number: ");
scanf("%d", &base);
printf("Enter power number(positive integer): ");
scanf("%d", &exp);
YS
printf("%d^%d = %d", base, exp, power(base, exp));
return;
}
Output:
Enter base number: 3
3^3 = 27
SB
Enter power number(positive integer): 3
int Fib(int n)
TE
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
O
return Fib(n-1)+Fib(n-2);
}
void main()
N
{
int n, i = 0, c;
printf("enter n value: ");
scanf("%d",&n);
U
Output:
enter n value: 7
Fibonacci series . . .
0112358
Belief in oneself is one of the most important bricks in building any successful venture. -Lydia M. Child
118
int fact(int n)
{
if(n!=1)
return n*fact(n-1);
}
void main()
{
I
int n;
R
printf("Enter an positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, fact(n));
return;
YS
}
Output:
Enter an positive integer: 6
Factorial of 6 = 720
void main()
{
int num;
N
}
Output:
Enter the number of disks : 3
VT
119
I
list[j] = temp;
R
}
}
void binary_search(int list[], int lo, int hi, int key)
{
YS
int mid;
if (lo > hi)
{
printf("Key not found\n");
return;
}
mid = (lo + hi) / 2;
if (list[mid] == key)
{
printf("Key found\n");
SB
}
else if (list[mid] > key)
{
TE
binary_search(list, lo, mid - 1, key);
}
else if (list[mid] < key)
{
binary_search(list, mid + 1, hi, key);
}
O
void main()
{
N
bubble_sort(list, size);
printf("\n\n");
printf("Enter key to search: ");
scanf("%d", &key);
binary_search(list, 0, size, key);
}
Output:
Enter size of a list: 10
Enter 10 numbers : 83 86 77 15 93 35 86 92 49 21
Enter key to search: 21
Key found
Take care of your body. It's the only place you have to live. -Jim Rohn
120
I
int roll;
float marks;
R
};
void main()
{
YS
struct student s;
printf("Enter information of students:\n\n");
printf("Enter name: ");
scanf("%s",s.name);
printf("Enter roll number: ");
scanf("%d",&s.roll);
printf("Enter marks: ");
scanf("%f",&s.marks); SB
printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return;
}
TE
Output:
Enter information of students:
Displaying Information
name: Adele
Roll: 21
N
Marks: 334.50
U
VT
121
void main()
I
{
R
complex n1,n2,temp;
printf("For 1st complex number \n");
printf("Enter real and imaginary respectively:\n");
scanf("%f%f",&n1.real,&n1.imag);
YS
printf("\nFor 2nd complex number \n");
printf("Enter real and imaginary respectively:\n");
scanf("%f%f",&n2.real,&n2.imag);
temp=add(n1,n2);
printf("Sum=%.1f+%.1fi",temp.real,temp.imag);
return;
} SB
complex add(complex n1,complex n2)
{
complex temp;
temp.real=n1.real+n2.real;
temp.imag=n1.imag+n2.imag;
TE
return(temp);
}
Output:
For 1st complex number
Enter real and imaginary respectively: 2.3
O
4.5
For 1st complex number
Enter real and imaginary respectively: 3.4
5
N
Sum=5.7+9.5i
U
VT
It's just a job. Grass grows, birds fly, waves pound the sand. I beat people up. -Muhammad Ali
122
void main()
{
I
struct student s[10];
R
int i;
printf("Enter information of students:\n");
for(i=0;i<10;++i)
{
YS
s[i].roll=i+1;
printf("\nFor roll number %d\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
}
printf("\n"); SB
printf("Displaying information of students:\n\n");
for(i=0;i<10;++i)
{
printf("\nInformation for roll number %d:\n",i+1);
printf("Name: ");
TE
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
}
return;
}
Output:
O
Enter marks: 98
Enter marks: 89
.
.
VT
People must learn to hate and if they can learn to hate, they can be taught to love. -Nelson Mandela
123
I
{
R
printf("For student %d\n Enter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
YS
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
}
Output:
Enter number of students: 2
For student 1
Enter name: sri
Enter marks: 75
For student 2
SB
……………….
PROGRAM TO OPEN A FILE AND WRITE DATA USING THE FUNCTION fprintf().
TE
void main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\program1.txt","w");
printf("Enter n: ");
O
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
}
N
Output:
Enter n: 1234
PROGRAM TO OPEN A FILE AND READ DATA USING THE FUNCTION fscanf()
U
void main()
{
int n;
VT
FILE *fptr;
fptr=fopen("C:\\program1.txt","r")
fscanf(fptr,"%d",&n);
printf("Value of n= %d",n);
fclose(fptr);
}
Output:
Value of n= 1234
Life doesn't run away from nobody. Life runs at people. -Joe Frazier
124