Professional Documents
Culture Documents
Introduction:
Lower level language
Higher level language
Object Oriented Language
Feature of C
Character set in C
Structure of a C program
Basic Input / output functions
Standard output function
printf() statement
Syntax
Format modifiers
putchar() statement
Escape sequence
C tokens
Constants
Integer constants
Floating-point constants
Character constants
String constants
Symbolic constants
Identifiers
Declaration of identifiers
Operators
Unary operator
Binary operator
Turnary operator
Chapter 2 Introduction to standard input function and operators
Introduction
Basic input function
Scanf()
Syntax
Use
getche()
Chapter 3 Operators in C
Unary operator
Binary operator
Unary Oerator
Increment operator
Decrement operator
Binary Operator
Assignment operator
Syntax:
Arithmetic operators
Addition Operator:
Subtraction Operator:
Multiplication Operator:
Division Operator:
Modulus operator
Relations operator
Logical Operator:
Turnary Operator:
Strings in C Language
Syntax
Pointers in C
File Handling In C
CHAPTER 1
INTRODUCTION TO C PROGRAMMING
Introduction:
In our day to day life, we communicate with different types of people. While we interact with them
we use specific language, English, Hindi, Gujarati and so on. A language is generally used to interact and
to convey our message to other people. Similarly, to interact with the with the computer system we need
some special language that helps us to interact with it.
Computer language has various categories that are mention below:
Lower level language
Binary language (Machine Language)
Assembly Language (uses mnemonics)
Higher level language
Prolog
Prolog Programming logic
Algol
Algorithmic Language
CP/M
Control Program for Microprocessor
LISP
List Programming
BCPL
Basic Combine Programming Language
BASIC
Beginners All Purpose Symbolic instruction code
COBOL
Common Business Oriented Language
Fortran
Formula Translator
Pascal
Object Oriented Language
C ++
Java
These languages are not powerful enough to process large amount of data or to hold large amount of
data. So, a language needs that can hold large amount and process it very efficiently. This reason lead to
develop our most popular language C.
Dennis Ritchie, a system programmer, originally develops C language under UNIX operating
system in 1970 at Bell Laboratory of USA. When DOS is invented, Dennis Ritchie and Keringon rewrite
this compiler for DOS base Operating system in 1972.
Compiler :
The problem of computers not understanding our language is solved by using software programs
called translators. This translator is known as compiler.
Feature of C:
1. Case sensitive language
2. Provide Modular Approach for programming
3. Portable Language
Structure of C program :
A C program is set of blocks called functions. A function is made up of one or more statements
used for performing a predefined task. A complete C program structure is given below :
Documentation
Symbolic constant definition
File include section
Global variable declaration
main( )
{
Declaration
Executable Statements
}
Function 1
Function 2
Function N
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
1
Documentation Section :
This section is an optional section. As the name indicates it is used for the purpose of documentation. It is enclosed within /* and */. Whenever the text is enclosed between /* and */, it is considered as a
comment in C. Comments are not processed by C compiler and are left as it is. This section is normally
used to tell about the purpose of program, author, date of creation etc. Comments in C can be added anywhere in the program.
Symbolic Constant Definition :
There is a symbolic constant like PI. To use such symbolic constant in our program we need to use #define as a prefix to it. Here #define is known as preprocessor directive. It instructs the compiler to replace
all occurrences of symbolic constant with the values specified against it. Normally, symbolic constant are
defined using capital letters.
Ex. #define PI 3.14
File include Section :
C provides inbuilt or library functions. Some examples are pow(), sqrt(), etc. These functions have a predefined purpose. To use them we have to include files that hold information about these functions. These
files are known as header files. The extension of header file is .h. WE use the syntax #include <filename.h> to include header file in our program.
Global variable declaration Section :
C variables are governed by scope. A scope of variable is decided by using opening and closing curly
braces { }. This variable can not be used outside the scope. At times we need to use a variable in all the
functions, such a variable is known as global variable. This variable is defined before defining all the functions.
Main Function :
All C program contain one function with the name main( ). This is the function from where the execution of
any C program starts. The control is first transferred to this function and from here rest of the operations
are carried out. main() is a user-define function.
User defined function :
C provides us a facility of breaking a single program into set of small pieces. These pieces are known as
functions. In this section we define all the additional functions used in our program. Functions have been
discussed in detail later on.
Character set in C:
Character set refers to the set of character used to provide instruction or command to the computer. In include alphabets, numbers, and special symbols.
Uppercase letters
Lowercase letters
Digits
Symbols
A Z,
az
09
*, /,<,>,#,(,),{,} etc.
C tokens
C tokens are the smallest unit in C language. C tokens are given as follow
1. Constants
Integer constants
Floating point constants
Character constants
String constants
Symbolic constants
2. Keywords
3. Identifiers
4. Operators
5. Special symbols
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
2
1) Constants
Integer Constant:
1. Integer constant must have at least one digit.
2. They must not have a decimal point.
3. They can be positive or negative.
4. If there is no any sign to integer it is assume to be positive.
5. No comma or blank spaces are allowed within the integer constant. e.g. 426, +756,-588 etc.
Real Constant:
1. These are generally called as floating point constant. They can be written two forms. That is,
fractional form & exponential form.
2. Real constant can be positive or negative.
3. They must have decimal point.
4. Default sign is positive.
5. No comma or blank spaces are allowed in the real number. e.g. 22.45, -85.23, 11.20, +3.211e-4, 5.6e4 etc.
Character Constants:
There are two types of character constants.
Single character constant :
1. The character constant is a single alphabet or a single digit or a single special symbol enclosed
within the single quotation marks.
2. Maximum length of a character is one character. e.g. f, h, =, 8
etc.
String constants:
String constant refers to the constants values, which remains constants during program execution
enclosed within the double quotes. e.g. India, LCC Infotech Ltd. etc are String constants.
Symbolic constants:
We often use certain unique constants in a program. These constants appears in number of places in the program. One example of such constant is 3.14159 this value represent value of the mathematical constant pi. This types of constant can be defined with the help of #define clause.
example:
#define pi 3.14159
2) Keywords
Keywords have special meaning. Keyword is the word whos meaning as already being given to the
C compiler. The keywords can not be given as variable name in C. These are also called as reserve
words. The C supports 32 different keywords listed below :
Auto
break
case
char
const
continue
default
do
Double
else
enum
extern
float
far
for
goto
If
int
long
near
register
return
short
signed
Static
struct
switch
typedef
union
unsigned
void
while
3) Identifiers
It refers to the name of function, a variable, or an structure. This is the user defined name consist
of a sequence of character or a digits with a letter as a first character, or we can write the definition as
follow
It is a symbolic location in memory in which user can store his data. It may store different types of
values according defined in memory.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
3
Meaning
New line
Tab
Backspace
Vertical tab
Audible Alert (Bell)
Carriage return
Farm Feed
Backslash
Single Quote
Double Quote
Separators
These are the symbols which are used to indicate where groups of codes are divided
and arranged. They are basically used to define the shape and function of the program code. The
most commonly used separator is semicolon. All these separators are listed below:
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
5
Separator
()
Name
Parenthesis
Purpose
Used to contain lists of parameters in function definition and call.
Also used for defining precedence in expressions, containing expressions in control statements, and surrounding cast types.
Used to contain the values of automatically initialized arrays. Also
used to define a block of code for classes, functions, and local
scopes.
{}
Curly
Braces
[]
Square
brackets
<>
Angle
Brackets
Semicolon
Comma
Double
quotes
Single
quotes
Sample program :
#include <stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(Programming in C is easy.\n);
printf(\tAnd so is Pascal.);
getch();
}
The output of above program is :
Programming in C is easy.
And so is Pascal.
Exercise for printf function:
1. Write a program to print different five statement of your favorite picnic place.
2. Write a program to print at least five statement for cricket game
3. Write a program to print your bio-data on screen
4. Write a program to print at least five statement about you and your likes and dislikes
5. Write a program to display five statements about legendary personality of your choice.
DATA TYPES
Type of value that can be assigned to an identifier is known as data types. C language uses set of
keywords to relate a data with its value. These keywords identify two things, the type of value that can
be stored in an identifier and the memory space required by an identifier. Each data type is allocated a
fixed memory space in C. It is denoted by bytes.
1 byte = 8 bits
The three basic data types are integer, float and character.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
6
INTEGER
These are whole numbers, both positive and negative. Unsigned integers (positive values only)are supported. In addition, there are short and long integers. The keyword used to define integers is,
int
An example of an integer value is 32. An example of declaring an integer variable called sum is,
int sum
sum = 20
DATA TYPE
DESCRIPTION
int
short int
long int
To store a positive
or negative whole
number.
unsigned int
To store a positive
whole number
RANGE
BYTE REQUIRED
2
-32768 to
+32767
-2147483648 to
+2147483647
0 to
65535
0 to
4294967295
EXAMPLE
int amount;
short int a;
long int bal;
FLOAT
These are numbers which contain fractional parts, both positive and negative. The keyword
used to define float variables is,
float
An example of a float value is 34.12. An example of declaring a float variable called money is,
float money
money = 0.12
DATA TYPE
DESCRIPTION
float
double
To store a positive
or negative real
number.
RANGE
+/- 3.4e-38 to +/3.4e +38
+/-1.7e-308 to +/1.7e +308
long double
BYTE REQUIRED
4
EXAMPLE
float amount;
double total;
10
CHARACTER
These are single characters. The keyword used to define character variables is,
char
An example of a character value is the letter A. An example of declaring a character variable called
letter is,
char letter
letter = 'A'
Note the assignment of the character A to the variable letter is done by enclosing the value in single
quotes. Remember the golden rule: Single character Use single quotes.
DATA TYPE
char
unsigned char
DESCRIPTION
To store a character.
RANGE
-128 to +127
BYTE REQUIRED
1
EXAMPLE
char gender;
0 to 255
In order to print the values of the variables printf can also be used as:
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
7
%e
%E
%f
%i
%s
%u
%ld
int age;
clrscr();
age=25;
printf(Age is initialize by %d, age);
}
Standard input function
scanf
This formatted input function statement defined in stdio.h file and used to accept the values of variables from the keyboard.
Syntax:
scanf(<format string>, <variables-list>);
Here, the format string will contain the format specifiers or format codes
to accept the values of variables in the sequence of format specifiers. For example:
int var1;
float var2;
scanf(%d%f, &var1, &var2);
This statement will read an integer number and a float number from keyboard and store
these values in var1 and var2 respectively. The scanf allows all the above format specifiers to use
for inputting the values.
Sample C program 1.5
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,ans;
clrscr();
printf("Enter two numbers:");
scanf("%d",&a);
scanf("%d",&b);
ans = a * b;
printf("%d * %d = %d",a,b,ans);
getch();
}
Output :
Enter two numbers: 10
20
10 * 20 = 200
A Sample program 1.6
// to calculate area of circle.
#include <stdio.h>
#include <conio.h>
#define pi 3.14159
void main()
{
float r=2.5, a=0;
clrscr();
printf(\n\t Area of a Circle is );
a=pi*r*r ;
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
9
printf(%d,a);
getch();
}
Summary of major points:
1 program execution begins at main()
2 keywords are written in lowercase
3 statements are terminated with a semicolon
4 text strings are enclosed in double quotes
5
6
7
8
C is case sensitive, use lowercase and try not to capitalize variable names
\n means position the cursor on the beginning of the next line
printf() can be used to display text to the screen
The curly braces {} define the beginning and end of a program block.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
10
CHAPTER 2
FORMATTED INPUT OUTPUT FUNCTIONS
Computer basically has three parts namely, input, process and output. Similarly, any program can be
thought of as having three parts, input, process and output. Input means to read data from some input
devices. Output means to write processed data to the output device. I/O in C is done through some standard library functions.
Input functions : getchar( ), getch( ), getche( ), getc( ), gets( ), scanf( )
Output functions : putchar( ), putc( ), puts( ), printf( )
getchar( ):
To read a single character from user / keyboard, a function called getchar( ) is used. It does not
assign value to variable till we press an enter key from keyboard. It echo the character on screen.
Syntax:
Variable_name = getchar( );
Example:
char choice;
choice = getchar( );
Sample C Program 2.1
#include <stdio.h>
#include <conio.h>
void main()
{
char ch;
clrscr();
printf(Enter any character );
ch = getchar();
printf(\n\t Entered character is %c, ch);
}
getche( ):
getche( ) function is also used to input a single character. It assign character to a variable, without
pressing enter key from keyboard. It also echo character on screen. The getche( ) function is similar to
getchar( ) except that the function getche( ) is included in the conio.h header file.
syntax:
Variable_name = getche( );
Example:
char choice;
choice = getche( );
Sample C Program 2.2
#include <stdio.h>
#include <conio.h>
void main()
{
char ch;
clrscr();
printf(Enter any character );
ch = getche();
printf(\n\t Entered character is %c, ch);
}
getch( ) :
It is also a function which accepts a single character. it assigns value to variable as we type in
form keyboard. It accepts a character form user but does not echo it on screen means character will not
be visible to the screen.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
11
syntax:
Variable_name = getch( );
Example:
char choice;
choice = getch( );
Sample C Program 2.3
A program to accept a character and print it.
#include <stdio.h>
#include <conio.h>
void main()
{
char ch;
clrscr();
printf(Enter any character );
ch = getch();
printf(\n\t Entered character is %c, ch);
}
gets( ):
We call a group of character as a string. A string in C is enclosed within double quotation. It always ends with a null character (\0). We can use a sequence of getchar( ) functions to accept a string.
Alternatively we use gets( ) function to read string. It is a library function, stored in stdio.h header file.
syntax:
gets( Variable_name );
Example:
char name[50];
gets( name );
Sample C program 2.4
#include <stdio.h>
#include <conio.h>
void main()
{
char name[10];
clrscr();
printf(Enter your Name please );
gets(name);
printf(\n\t Name entered is %s, name);
getch();
}
Sample program 2.5
// A program to accept name, address, city form user and print it.
#include <stdio.h>
#include <conio.h>
void main()
{
char name[10], addr[15], city]15];
clrscr();
printf(Enter Name: );
gets(name);
flushall();
printf(Enter Address: );
gets(addr);
flushall();
printf (Enter City: );
gets(city);
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
12
flushall();
printf(\n\t Name %s: , name);
printf(\n\t Address %s: , addr);
printf(\n\t: city %s ,city);
getch();
}
getc( ) and putc( ) functions are discussed in detail later on.
putchar( ) :
putchar( ) function prints a single character on a screen. It take a variable of type character as an
argument an displayed content of it.
syntax:
putchar( variable_name );
example:
char ch=A;
putchar(ch);
Sample C program 2.6
#include <stdio.h>
#include <conio.h>
void main()
{
char ch=x;
clrscr();
printf(Character is );
putchar(ch);
putchar(\n);
putchar(y);
getch();
}
Output :
Character is x
y
puts( ) statement:
puts( ) statement is used to display string type data. It take a string variable as an argument, or it
also take a constant string as argument.
Syntax:
puts(variable_name);
Example:
puts(India);
Sample C program 2.7
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
puts(Welcome to C program);
}
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
13
to accept your name, address, city and phone and print it.
to accept sales man name and his age and print it on screen.
to accept employee name, his department, and his basic salary and print it.
to accept student name, roll no, and marks of five different subjects and print it.
to accept item name, quantity and rate and print it on screen.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
14
CHAPTER 3
OPERATORS IN C
Operators are the special symbol use to perform special operation (for example, arithmetic
& logical) on operands. Operands are the variables, constants or expressions on which operators
perform operation.An operator is the special capable of performing any type of arithmetic operation.
They are used in program to manipulate data and variable. They usually form a part of mathematical of
logical expression. C has rich set of operators.
The operators in C can be categorized into eight types :
1. Arithmetic operator
2. Assignment operator
3. Relational operator
4. Increment and decrement operator
5. conditional operator
6. logical operator
7. bitwise operator
8. special operator
1 ) Arithmetic operators
Arithmetic operators used to perform any type of arithmetic operation such as addition, subtraction, multiplication and division etc. Arithmetic operator has further following type:
1. Addition operator
(+)
2. Subtraction operator
()
3. Multiplication operator ( * )
4. Division Operator
(/)
5. Modulus Operator
(%)
Addition Operator:
This operator is used to perform addition on any numerical operand.
e.g. c = a + b, c = c + 1 etc.
Subtraction Operator:
This operator is used to perform subtraction on any numerical operand.
e.g. c= a b, c = c 1
Multiplication Operator:
This operator is used to perform multiplication on any numerical operand.
e.g.
c = a * b, c = c * 2
Division Operator:
This operator is used to perform division on any numerical operand.
e.g. c = a / b, c = c / 3
Modulus Operator:
This operator is used to perform modulus operation on any numerical operand. e.g. c = a % 10, c
= a %10.
2) Assignment operator
An assignment operator is used to assign value to variable. Assignment always performed right to
left.
Syntax:
Variable = value
Example:
Age = 25;
3) Relational Operators:
Relational operators are used to perform to or more values to set relation between them whether
one operand is greater, equal, less or not.
Relational operand has further more type:
1. Greater then operator
(>)
2. Less then operator
(<)
3. Greater then or equal to operator
( >=)
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
15
(<=)
(!=)
8) Special Operators:
C provides special operators like sizeof( ), ,, ., &, *. The sizeof( ) operator is a special operator used
to return size of bytes required to store an entity. For example val = sizeof(int) will give value 2 to val.
This is because data type int uses 2 bytes in memory space.
Sample Program 3.1: addition of two integer numbers.
#include <stdio.h>
#include <conio.h>
void main()
{
int N1, N2, sum;
clrscr();
printf(Input value to N1: );
scanf(%d,&N1);
printf(Input value to N2: );
scanf(%d,&N2);
sum = N1 + N2;
printf(\n\tSum of %d + %d = %d, N1,N2,sum);
getch();
}
Similarly, we can perform subtraction, multiplication etc.
Sample Program 3.2 multiplication of two numbers.
#include <stdio.h>
#include <conio.h>
void main()
{
float a, b, ans;
clrscr();
printf(Enter two numbers : );
scanf(%f%f,&a,&b);
ans = a * b;
printf(\n\t Multiplication of %f * %f = %f, a,b,ans);
getch();
}
Sample Program 3.3 : Division of two numbers
#include <stdio.h>
#include <conio.h>
void main()
{
int N1, N2, N3;
clrscr();
printf(Input value to N1: );
scanf(%d,&N1);
printf(Input value to N2: );
scanf(%d,&N2);
N3 = N1 / N2;
printf(\n\t Division of %d / %d = %d, N1,N2,N3);
getch();
}
Output :
Input value to N1 : 7
Input value to N2 : 3
Division of 10/3 = 2
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
17
Here, the variable n1 and n2 are type of integer so value of n3 will bi 2 in integer not 2.33333. It
can not be in float.
A Sample program 3.4
// A program to accept number and find its square.
#include <stdio.h>
#include <conio.h>
#include<math.h>
void main()
{
double n, p;
clrscr();
printff(Enter any number for which you want to find square: );
scanf(%lf,&n);
p=pow(n,2);
printf(\n\t Square of %lf is %lf, n, p);
getch();
}
A Sample program 3.5
// A program to accept number and find its square root.
#include <stdio.h>
#include <conio.h>
#include<math.h>
void main()
{
float n, s;
clrscr();
printff(Enter any number for which you want to find square root: );
scanf(%f,&n);
s=sqrt(n);
printf(\n\t Square root of %f is %f, n, s);
getch();
}
A sample program 3.6
// A program to enter currency in Indian rupees and convert it into dollars, and pound.
#include <stdio.h>
#include <conio.h>
void main()
{
float rs, pnd,dlr;
clrscr();
printf(Enter Indian Rupees: );
scanf(%f,&rs);
dlr=rs/48.5;
printf(\n\t Rupees %f equals dollars %f, rs, dlr);
pnd=rs/79;
printf(\n\t Rupees %f equals pound %f, rs, pnd);
getch();
}
A sample program 3.7
// A program to enter Distance in km and convert it into meter, feet and inches
#include <stdio.h>
#include <conio.h>
void main()
{
float d, m, f, i;
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
18
clrscr();
printf(Enter Distance in KM: );
scanf(%f, &d);
m=d*1000;
printf(\n\t Distance in Meter is %f , m);
f=m*3.33;
printf(\n\t Distance in feet is %f, f);
i=f*12;
printf(\n\t Distance in inches is %f, i);
getch();
}
A sample program: 3.8
// A program to convert temperature entered in Celsius to its equivalent Fahrenheit degree.
#include <stdio.h>
#include <conio.h>
void main()
{
float c, f;
clrscr();
printf(Enter temperature in Celsius: );
scanf(%d, &c);
f=9.0/5.0 * c + 32.0;
printf(\n\t Temperature in Fahrenheit is %f, f);
getch();
}
A sample program 3.9
// A program to convert temperature entered in Fahrenheit degree and convert to its equivalent
Celsius degree.
#include <stdio.h>
#include <conio.h>
void main()
{
float c=0, f=0;
clrscr();
printf(Enter temperature in Fahrenheit: );
scanf(%d, &f);
c=(5.0/9.0) * (f 32);
printf(\n\t Temperature in Celsius is %f, c);
getch();
}
A Sample program 3.10
// Program to find area of a circle and circumference of a circle.
#include <stdio.h>
#include <conio.h>
#define PI 3.14
void main()
{
float r, a, c;
clrscr();
printf(Enter Radius of a Circle : );
scanf(%d, &r);
a=PI * r * r ;
c= 2 * PI * r ;
printf(\n\t Area of a circle is %f, a);
printf(\n\t Circumference of a circle is %f, c);
getch();
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
19
}
A Sample program 3.11
// A program to enter salary and sale amount of a salesman and calculate his commission @ 12%
of sales amount and display total salary;
#include <stdio.h>
#include <conio.h>
void main()
{
float sal,amt,com,total;
clrscr();
printf(Enter Salary of a Salesman: );
scnaf(%d, &sal);
printf(Enter sales amount of a Salesman: );
scnaf(%d, &amt);
com = amt * 0.12 ;
total = sal + com;
printf(\n\t Salary of a salesman: %f,sal);
printf(\n\t Commission %f, com);
printf(\n\t Total salary: %f, total);
getch();
}
A Sample program 3.12
//Example of increment - decrement operator.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20,c;
c = a++;
printf("a = %d b = %d c = %d",a,b,c);
- - b;
printf("\nb = %d",b);
c = ++a + b--;
printf("\n a = %d b = %d c = %d",a,b,c);
getch();
}
Output :
a = 11 b = 20 c = 10
b = 19
a = 12 b = 18 c = 31
A Sample program 3.13
//Example of conditional opertor.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=70,b=50,max;
clrscr();
max = (a>b) ? a : b;
printf("Maximum number is %d",max);
getch();
}
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
20
Exercise:
1. Accept marks of five different subjects from the user calculate total and average and display it.
2. Accept a character and convert it to uppercase character and vise-versa.
3. Accept principle amount, rate of interest and number of years from user and find simple interest.
4. Accept simple interest, rate of interest and number of year from the user and find principle
amount.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
21
CHAPTER 4
INTRODUCTIONS TO CONTROL STATEMENTS
Introduction:
So far we learn about data types, basic input and output function etc. now we will learn about
branching control to some other process. Before we learn about it. We will look at some programming
construct, i.e. sequential programming, selective programming, and iterative programming. Sequential
programming is that in which program starts from top and ends with last line without branching control to
other process, and Selective programming is that in which control can be branch to some other process
This is done using control statements in C Language. A flow control statement is used to control flow of
program execution depending upon given condition. C language has two types of control statements.
1.
if statement
* Simple if statement
* if else statement
* nested if
* else if ladder
2..
switch statement
Simple if Statement:
if statement is a powerful decision making statement and is used to test one or more than one
value of condition at a time. It is also used to control the flow of execution of statements. It is basically a
two way decision statement and is used in conjunction with an expression. It is used when we have more
than one option to select the process and depending on condition we want to read or execute the
process.
Syntax:
if(condition)
{
action;
}
Statement x;
Here condition is given criteria or test condition that should be a logical expression, and action means
statements of process to be performed when given criteria satisfied. The statement block may be a single
statement, or a group of statement. If the test condition is true, the statement block will be executed; otherwise statement block will be skipped and execution will be jump to the statement-x. Remember, when
condition is true both statement block and statement-x are executed in sequence.
Sample Program 4.1
// Write a program to check whether entered value is more than 100 or not.
#include <stdio.h>
#include <conio.h>
void main()
{
int n;
clrscr()
printf(Enter any number : );
scanf(%d,&n);
if(n > 100)
{
printf(\n\t Value %d is more than 100,n);
}
}
in above example if given value is less then 100 then it wouldnt display any thing on the screen, because
we could not specified alternate option for the if statement.
if .. else Statement:
To perform an operation in both the case means if given condition is true or given condition is false, the
first test determines whether condition is true or not. if condition is not true then it executes statement
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
22
block immediately after if statement otherwise it executes statement block immediately after else statement. we could write the previous program as follows using if .. else statement
Syntax:
if(condition)
{
action;
}
else
{
action;
}
in above example if given value is less then 100 then it displays message on the screen, because we
specified alternate option for the if statement means if given condition is true then it executes statements
after the if statement, if given condition is false then also it execute the statements after else statement.
Note:
1. Statements inside the ifs curly braces are called as if block and statements for elses curly
braces are called as else block.
2. There is no necessity to have an else for if but, each else must match an if statement else
there will be a compiler error. The error will be
Misplaced else.
3. If there is only one statement inside if as well as else block, we can eliminate the curly braces.
Sample Program 4.2
/* program to display greater number between two numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter two numbers :");
scanf("%d%d",&a,&b);
if(a>b)
printf("greater no is a %d", a);
else
printf("greater no is b %d", b);
getch();
}
Sample Program 4.3
/* program to check whether entered number is even or odd */
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter a integer number \t :");
scanf("%d",&a);
if(a%2 == 0)
printf("%d is Even number.",a);
else
printf("%d is Odd number.",a);
getch();
}
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
23
Nested if else
If we write an entire if - else construct within the body of the if statement or the body of
an else statement. This is called nesting of if- else.
Syntax:
if(condition)
{
//statements1
if (condition)
{
// statements2
}
else
{
// statements3
}
}
else
// statement 4
Here, the inner condition executed only when the outer condition of if is true. This hierarchy of nesting
of if can be extended in deep with any number of if-else statements.
Sample Program 4.4
/* program to find maximum number between three numbers */
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max;
clrscr();
printf("Enter 3 numbers \t");
scanf("%d%d%d",&a,&b,&c);
if ( a > b )
{
if ( a > c )
max=a;
else
max = c;
}
else
{
if ( b > c)
max=b;
else
max=c;
}
printf("Max = %d ",max);
getch();
}
if .. else if statement (else if ladder) :
There is another way of putting ifs together when multipath decision are involved. A multipath
decision is a chain of ifs in which associated with each else is an if. It makes following general form of if ..
else if structure:
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
24
Syntax:
if(condition)
{
action;
}
else if(condition)
{
action;
}
else
{
action;
}
It required when we have more then one conditional statements. It is applied when we want to apply
grades to students or to decide who is eligible for bonus in company etc.
A Sample program 4.5
//program to display grade of the student based on marks obtained.
#include<stdio.h>
#include<conio.h>
void main()
{
float marks;
clrscr();
printf("Enter marks :");
scanf("%f",&marks);
if(marks>80)
{
printf("Grade is A.");
}
else if(marks>70)
{
printf("Grade is B.");
}
else if(marks>50)
{
printf("Grade is C.");
}
else if(marks>35)
{
printf("Grade is D.");
}
else
{
printf("Student is Fail.");
}
getch();
}
Example:
1. Write a program to enter sales amount of a salesman and salary of a salesman and calculate is
commission
Rates of commission are:
Sales amount > 15000 rate of commission is 15%
Sales amount between 8000 and 15000 rate of commission is 12%
Sales amount between 5000 and 8000 rate of commission is 10%
Sales amount less then 5000 rate of commission is 8%
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
25
2.
3. Write a program to check given year is leap year or not.
4. Write a program to check entered number is positive, negative or zero.
5. Write a program to check whether the person is eligible for voting or not.
Switch case statement :
C language has a built-in multiway decision statement known as switch statement. It is another
type of control statement used to test limited scope of condition like to check constant expression like vowel or operator etc. we can not check large range of data in switch statement. It tests the value of variable
(or expression) against a list of case values and when a match is found, a block of statements associated
with that case is executed. The general form of switch statement is shown below:
The expression is an integer expression or characters,. value-1, value-2 .. are constants or
constant expression ( evaluable to an integer constants, and are known as case labels. Each of these
values should be unique within a switch statement, block-1, block-2 . Are statement blocks. Note that
case labels are ends with colon (:)
Syntax:
switch(variable or expression)
{
case constexpr1:
action1;
break;
case constexpr2:
action2;
break;
case constexprN:
actionN;
break;
default:
action;
}
Sample Program 4.5
//display word according to given number.
#include<stdio.h>
#include<conio.h>
void main()
{
int choice;
clrscr();
printf("Enter any number between 1 to 5 :");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("One");
break;
case 2:
printf("Two");
break;
case 3:
printf("Three");
break;
case 4:
printf("Four");
break;
case 5:
printf("Five");
default :
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
26
printf("Invalid choice.");
}
getch();
}
A Sample program 4.6
// calculator
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,ans,choice;
clrscr();
printf("Enter two numbers :");
scanf("%d%d",&a,&b);
printf("\n Calculator");
printf("\n1. Addition");
printf("\n2. Subtraction");
printf("\n3. Multiply");
printf("\n4. Division");
printf("\n\n Enter your choice 1 2 3 4 \t");
scanf("%d",&choice);
switch(choice)
{
case 1:
ans = a + b;
printf("Addition = %d",ans);
break;
case 2:
ans = a - b;
printf("Subtraction = %d",ans);
break;
case 3:
ans = a * b;
printf("Multiplication = %d",ans);
break;
case 4:
ans = a / b;
printf("Division = %d",ans);
break;
default :
printf("Invalid choice.");
}
getch();
}
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
27
CHAPTER 5
LOOPS IN C
Many times it is necessary to execute several statements repetitively for certain number of
times. In such cases, we can use looping statements of C programming language. The statements are
executed until a condition given is satisfied. Depending upon the position of the condition in the loop,
the loop control structures are classified as the entry-controlled loop and exit-controlled loop. They are
also called as pre-test and post-test loops respectively.
If I ask you to print your name 5 times what you do? Naturally, you will write five printf statements
right?. Because you dont know about the loop process. A loop is a process of executing statements within the loop till given condition is true. It reduce redundancy of code of program. C language has basically
three types of loops
1.
while loop
2.
do .. while loop
3.
for loop
while loop
The simplest of all the lopping structure in c is the while statement. A while loop is generally
known as entry-conditional loop, then the body of the loop is executed. It is also known as pre tested loop
because it test the condition before it enters in loop and executes statements within the body of the loops.
Characteristic of while loop
1.
Pre tested loop
2.
It executes statement within the body of the loop till given condition is true.
3.
If condition in the beginning is false entire loop skips and statement executes immediately
after the body of the loop.
Syntax:
while(condition)
{
statements;
}
Here, the condition is evaluated first, if it is true then loop statements or body of the loop is executed. After this the program control will transfer to condition again to check whether it is true or false. If
true, again loop body is executed. This process will be continued until the condition becomes false.
When is becomes false, the statements after the loop are executed.
Sample Program 5.1:
#include <stdio.h>
#include <conio.h>
void main()
{
int count=1;
clrscr();
while(count <= 5)
{
printf(\n\tCount = %d,count);
count++;
}
getch();
}
above programs prints following output.
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
28
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
29
Syntax:
do
{
statements;
} while(condition);
Characteristic of do .. while loop
1.
It is post tested loop
2.
It executes the statements within the body of loop till given condition is false
3.
if condition in the beginning is false it executes statements within the body of loop at least
once.
Sample Program 5.4
#include <stdio.h>
#include <conio.h>
void main()
{
int count;
clrscr();
do
{
printf(\n\tcount = %d,count);
count++;
} while(count <= 5);
getch();
}
above programs prints following output.
Output
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
Sample Program 5.5
// to print welcome till user wants.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
do
{
printf("\n\tWelcome");
printf("\nDo you wnat to continue ? (y - yes n - No) :");
flushall();
ch = getchar();
}
while(ch == 'y' || ch == 'Y');
printf("\nThanks for visit...");
getch();
}
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
30
while loop
do-while loop
Syntax:
do
{
//loop body
}while(condition);
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
31
as post-test loop.
Exercise:
1. Generate the following Fibonacci series using while loop till n number. Accept n from user. 0 1
1
2
3
5
8
13 n
2. Write a program to find sum of all even numbers from n to m. Accept values of variables n and m from
keyboard.
3. Write a program to print numbers between 1 to n and its square.
4. Write a program to input a number and display its all digit in reverse order.
For Loop
The for loop is another entry-controlled loop that provides more concise loop control structure. It
is also an example of pre tested loop. We can use this loop only when we know the number of iteration.
Loop contains initialization, test condition, and increment together.
Syntax:
for(initialization; condition; increment/decrement)
{
statements;
}
The execution of for loop statement takes as follows:
1. Initialization of loop control variables is done first using assignment operators such as:
i = 1 or count = 0 etc. Remember this part is executed only once.
2. The condition given afterwards is checked then. If this condition is true, the statements inside the
loop are executed. Else program control will get transferred nest statement after the loop. The condition can be combination of relational as well as logical operators such as:
count < 10
3. When the body of the loop is executed, program control will get transferred back to for
statement for executing the third statement that is, increment/decrement. In this part the loop control variables value is incremented or decremented. Then program controls the condition again to
check whether it is true or not. If true, the loop body executed again. And the process is continued
again until the condition evaluates to false.
Characteristic of for loop
1
Pre tested loop
2
It executes statement within the body of the loop till given condition is true.
3
If condition in the beginning is false entire loop skips and statement executes immediately
after the body of the loop.
Sample Program 5.8
#include <stdio.h>
#include <conio.h>
void main()
{
int count;
clrscr();
for(count=1; count <= 5; count++)
{
printf(\nCount = %d,count);
}
getch();
}
above programs prints following output.
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
32
}
printf("\n");
}
getch();
}
A sample program 5.12
A program to print x^y and 1/x^y using for loop
#include <stdio.h>
#include <conio.h>
void main()
{
long
pass=0;
int
n=0;
double q=0;
clrscr()
printf(-----------------------------------------------------------);
printf( 2 to power n
n
2 to power n);
printf(-----------------------------------------------------------);
p = 1;
for(n=0; n<21; ++n)
{
if(n == 0)
p = 1;
else
p = p * 2;
q = 1.0 /(double)p;
printf(%10 %10d %20.12lf\n,p,n,q);
}
printf(-----------------------------------------------------------);
getch();
}
Exercise using for loop:
1. Write a program to print Square and cube of all natural number between 1 and 100
2. Write a program to print fibbonacy series of first 10 natural number.
3. Write a program to print 1, 2, 2, 4, 8, 32, 256 etc. series.
4. Write a program to print a multiplication table of a given number.
5. Write a program to print a reverse number.
6. Calculate sum of an individual digit of a given number.
7. write programs to display following output :
1
321
111
*
22
21
333
* *
333
1
555
* * *
Nested Loops:
When a loop is used within another loop it is said to be a nested loop. We can combine any loop
with any other loop. Any loop can be keep together for process.
Nested loops can be used for:
To read or to write double dimension array
To sort a single dimension array
To print different types of patterns on screen
Syntax:
while(condition)
{
while(condition)
{
statements;
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
34
}
}
similarly, you can nest for loop and do while loop.
Sample Program 5.13
Create following pattern on screen
*
**
***
****
#include <stdio.h>
#include <conio.h>
void main()
{
int i=1,j;
clrscr();
while(i<=10)
{
j=1;
while(j<=i)
{
printf( *);
j++;
}
printf(\n);
i++;
}
getch();
}
modify above program using for and do while loop.
Exercise of nested Loop:
Write program for the following pattern
1)
2)
A
A
AB
BC
ABC
DEF
ABCD
GHIJ
4) Write a program to print all prim number between 1 and 100.
5) Write a program to print multiplication table of 1 to 10.
3)
1
12
123
1234
scanf(%lf, &number);
if(number == 9999)
break;
if(number < 0)
{
printf(\n\t Number is negative);
negative++;
continue;
}
sqroot = sqrt(number);
printf(\n\t Number
= %lf, sqroot);
count ++
}
printf(\n\t Number of items done = %d\n, count);
printf(\n\t Negative intes
= %d\n, negative);
getch();
}
Sample Program 5.15
A program to print following pattern on screen
1
22
333
4444
55555
#include <stdio.h>
#include <conio.h>
void main()
{
int i,J;
clrscr();
for(i=1; i<5; i++)
{
for(J=0;J<=i;J++)
printf(%d,i);
printf(\n);
}
getch();
}
The break statement
As we have already seen, the break statement is used to exit out of the switch statement. It is having another useful application in loop control structures. That is, the break statement is used to
jump out of the loop. When the break is executed inside the loop, the program control will not execute the loop for further iterations. Generally, the break is associated with if-statement. General form
of using break is:
break;
Example
int x;
for(x = 10;x < 20; x++)
{
if(x%4==0)
break;
printf(%d\n);
}
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
36
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
37
CHAPTER 6 :ARRAYS IN C
An array is a collection of group of variable or data items that can share common name to access
it. All elements in an array are stored consecutively. An array can be of any variable type. A specific value
stored in an array can be displayed by a number called index or subscript.
The ability to use a single name to represent a collection of item and to refer to an item by specifying the
item number enables us to develop concise and efficient program. Suppose you want to store marks of
five students that we can store in different variables but in array we have only one variable and we can
store marks of five students in an array as given
Using variable
int m1=36,m2=36, m3=36,m4=36,m5=36;
Using array
int marks[5]={36,45,54.68,75};
Arrays are very helpful in C programming. You can manipulate number of variables at a time. We can
store more than on value in a using array. Arrays have two category given below:
1) Single dimension
2) Two dimension
Single dimension array:
A list of items can be given one variable name using only one subscript and such a variable is
called a single-subscripted variable or a single dimension array. In mathematics, we often deal with variables that are single-subscripted. The subscript can begin with number 0. Like any other variable arrays
must be declared before they are used. The general form of the array declaration is given below:
Syntax:
DataType ArrayName[size]
Here type means data type of a array style variable, name is the name of array, and boundary means
number of elements within the array.
Example: Declaration of Array:
int marks[5];
Initialization of an array:
Like other variable we can initialize an array. It prevent garbage value in processing. We can initialize an array as follows:
Syntax:
variable[index]= value;
Example:
marks[0] = 50;
marks[1] = 25;
. And so on.
or
int marks[5]={ 50,25,23,56,70};
// declaration with initialization
Sample Program 6.1:
Program to Input five value to an array and print it on screen
#include <stdio.h>
#include <conio.h>
void main()
{
int a[5], i;
clrscr();
printf(Enter Five values : );
for(i=0; i<5; i++)
scanf(%d,&a[i]);
printf(Output of an array :\t);
for(i=0; i<5; i++)
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
38
printf(\n\t%d,a[i]);
getch();
}
similarly you can manipulate array using arithmetical operators and calculate sum of arrays. Example
shows summation of a array.
Sample Program 6.2:
Program to Input five value to an array and calculate of sum and print it on screen
#include <stdio.h>
#include <conio.h>
void main()
{
int a[5], i, sum=0;
clrscr();
printf(Enter Five values : );
for(i=0; i<5; i++)
scanf(%d,&a[i]);
for(i=0; i<5; i++)
sum=sum + a[i];
printf(Output of an array :\t);
for(i=0; i<5; i++)
printf(\n\t%d,a[i]);
printf(\n\t Sum of array is %d,sum) ;
getch();
}
Sample Program 6.3
/* program to add two arrays. */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,a[5],b[5],sum;
clrscr();
printf("Enter any five numbers for array a:");
for (i=0;i<5;i++)
scanf("%d",&a[i]);
printf("\nEnter any five numbers for array b:");
for(i=0;i<5;i++)
scanf("%d",&b[i]);
printf("\nAddition of Array : \n");
for(i=0;i<5;i++)
{
sum = a[i] + b[i];
printf("\n%d",sum);
}
getch();
}
Sample Program 6.4
// example of character array.
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char name[7];
clrscr();
printf("Enter your name : ");
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
39
scanf("%s",&name);
printf("name = %s",name);
for(i=0;i<7;i++)
printf("\n%c",name[i]);
getch();
}
Search
you can also search values within the array. C has two types of searching method.
Linear search
Binary search
Linear search:
In linear search we assume that the first element is the highest value, we compare it with all elements of array one by one, if it found really highest then exchange it with next element and repeat same
steps till entire array is sorted.
Sample Program 6.5
Program to search values from array
#include <stdio.h>
#include <conio.h>
void main()
{
int n[5],i,sv=0,found=0;
clrscr();
printf(Enter five values to array\n);
for(i=0; i<5; i++)
scanf(%d,&n[i];
printf(Enter search value: );
scanf(%d,&sv);
for(i=0; i<5; i++)
{
if(n[i] = = sv)
{
found=1;
break;
}
}
if(found)
printf(\n\t Found);
else
printf(\n\t Not Found);
getch();
}
Binary search
Binary search another type or search method in which we divide an array into two parts, then find
the middle element from it and compare it with search value, if search value is greater then the middle
element, set the lower boundary of array and repeat same step till we get desire value, if value not
present in the array display an error message to user.
Sample Program 6.6
Program to search value using binary search
#include <stdio.h>
#include <conio.h>
void main()
{
int n[5], low, high, mid, f=0, i=0, sv=0;
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
40
clrscr();
printf(Enter values to array\n);
for(i=0; i<5 i++)
scanf(%d,&n[i]);
printf(Enter Search value: );
scanf(%d,&sv);
low=0;
high=4;
while(low <= high)
{
mid=(low+high)/2;
if(n[mid) > sv)
low=mid+1;
else if(n[mid) > sv)
high=mid -1;
else if(n[mid]==sv)
{
f=1;
break;
}
}
if(f == 1)
printf(\n\t Search value found in array);
else
printf(\n\t Search value found in array);
getch();
}
above program search value within the array using binary search.
Sorting of an array
Sorting is a process in which we arrange an array either in ascending order or in descending order, C Language generally provides two types of searching methods
Linear sorting or sequential sort method
Bubble sort method.
Linear sort
In l Liner sort we assume that the first element of the array is the highest value we compares it
with the next element of array if the first element value is larger then the second, exchange it, and repeat
previous steps by comparing value to next element till all elements in array are sorted.
Sample Program 6.7
Program to sort an array using liner sort
#include <stdio.h>
#include <conio.h>
void main()
{
int n[5], i, j, t=0;
clrscr();
printf(Enter Values to an array:\n);
for(i=0; i<5 i++)
scanf(%d.&n[i]);
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
41
Rows
[0][0]
[0][1]
[0][2]
[0][3]
[1][0]
[1][1]
[1][2]
[1][3]
[2][0]
[2][1]
[2][2]
[2][3]
[3][0]
[3][1]
[3][2]
[3][3]
[4][0]
[4][1]
[4][2]
[4][3]
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
44
CHAPTER 7
STRINGS IN C LANGUAGE
The string is sequence of characters that is treated as a single data item. In general, the
character array is called as string. Any group of characters defined between double quotation
marks is a string constant. Such as
The C Programming Language.
Declaring a string
C does not support string as the data type. However is allows us to represent strings as
character arrays. It can be declared as
char string_name[size];
Here, string_name is the valid variable name given to the string and
size determines the number of characters in the string. For example:
char city[10];
char name[30];
Here, city is the character array or a string can be stored with 10
characters. The name will store 30 characters as well.
Initializing a string
Like numerical arrays the strings can also be initialized when they are declared which is referred as compile time initialization. It can be done in following three forms:
char city[6] = Nashik;
char city[ ] = Nashik;
char city[6] = {N, a, s, h, i', k };
For initializing the string at run-time, we use scanf function with %s format specifier such as:
char str[10];
scanf(%s, str);
This statement will initialize the string str by taking the input from the keyboard. This will read the character sequence until occurrence of first separator such as space character, tab or enter and store it into
str. We can also use the following function to input the string including spaces.
char str[10];
gets(str);
The gets() function defined in stdio.h file reads the string from the keyboard until the enter is not pressed.
For printing the string, we can use the printf function in the similar format such as:
printf(%s, str);
Note:
A string consists of characters which is known as string. String terminates by a terminator character
means a NULL character that is \0. When we input a string from key board and when we stopped inputting string C compiler automatically adds a special at the end of string which is known as NULL ( \0 )
character.
There are various types of functions which can be helpful to manipulate string, to use string function we
must include string.h header file, string functions are given below:
1.
strlen( ):
{
char s[80];
int ln;
printf(Enter any string :);
gets(s);
ln=strlen(s);
printf(\n\t Length of %s is %d,s,ln);
getch();
}
2.
string
strcpy( ):
it is used to copy a string to another. Means we can copy source string to target
eg.
char s1[10]=India,s2[10];
strcpy(s2,s1);
}
4.
strrev( ):
baro-
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
48
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
49
CHAPTER - 8
FUNCTIONS IN C LANGUAGE
A function is self-contained block of statements
that performs particular task. C functions
can be classified into two types:
1) Library functions (Built-in Functions)
2) User-defined functions
The library functions are the functions which are already defined in Cs functions library i.e.
header files. For example, the functions scanf() and printf() are the library functions defined in file
stdio.h same as functions sqrt() is defined in math.h and getch() is defined in conio.h. User defined
function is the function defined by the programmer who has written the program. The task to perform is decided by the user. For example, the main() function is an user-defined function. We decide
what is to be written in this function.
Need of user-defined function
1. The functional program facilitates top-down modular programming approach.
2. The length of source program can be reduced by using functions at appropriate places.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by many other programs. This means that a C programmer can build on what
others have already done. That is we can reuse the functions already defined in some program files.
user-defined function
In order to make use of user defined functions, we need to establish three elements that are
related to functions.
1. Function definition
2. Function call
3. Function declaration
1. Declaration of a function
Syntax:
Return-type name_of_function(list of arguments);
Example:
int length(char ch);
float factorial(int);
A function has four type of declaration according to it type. There are four type of function declaration
No return value no argument; means a function will not return any value or it will not accepting arguments
form user.
Eg.
void sumNo(void);
No return value with argument, means a function will not return value but it will accept one or more then
one arguments for process.
Eg. void sumNo(int, int)
Above function will not return any value but it will accept two integer type arguments.
With return value with no argument, means a function will return a value but never accept any
argument from user
Eg.
int sumNo(void);
With return value with arguments, means a function will return a value and it also accepts one or more
then one arguments for process.
Eg.
int sumNo(int, int);
A declaration of a function is known as a prototype of a function.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
50
2. Function definition
The function definition is an independent program module that is specially written to implement the
requirements of the function. So it is also called as function implementation.
Syntax:
Return_type function_name(parameters list)
{
local variables declaration;
statements;
- - - - - -;
- - - - - -;
return statement;
}
It includes three parts:
1. Function type
It specifies type of the value that the function is expected to return to the program calling the
function. It is also called as return type. If function is not returning any values we have to
specify it as void.
2. Function name
It is any valid C identifier name and therefore must follow the rules for creation of variable names
in C.
3. Parameters list
It declares variables that will receive the data sent by the calling program. They serve as
input data to the function to carry out specific task. Since, they represent the actual input values
they are referred as formal parameters or formal arguments.
Example:
float mul(float x, float y)
{
float result;
/* local variable */
result = x * y;
/* find the result */
return(result);
/* return the result */
}
Return values
A function may or may not send back any value to the calling function. If it does, it is done by
return statement. The return statement also sends the program control back to the calling
function. It is possible to pass a calling function any number of values but called function can
only return one value per call.
3. Function call
A function can be called by simply using function name followed by a list of actual parameters (or arguments) if any, enclosed in parentheses.
Example:
main()
{
float m;
m = mul(5.2, 3.71);
/* function call */
printf(\n%d,m);
}
When compiler encounters the function call, it transfers program control to the function
mul() by passing values 5.2 and 3.71 (actual parameters) to the formal parameters on the function
mul(). The mul() will performs operations on these values and then returns the result. It will be stored
in variable m.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
51
// function Definition
// Calling a function.
}
void sumNo(int x, int y)
// Body of a function
{
int z;
z=x+y;
printf(\n\t Sum is %d, z);
}
Sample Program 8.3
// A function with return type and no arguments.
#include <stdio.h>
#include <conio.h>
void main()
{
int n3;
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
52
int sumNo(void);
clrscr();
n3=sumNo();
printf(\n\t Sum is %d, n3);
getch();
}
int sumNo(void)
// Body of a function
{
int n1,n2;
printf(Enter value to N1: );
scanf(%d,&n1);
printf(Enter value to N2: );
scanf(%d,&n2);
return (n1+n2);
}
Sample Program 8.4
// A function with return with arguments
#include <stdio.h>
#include <conio.h>
void main()
{
int n1,n2,n3;
int sumNo(int,int);
clrscr();
// Calling a function.
getch();
}
int sumNo(int x,int y)
{
int z;
return (z);
}
// Body of a function
Similarly you can developed function for subtraction, multiplication, and division of two numbers. For
above mentioned type.
A function may called with reference to value is known as called by value, where as when a function is
called with reference to address of a variable is known as called by reference.
In called by value type of function calling we send a copy of a variable to the called function. Where as in
called by reference we send the address of variable.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
53
Recursive function
When a function calls itself within the same function is called as recursion of a function. A recursive function is more efficient then a normal function. It provide faster process.
Sample Program 8.5
/*A Program using recursive function
Find a factorial number of a given number.*/
#include <stdio.h>
#include <conio.h>
void main()
{
long n=0,f=0;
long factorial(long);
// Declaration of a function / Prototype of a function
clrscr();
printf(Enter value to N: );
scanf(%ld,&n);
f=factorial(n);
// Calling a function.
printf(\n\t %ld! = %ld, n,f);
getch();
}
long factorial(long n)
{
long f=1;
if(n==1)
return 1;
else
f=n * factorial(n-1);
// Body of a function
return f ;
}
Exercise of a function
Write a function to find square root of a given number.
Write a function to find square of a given number.
write a function to convert temperature entered in Celsius degree to its equivalent Fahrenheit.
Write a function to print first n fibbonacy number.
Write a function to find circumference and area of a circle with given radius
Write a function to find distance entered in km to it equivalent meter, feet and inches.
Write a function to convert Indian currency to its equivalent dollar, and pound and vise versa.
Write a function to swap a value of variables.
Write a function to calculate number of words, characters, digits in a given string.
Write a function to remove extra spaces from given string.
Write a function to reverse a string.
Write a function to check whether entered character is vowel or not.
Write a function to check whether entered year is leap year of not.
Write a function to check whether a entered number is odd of even.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
54
Additional Programs
Sample program ad1
Function to find compound interest (no return no argument)
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr() ;
void printline();
void value();
void printline();
printline();
value();
printline();
getch();
}
void printline()
{
int i;
for(I=1;I<=35;I++)
printf(%c.-);
printf(\n);
}
void value()
{
int
year, period;
float
inrate, sum, principle;
printf(Principle amount? );
scanf(%f,&principle);
printf(Interest rate? );
scanf(%f,&inrate);
printf(Period? );
scanf(%d, &period);
sum=principle;
year=1;
while(year <= period)
{
sum=sum* (1+inrate);
year=year+1;
}
print(%f %f %d %f,principle,inrate,periao,sum);
getch();
}
Sample Program ad2
Function to find compound interest (with return no argument)
#include <stdio.h>
#include <conio.h>
void main()
{
float sum;
void printline();
float value();
void printline();
clrscr()
printline();
sum=value();
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
55
printline();
print( %12.2f,sum);
getch();
}
void printline()
{
int i;
for(I=1;I<=35;I++)
printf(%c.-);
printf(\n);
}
float value()
{
int
year, period;
float
inrate, sum, principle;
printf(Principle amount? );
scanf(%f,&principle);
printf(Interest rate? );
scanf(%f,&inrate);
printf(Period? );
scanf(%d, &period);
sum=period;
year=1;
while(year <= period)
{
sum=sum* (1+inrate);
year=year+1;
}
print(%8.2f %5.2f %5d ,principle,inrate,period);
return sum;
}
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
56
CHAPTER 9
POINTERS IN C
A pointer is a variable capable of holding address of another variable. A pointer provides faster
process as well as variables that are not accessible to the function that also can be accessed through the
function. Pointer variable occupies less memory means it occupy only two bytes in memory. It also used
to developed system programs like virus, anti-virus, operating system etc. A pointer is denoted by * sign.
We can declare a pointer variable same as normal variable but we must put * sign before a variable to indicate pointer variable.
Syntax:
dataType *name_of_pointervariable;
Example:
int *p;
char *ptr;
The address can be collected in a variable, by ,
p = &i;
here, p is not an ordinary variable. It is a pointer variable that contains the address of other integer variable ( i ).
Sample Program of pointer variable 9.1
// Write a program to inter change value of two variable.
#include <stdio.h>
#include <conio.h>
void main()
{
int n1, n2, t, *p1, *p2;
clrscr();
p1=&n1;
p2=&n2;
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
57
Pointer to an array:
Pointer to an array is that a pointer variable points to an array. A pointer variable holds address of
the first elements of an array which is known as base address. Then after we can manipulate an array
using pointer.
Syntax:
int n[5]={0}, *p1
p1=n;
Here p1 holds the address of first element of an array. This address of first element is known as base
address. A sample program shows use of pointers with an array.
Sample Program 9.2
// Program to accept five value to an array and print it with the help of array.
#include <stdio.h>
#include <conio.h>
void main()
{
int n[5], i, *p1;
clrscr();
p1=n;
printf(Enter five values to an array\n);
for(i=0; i<5; i++)
scanf(%d,&n[i]);
printf(\n\t Output of an array\n);
for(i=0; i<5; i++)
printf(%3d,*p1++);
getch();
}
Above example shows use of pointer to an array. In printing process we have been used pointer notation
to print values of an array. Normally ++ operator increments value of variable by one but here in pointer
arithmetic it will increment value by the size of data type used by the variable. Means if a pointer variable
points to an integer type ++ operator increments value of pointer variably by the size of an integer.
Array of pointers:
When an array of pointer hold the address of one or more then one variable it is known as array
of pointer. Following example shows use of array of pointer
Sample Program 9.3
/* Program to declare an array of pointer type and store five different address of five different variable and print it. */
#include <stdio.h>
#include <conio.h>
void main()
{
int *n[3],n1=0, n2=0, n3=0, i;
clrscr();
n[0]=&n1;
n[1]=&n2;
n[2]=&n3;
printf(Enter value to N1: );
scanf(%d,n1);
printf(Enter value to N2: );
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
58
scanf(%d,n2);
printf(\n\t Output of variables using array of pointer\n);
for(i=0; i<3; i++)
printf(\n\t N%d = %3d,i+1,*n[i]);
getch();
}
Exercise of a pointer
Write a program using pointer that will search a given value from an array.
Write a program using pointer that will sort an array in ascending order.
Write a program using pointer to find length of a given string.
Write a program using pointer to copy a string to another
Write a program using pointer to concatenate two string
Write a program using pointer to convert lowercase string to its uppercase string
Write a program using pointer to convert uppercase string to its lowercase string.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
59
CHAPTER 10
STRUCTURE AND UNION
A structure is a collection of different types of variables which are known as member of a structure. An advantage of the structure is that we can store different types of values. Generally a normal array
can hold more than one variable of similar type, where a structure can hold more than one variable of different size. A structure can be defined with struct clause. A structure member can occupy individual
memory location.
Declaring a Structure
Syntax:
struct StructureName
{
member1;
member2;
memberN;
};
Example:
struct book
{
char name[20] ;
float price;
int pages;
};
This statement defines a new data type called struct book. Each variable of this data type will consist of
a character variable name, a float variable called price and integer variable called pages. Once the new
structure data type has been defined one or more variables can be declared to be of that type. For example the variables b1, b2, b3 can be declared to be of the type struct book, as,
struct book b1,b2,b3;
This statement sets aside space in memory. It makes available space to hold all the elements in the structure.
We can combine the declaration of the structure type and the structure variables in one statement.
For example,
struct book
{
char name[20] ;
float price;
int pages;
};
struct book b1,b2,b3;
is same as
struct book
{
char name[20] ;
float price;
int pages;
} b1,b2,b3;
Or even
struct
{
char name[20] ;
float price;
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
60
int pages;
}b1,b2,b3;
Like variables and array, structure variables can also be initialized where they are declared. The format
used is quite similar to that used to initiate arrays.
struct book
{
char name[20] ;
float price;
int pages;
};
struct book b1 = { Basic, 130.00,550};
struct book b2 = { Physics, 150.00,300};
Accessing a structure Elements
In arrays we can access individual elements of an array using a subscript/index. Structures use a different
scheme. They use a dot (.) operator. So to refer to pages of the structure defined above example, we
have to use,
b1.pages
similarly, to refer to price we would use,
b1.price
Note that before the dot there must always be a structure variable and after the dot there must always be
a structure element.
Sample Structure Program 10.1
/* Declare a structure of a student which has following member rno, name, address, city, accept
data from user and print it. */
#include <stdio.h>
#include <conio.h>
struct student
{
int rno;
char name[10],address[15],city[20];
};
void main()
{
struct student s1;
clrscr( );
printf(Enter Rollno: );
scanf(%d,&s1.rollno);
flushall( );
printf(Enter Name: );
gets(s1.name);
flushall();
printf(Enter Address: );
gets(s1.address);
flushall( );
printf(Enter City: );
gets(s1.city);
flushall( );
printf(\n\t Rollno: %d,s1.rollno);
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
61
}
similarly we can assign a pointer to structure object variable
Sample structure program 10.3
/* Declare a structure of a student which has following member rno, name, address, city, accept
data from user and print it. Use pointer variable */
#include <stdio.h>
#include <conio.h>
struct student
{
int rno;
char name[10],address[15],city[20];
};
void main()
{
int I;
struct student s1,*s;
clrscr();
s=&s1;
printf(Enter Rollno: );
scanf(%d,&s->rollno);
flushall();
printf(Enter Name: );
gets(s->name);
flushall();
printf(Enter Address: );
gets(s->address);
flushall();
printf(Enter City: );
gets(s->city);
flushall();
printf(\n\t Rollno: %d,s->rollno);
printf(\n\t Name: %s,s->name);
printf(\n\t Address: %s,s->address);
printf(\n\t City: %s,s->city);
getch();
}
similarly we can assign a pointer to structure object variable which an array type.
Sample Structure Program 10.4
/* Declare a structure of a student which has following member rno, name, address, city, accept
data from user and print it. Use structure array and pointer variable */
#include <stdio.h>
#include <conio.h>
struct student
{
int rno;
char name[10],address[15],city[20];
};
void main()
{
int i;
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
63
union student
{
int rno;
char name[10],address[15],city[20];
};
void main()
{
union student s1;
clrscr();
printf(Enter Rollno: );
scanf(%d,&s1.rollno);
flushall();
printf(Enter Name: );
gets(s1.name);
flushall();
printf(Enter Address: );
gets(s1.address);
flushall();
printf(Enter City: );
gets(s1.city);
flushall();
printf(\n\t Rollno: %d,s1.rollno);
printf(\n\t Name: %s,s1.name);
printf(\n\t Address: %s,s1.address);
printf(\n\t City: %s,s1.city);
getch();
}
Simple union structure Program 10.6
/* Declare a structure of a student which has following member rno, name, address, city, accept
data from user and print it. Use union structure array. */
#include <stdio.h>
#include <conio.h>
union student
{
int rno;
char name[10],address[15],city[20];
};
void main()
{
int I;
union student s[3];
clrscr();
for(i=1; i<3;i++)
{
printf(Enter Rollno: );
scanf(%d,&s[i].rollno);
flushall();
printf(Enter Name: );
gets(s[i].name);
flushall();
printf(Enter Address: );
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
65
gets(s[i].address);
flushall();
printf(Enter City: );
gets(s[i].city);
flushall();
}
for(i=0;i<3;i++)
{
printf(\n\t Rollno: %d,s[i].rollno);
printf(\n\t Name: %s,s[i].name);
printf(\n\t Address: %s,s[i].address);
printf(\n\t City: %s,s[i].city);
printf(\n);
}
getch();
}
Exercise of a structure
1.
Write program to define following structure having following members
struct emp
{
int eno;
char name[15],desig[15],dept[20];
int da, hra, pf; bs,gs;
}
2.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
68
CHAPTER 11
FILE HANDLING IN C
So far we learn about structures and unions. These structures and unions are useful in file handling. So what is a file? A question arise in mind naturally isnt it?
A file is collection of related information. Till now what we learn is to input or to print it on
screen. We can not store it permanently. Unless we store it permanently it is worth because we can not
reuse it for further process. A file is a place or we can say that it is a basic unit to store data permanently. To understand a file, we must understand following terms:
1.
2.
3.
field:
record:
database:
To handle a file properly in C we must go through following functions, useful in file handling, functions are
listed below:
1.
fopen(): it is used to define a file and open it in memory for writing purpose.
If file does not
exist on disk compiler add file to disk and then open it in memory for writing.
syntax:
fopen(filename,mode);
2.
fread():
syntax:
3.
4.
eof():
5.
fclose():
syntax:
6.
rewind();
it is used to reposition file pointer at the top of file.
syntax:
rewind(filepointer);
As we learn about the function used to red or to write in file, we must learn about file mode which helps to
maintain files. There various modes listed below
1.
2.
3.
w, w+:
this mode open file for write and update mode in memory. When we
use this mode, each time file opens in memory loses its data.
r, r+:
this mode opens file for reading and updating mode.
a, a+:
this mode opens file for append and update mode, data which
stored in file will not be erased.
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
69
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
70
struct student
{
int rno;
char name[10],address[15],city[20];
};
void main()
{
struct student s1;
FILE *fp;
clrscr();
fp=fopen(student.dat,r);
if(fp==0)
{
printf(\n\t Error opening file);
getch();
exit(1);
}
while(fread(&s1,sizeof(s1),1,fp))
{
printf(\n\t Rollno: %d,s1.rollno);
printf(\n\t Name: %s,s1.name);
printf(\n\t Address:%s,s1.address);
printf(\n\t City: %s,s1.city);
printf(\n);
}
fclose(fp);
}
Sample Program to delete record from file 11.3
// A program to delete record from file
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct student
{
int rno;
char name[10],address[15],city[20];
};
void main()
{
struct student s1;
FILE *fp, *ft;
int rno=0;
char ch=y;
clrscr();
fp=fopen(student.dat,a+);
if(fp==0)
{
printf(\n\t Error opening file);
getch();
exit(1);
}
rewind(fp);
while(ch==Y || ch==y)
{
clrscr();
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
71
printf(Enter Rollno:)
scanf(%d,&rno);
flushall();
ft=fopen(temp.dat,w);
rewind(fp);
while(fread(&s1,sizeof(s1),1,fp))
{
if(s1.rno != rno)
write(&s1,sizeof(s1),1,fp);
}
fclose(fp);
fclose(ft);
remove(student.dat);
rename(temp.dat,student.dat)
fp=fopen(student.dat,r);
printf(Continue? (y yes / n no) );
scanf(%c,&ch);
}
}
Item related
Sample Program to add record 11.4
Declare a structure of a item which has following member ino, iname, qty, rate, amount, accept data from
user and store it in item.dat file.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct item
{
int ino, qty, rate, amount;
char iname[10];
};
void main()
{
struct item s1;
FILE *fp;
char ch=y;
clrscr();
fp=fopen(item.dat,a+);
if(fp==0)
{
printf(\n\t Error opening file);
getch();
exit(1);
}
while(ch==Y || ch==y)
{
clrscr();
printf(Enter ItemNo: );
scanf(%d,&s1.ino);
flushall();
printf(Enter Item Name: );
gets(s1.iname);
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
72
flushall();
printf(Enter Quantiry: );
scanf(%d,&s1.qty);
flushall();
printf(Enter Rate: );
scanf(%d,&s1.rate);
flushall();
s1.amount=s1.qty*s1.rate;
fwrite(&s1,sizeof(s1),1,fp);
printf(Continue? (y yes / n no) );
scanf(%c,&ch);
}
}
Above program adds records in file till user press n from keyboard.
Sample Program to read a file 11.5
// Read data from an existing student file.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct item
{
int ino, qty, rate, amount;
char iname[10];
};
void main()
{
struct item s1;
FILE *fp;
clrscr();
fp=fopen(item.dat,a+);
if(fp==0)
{
printf(\n\t Error opening file);
getch();
exit(1);
}
while(fread(&s1,sizeof(s1),1,fp))
{
printf(\n\t
ItemNo: %d,s1.ino);
printf(\n\t Item Name: %s,s1.iname);
printf(\n\t Quantiry: %d,s1.qty);
printf(\n\t
Rate: %d,s1.rate);
printf(\n\t
Amount: %d,s1.amount);
}
}
Sample Program to delete record from file 11.6
// Program to delete a record from a file
A program to delete record from file
#include <stdio.h>
#include <conio.h>
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
73
#include <stdlib.h>
struct item
{
int ino, qty, rate, amount;
char iname[10];
};
void main()
{
struct item s1;
FILE *fp, *ft;
int ino=0;
clrscr();
fp=fopen(item.dat,a+);
if(fp==0)
{
printf(\n\t Error opening file);
getch();
exit(1);
}
rewind(fp);
while(fread(&s1,sizeof(s1),1,fp))
{
clrscr();
printf(Enter item no to be deleted:)
scanf(%d,&ino)
flushall()
ft=fopen(temp.dat,w);
while(fread(&s1,sizeof(s1),1,fp))
{
if(s1.ino != ino)
write(&s1,sizeof(s1),1,fp);
}
fclose(fp);
fclose(ft);
remove(item.dat);
rename(temp.dat,item.dat)
fp=fopen(student.dat,r);
}
fclose(fp);
}
Additional programs
A Sample program for result ad1
#include<stdio.h>
#include<conio.h>
void main()
{
int m1,m2,m3,m4,m5;
float total, percent;
clrscr();
printf("enter the value fo m1 :");
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
74
scanf("%d",&m1);
printf("enter the value of m2 :");
scanf("%d",&m2);
printf("enter the value of m3 :");
scanf("%d",&m3);
printf("enter the value of m4 :");
scanf("%d",&m4);
printf("enter the value of m5 :");
scanf("%d",&m5);
total=m1+m2+m3+m4+m5;
percent=total*100/500;
printf("\n*********************result**************");
printf("\ntotal marks of the student :: %f",total);
printf("\npercent of the student :: %f",percent);
If(percent>=70)
printf("distinction");
else if (percent>=60 && percent<70)
printf("first grade");
getch();
}
A Sample program of structure to write employee details in file. ad2
#include<stdio.h>
#include<conio.h>
struct ss
{
int no;
char name[10];
int salary;
};
void main()
{
struct ss s1;
FILE *fp;
clrscr();
fp=fopen("datas","a");
printf("Enter the value of no:");
scanf("%d",&s1.no);
printf("Enter the name\n:");
fflush(stdin);
gets(s1.name);
printf("Enter the salary:");
scanf("%d",&s1.salary);
fwrite(&s1,sizeof(s1),1,fp);
getch();
}
Sample Pogram ad3: to read employee details from file.
#include<stdio.h>
#include<conio.h>
struct ss
{
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
75
int no;
char name[10];
int salary;
};
void main()
{
struct ss s1;
FILE *fp;
clrscr();
fp=fopen("datas","r");
fread(&s1,sizeof(s1),1,fp);
printf("the no is :%d\n",s1.no);
printf("the name is: %s\n",s1.name);
printf("the salary is: %d\n",s1.salary);
getch();
}
Sample Program ad4:
#include<stdio.h>
#include<conio.h>
struct ss
{
int no;
char name[10];
int salary;
};
void main()
{
struct ss s1;
FILE *fp;
clrscr();
fp=fopen("datas","r");
fread(&s1,sizeof(s1),1,fp);
while(!feof(fp))
{
printf("The no is: %d\n",s1.no);
printf("The name is: %s\n",s1.name);
printf("The salary is: %d\n",s1.salary);
fread(&s1,sizeof(s1),1,fp);
}
getch();
}
Sample Program ad5:
A program to convert a number into its equivalent roman number
#include<stdio.h>
#include<conio.h>
void main()
{
int y;
clrscr();
void roman(int);
printf ("enter year");
scanf ("%d",&y);
roman(y);
}
void roman(int x)
{
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
76
while(x>=1000)
{
printf("m");
x=x-1000;
}
while(x>=500)
{
printf("d");
x=x-500;
}
while(x>=100)
{
printf ("c");
x=x-100;
}
while (x>=50)
{
printf ("l");
x=x-50;
}
while (x>=10)
{
printf ("x");
x=x-10;
}
while (x>=5)
{
printf ("v");
x=x-5;
}
while (x>=1)
{
printf ("i");
x=x-1;
}
}
Sample Program of function ad6:
#include<stdio.h>
#include<conio.h>
int i=0;
void main()
{ clrscr();
void val();
printf("main i=%d",i);
i++;
val();
printf("main i=%d",i);
val();
}
void val()
{
i=100;
printf("val i=%d",i);
}
Sample Program ad7: to calculate salary based on commision.
#include <stdio.h>
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
77
#include <conio.h>
void main()
{
int salary=0,sales_amt=0;
clrscr();
printf("enter the value of sales amount:");
scanf("%d",&sales_amt);
printf("enter the value of salary:");
scanf("%d",&salary);
if (sales_amt > 12000)
{
printf("rate of commission is %f",sales_amt*0.12);
printf("\nsalary=%f",salary+sales_amt*0.12);
}
else
{
printf("rate of commission is %f",sales_amt*0.08);
printf("\nsalary= %f",salary+sales_amt*0.08);
}
getch();
}
Sample Program ad8:
A program to find whether a string is palindrome or not.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char arr[]="radar";
char *rev ;
clrscr();
puts(arr);
rev=strrev(arr);
printf ("\n%s",rev);
if(rev==arr)
{
printf("\nit is palendrone");
}
else
{
printf ("\nit is't a palendrone");
}
}
Sample Program ad9:
A Program to print a prim factor of a given number.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,c,i,j;
clrscr();
printf ("enter no. to get its prime factors");
scanf ("%d",&a);
for (c=1;;c>=100;c++)
{
j=(a%c);
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
78
if (j==0);
printf ("%d\n",c);
}
}
char c;
clrscr();
printf("\nEnter the value of a:");
scanf("%f",&a);
printf("\nEnter the value of b:");
scanf("%f",&b);
printf("\nEnter the c:");
fflush (stdin);
scanf("%c",&c);
switch(c)
{
case '+':
{
d=a+b;
break;
}
case '-':
{
d=a-b;
break;
}
case '*':
{
d=a*b;
break;
}
default :
{
d=a/b;
break;
}
}
printf("The value of d is : %f",d);
getch();
}
Sample Program ad12:
A program to find greater number among given two number
#include<stdio.h>
#include<conio.h>
void main()
{
int x=0,y=0;
clrscr();
printf("Enter the value of x");
scanf("%d",&x);
printf("Enter the value of y");
scanf("%d",&y);
if(x>y)
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
getch();
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
80
}
Sample Program ad13:
A Program to display menu and print an operation accordingly.
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
int cel=0,fahren=0,choice=0;
clrscr();
printf("\n\t1) Temperature in celcius");
printf("\n\t2) Temperature in fahrenheit");
printf("\n\t3) Exit");
printf("\n\tenter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n\tenter the temperature in celcius:");
scanf("%d",&cel);
printf("\n\ttemperature in fahrenheit =%d",9/5*(cel+32));
break;
case 2:
printf("\n\tenter the temperature in fahrenheit:");
scanf("%d",&fahren);
printf("\n\ttemperature in celcius =%d",9/5*(fahren-32));
case 3:
exit(0);
}
getch();
}
Sample Program ad14:
A program to calculate sales.
//sales girls
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50][50],g,c,d,e,i,j,v=0,t=0,k,h;
clrscr();
printf ("Enter no of girls g::");
scanf ("%d",&g);
printf ("Enter no of items sold i::");
scanf ("%d",&i);
for(j=1;j<=g;j++)
{
for(k=1;k<=i;k++)
{
printf ("a[%d][%d]::",j,k);
scanf ("%d",&a[j][k]);
}
}
for(j=1;j<=g;j++)
{
v=0;
for(k=1;k<=i;k++)
{
v=v+a[j][k];
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
81
t=t+a[j][k];
}
printf("\n total value of sales by each girls v::%d",v);
}
printf("\n total value of sales of all items t::%d",t);
for(k=1;k<=i;k++)
{
h=0;
for(j=1;j<=g;j++)
{
h=h+a[j][k];
}
printf("\n total value of sales of individual items h::%d",h);
}
}
Program to show the use of operators.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
float x,y,c,sum;
x=0;
y=0;
c=0;
printf("ENTER THE VALUE FOR X: \n");
scanf("%f",&x);
printf("ENTER THE VALUE FOR Y: \n");
scanf("%f",&y);
printf("ENTER THE VALUE FOR C: \n");
scanf("%f",&c);
sum = (x/y) + c;
printf("THE SUM OF ANSWER IS : %f",sum);
sum = 3 * x * x + 2 * x * x + 1;
printf("THE SUM OF ANSWER IS : %f",sum);
getch();
}
Program to find remainder of a given number.
#include<stdio.h>
#include<conio.h>
main()
{
int a, b;
clrscr();
printf("enter the value of a: ");
scanf("%d",&a);
b=a%10;
printf("the remainder is: %d",b);
getch();
}
Program to find largest using ternary operator
#include <stdio.h>
#include <conio.h>
void main()
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
82
{
int a,b,c;
clrscr();
printf("Enter the value of a:\n");
scanf("%d",&a);
printf("Enter the value of b:\n");
scanf("%d",&b);
c=a>b?a:b;
printf("the vlue of cis:%d\n",c);
getch();
}
{
cnt4=cnt4+1;
}
}
printf("\n\t Number of a is:%d\n",va);
printf("\n\t Number of e is:%d\n",ve);
printf("\n\t Number of i is:%d\n",vi);
printf("\n\t Number of o is:%d\n",vo);
printf("\n\t Number of u is %d\n",vu);
getch();
}
Program to print multiplication table.
#include<stdio.h>
#include<conio.h>
main()
{
int i,a,b;
clrscr();
a =860;
i=1;
while(i<=10)
{
b=a*i;
printf("%3d * %3d = %3d \n",a,i,b);
i=i+1;
}
getch();
}
Program to print alternate digits form given number.
#include <stdio.h>
#include <conio.h>
main()
{
long a,b,r,i,cnt=0,s=0,rs=0;
clrscr();
printf("enter the value:");
scanf("%ld",&a);
b=a;
while(a>0)
{
r=a%10;
a=a/10;
cnt=cnt+1;
}
for(i=1;i<=cnt;i++)
{
if(i%2!=0)
{
r=b%10;
s=s*10+r;
b=b/10;
}
else
{
b=b/10;
}
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
84
}
while(s>0)
{
r=s%10;
rs=rs*10+r;
s=s/10;
}
printf("\n\t An Alternate number is %ld", rs);
getch();
}
Program to count and sum of an individual digits of a given number.
#include <stdio.h>
#include <conio.h>
void main()
{
long int a,r,sum=0,cnt =0;
clrscr();
printf("ENTER THE VALUE: ");
scanf("%ld",&a);
while(a>0)
{
r=a%10;
a=a/10;
printf("%ld\n", r);
sum=sum + r;
cnt = cnt + 1;
}
printf("\n\t The sum is %ld\n", sum);
printf("\n\t Total Number of digits are %3ld\n",cnt);
getch();
}
Program to print following pattern on screen
1
1
2
1
2
3
#include <stdio.h>
#include <conio.h>
main()
{
int i, j;
clrscr();
for(i=1; i<=5;i++)
{
for(j=1;j<=5; j++)
{
printf("%d",j);
}
printf("\n");
}
getch();
#include<conio.h>
main()
{
int call,rcalls;
float rs;
clrscr();
printf("Enter the number of call:");
scanf("%d",&call);
if(call<=150)
rs=0;
else
{
rcalls=call-150;
rs=rcalls*1;
}
printf("\ncalls=%d\nbill=%f",call,rs);
getch();
}
program to perform arithmetic operation using function and if statement
#include <stdio.h>
#include <conio.h>
void main()
{
int a,b,c,d,e,f;
char ch;
clrscr();
printf("enter the value of a : ");
scanf("%d",&a);
printf("enter the value of b : ");
scanf("%d",&b);
printf("enter the operator: ");
fflush(stdin);
scanf("%c",&ch);
if(ch=='+')
{
c=add(a,b);
printf("The value of c is: %d\n",c);
}
else if(ch=='-')
{
d=sub(a,b);
printf("The value of d is: %d\n",d);
}
else if(ch=='*')
{
e=mul(a,b);
printf("The value of e is: %d\n",e);
}
else if(ch=='/')
{
f=div(a,b);
printf("The value of f is: %d\n",f);
}
getch();
}
int add(int g,int h)
{
int c;
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
86
c=g+h;
return c;
}
int sub(int j, int k)
{
int d;
d=j-k;
return d;
}
int mul(int m, int n)
{
int e;
e=m*n;
return e;
}
int div(int p, int q)
{
int f;
f=p/q;
return f;
}
Program to check date validity
#include <stdio.h>
#include <conio.h>
main()
{
int dd,month,year;
clrscr();
printf("Enter the date: ");
scanf("%d",&dd);
printf("Enter the month: ");
scanf("%d",&month);
printf("Enter the year: ");
scanf("%d",&year);
if (month==1 ||month==3 ||month==5 ||month==7 ||month==8 ||month==10
||month==12)
{
printf("month has 31 days:");
if(dd<1 || dd>31 )
{
printf("date is invalid: ");
}
}
else if(month==4 ||month==6 ||month==9 ||month==11)
{
printf("month has 30 days: ");
if (dd<1 || dd>30)
{
printf("date is invalid:");
}
}
else if (month==2)
{
if (year%4==0)
{
if(dd<1 || dd>29)
{
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
87
scanf("%d",&values[i][j]);
}
}
for(i=0;i<=2;i++)
{
printf("Enter the value for row %d:\n",i);
for(j=0;j<=2;j++)
{
scanf("%d",&values1[i][j]);
}
}
printf("The values for first matrix values:\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf(" %d ",values[i][j]);
}
printf("\n");
}
printf("The values for first matrix values1:\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf(" %d ",values1[i][j]);
}
printf("\n");
}
printf("The values for first matrix values2:\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
values2[i][j]=values[i][j]+values1[i][j];
printf(" %d ",values2[i][j]);
}
printf("\n");
}
getch();
}
Program to print triangle pattern like
1
1
2
1
1
2
3
2
1
#include <stdio.h>
#include <conio.h>
void main()
{
int i,j,k,l,m,p=4;
clrscr();
for(i=1;i<=4;i++)
{
for(l=1;l<=p;l++)
{
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
90
printf("*");
}
for(j=1;j<=i;j++)
{
printf("%d",j);
}
for(k=i-1;k>=1;k--)
{
printf("%d",k);
}
for(m=1;m>=p;m--)
{
printf("**");
}
printf("*\n");
p--;
}
getch();
}
Program to print result sheet of three student in columns
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,stud[3],subject[3],values[3][3];
clrscr();
for(i=0;i<=2;i++)
{
printf("Enter the marks for student :\n");
for(j=0;j<=2;j++)
{
scanf("%d",&values[i][j]);
}
}
for(i=0;i<=2;i++)
{
stud[i]=0;
subject[i]=0;
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
subject[i]=subject[i]+values[i][j];
}
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
stud[i]=stud[i]+values[j][i];
}
printf("\n");
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
91
{
printf(" %d ",values[i][j]);
}
printf("\n");
}
printf("column wise total :\n");
for(i=0;i<=2;i++)
{
printf(" %d ",stud[i]);
}
printf("\n");
printf("row wise total :\n");
for(i=0;i<=2;i++)
{
printf(" %d ",subject[i]);
}
getch();
}
Program to find largest value among given two value using function.
#include<stdio.h>
#include<conio.h>
main()
{
int a, b;
clrscr();
printf("Enter the value of a: \n");
scanf("%d",&a);
printf("Enter the value of b: \n");
scanf("%d",&b);
biggest(a,b);
getch();
}
void biggest(int x,int y)
{
int z;
if(x>y)
{
z=x;
}
else if(x<y)
{
z=y;
}
else
{
z=x;
}
printf("The big value is : %d\n", z);
}
Program to copy a string to another string using user define function.
#include<stdio.h>
#include<conio.h>
void main()
{
char name1[10],name2[10];
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
92
int a, c=0;
clrscr();
printf("Enter the string:");
scanf("%s",name1);
cpystr(a,c,name2,name1);
getch();
}
cpystr(int i, int j, char name2[], char name1[])
{
for(i=0;name[i] !='\0';i++)
{
name2 [j]=name1[i];
j++;
}
name1[j]='\0';
printf("The string is:%s\n",name);
}
Program to check whether entered character is an upper case alphabet, a lower case alphabet, a
number or a special character.
#include<stdio.h>
#include<conio.h>
void main()
{
char alpha;
clrscr();
printf("Enter any Character: ");
scanf("%c",&alphabet);
check(alpha);
getch();
}
check(char al)
{
if(al>='A' && al<='Z')
{
printf("It is in capital");
}
else if(a>='a' && a<='z')
{
printf("It is in small letters");
}
else if(a>='0' && a<='9')
{
printf("It is a number");
}
else
{
printf("It is a special character");
}
}
A program to sort an array in ascending using function
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, temp, values[5]={0};
clrscr();
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
93
ascsort(i,j,temp,values[5]);
getch();
}
ascsort(int i,int j,int temp,int values[])
{
for(i=0;i<=4;i++)
{
printf("Enter the value : \n");
scanf("%d",&values[i]);
}
for(i=0;i<=4;i++)
{
for(j=i+1;j<=4;j++)
{
if(values[i]>values[j])
{
temp=values[i];
values[i]=values[j];
values[j]=temp;
}
}
}
for(i=0;i<=4;i++)
{
printf(" %d ",values[i]);
}
}
Program to accept values in array and print it using function
#include<stdio.h>
#include<conio.h>
void main()
{
int a,value[5];
clrscr();
printf(Enter Five values to array:\n);
for(a=0; a<5;a++)
{
scanf(%d,&value[a]);
arr(a,value);
getch();
}
arr(int i,int values[])
{
for(i=0;i<=4;i++)
{
printf("values[%d]=%d \n",i,values[i]);
}
}
Program to print fibbonacii series using array and function.
#include<stdio.h>
#include<conio.h>
main()
{
int j,values1[10];
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
94
clrscr();
febonancci(j,values1);
getch();
}
febonancci(int i, int values[])
{
values[0]=1;
values[1]=1;
printf("%d %d",values[0],values[1]);
for(i=2;i<=9;i++)
{
values[i]=values[i-1]+values[i-2];
printf(" %d ",values[i]);
}
}
Program to pattern in reverse order like 54321 using function
#include <stdio.h>
#include <conio.h>
void main()
{
int a=0,b=0;
clrscr();
reverse(a,b);
getch();
}
reverse(int i,int j)
{
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
printf("%3d",j);
}
printf("\n");
}
}
Program to calculate da, hra, etc using function
#include<stdio.h>
#include<conio.h>
void main()
{
int basic;
clrscr();
printf("Enter the basic amount:");
scanf("%d",&basic);
calcbas(basic);
getch();
}
caldbas(int basic)
{
float hra,da,pf;
hra=basic*0.10;
da=basic*0.20;
pf=basic*0.30;
printf("The value of hra is:%f\n",hra);
printf("The value of da is :%f\n",da);
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
95
int i,j,k=0,flag=0;
clrscr();
printf("Enter the string:\n");
scanf("%s",name);
for(i=0;name[i] !='\0';i++);
for(j=i-1;j>=0;j--)
{
if(name[j]==name[k])
{
flag=1;
k++;
}
else
{
flag=0;
break;
}
}
if(flag==1)
{
printf("it's palandrom");
}
else if(flag==0)
{
printf("it's not palandrom");
}
getch();
}
Program to find largest number between two given number using pointer variable.
#include <stdio.h>
#include <conio.h>
void main()
{
int a, b;
int *p,*q;
clrscr();
printf("Enter the value of a : ");
scanf("%d",&a);
printf("Enter the value of b : ");
scanf("%d",&b);
p=&a;
q=&b;
if(*p>*q)
{
printf(" %d is big ",*p);
}
else if(*p<*q)
{
printf(" %d is big ",*q);
}
else
{
printf(" Both are equal. ");
}
getch();
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
98
}
Program to interchange value of variable using pointer variable.
#include <stdio.h>
#include <conio.h>
void main()
{
int a, b;
int *p,*q,**r;
clrscr();
printf("Enter the value of a : ");
scanf("%d",&a);
printf("Enter the value of b : ");
scanf("%d",&b);
p=&a;
q=&b;
r=&p;
printf("The a is : %d\n",a);
printf("The p is : %u\n",p);
printf("The value of p is : %d\n",*p);
printf("The b is : %d\n",b);
printf("The q is : %u\n",q);
printf("The value of q is : %d\n",*q);
printf("The p is : %u\n",p);
printf("The r is : %u\n",r);
printf("The value of r is : %u\n",*r);
printf("The value of value of r is : %d\n",**r);
getch();
}
Program to print square and cube between 1 and 10 using pointer variable
#include<stdio.h>
#include<conio.h>
main()
{
int i, b, c;
int *d;
clrscr();
i=1;
d=&i;
while(*d<=10)
{
b=*d * *d;
c=*d * *d * *d;
printf("%3d %3d %3d\n",*d,b,c);
i=i+1;
}
getch();
}
Program to reverse a string using pointer variable
#include <stdio.h>
#include <conio.h>
void main()
{
char a[10];
int b;
char *p,*q;
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
99
int cnt=0, i;
clrscr();
printf("enter the value of a: ");
scanf("%s",a);
p=&a[0];
printf("%c\n",*p);
while(*p !='\0')
{
q=p;
p++;
q++;
}
q--;
printf("%c\n",*q);
while(*q)
{
printf("%c",*q);
q--;
}
getch();
}
Program to use structure for date type variable and arrays.
#include <stdio.h>
#include <conio.h>
struct mdate
{
int dd,mm,yy;
};
void main()
{
struct mdate s1;
static int no_of_days[12]={31,28,31,30,31,30,31,31,30,31,30,31};
clrscr();
printf("Enter the value for dd : \n");
scanf("%d",&s1.dd);
printf("Enter the value for mm : \n");
scanf("%d",&s1.mm);
printf("Enter the value for yy : \n");
scanf("%d",&s1.yy);
printf("The present date is :%d-%d-%d",s1.dd,s1.mm,s1.yy);
if((s1.dd==no_of_days[s1.mm-1]) && (s1.mm!=12))
{
s1.dd=1;
s1.mm=s1.mm+1;
s1.yy=s1.yy;
}
else if((s1.dd==no_of_days[s1.mm-1]) && (s1.mm==12))
{
s1.dd=1;
s1.mm=1;
s1.yy=s1.yy+1;
}
else
{
s1.dd=s1.dd+1;
s1.mm=s1.mm;
s1.yy=s1.yy;
}
printf("\nThe next date is :%d-%d-%d",s1.dd,s1.mm,s1.yy);
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
100
getch();
}
2nd Floor, Roank Palza, Tulsidham Char Rasta, Manjalpur Ph: 3290290
3rd Floor, Kanchanganga Appt., Nr. Chakli Circle, Race course Ph: 3249499
101