C Language Programming Code
SOFTWARE:- As per the industrial standard a digitized automatic process. Software is a collection of programs.
A program is a set of instruction which is
designed for a particular task ‘n’ number of program combined together like a
single entity. It is called software tool or software component.
Software is classified into
two types.
1. System software 2.
Application software
1. System software:- Which
software is designed for general purpose and which doesn’t contain any
limitations it is called system s/w.
Ex:
Operating System, Compiler etc.
2. Application software:- Which software is designed for particular purpose (task)
and which contains limitations it is called application s/w.
Ex:
MS Office, Oracle, Tally etc.
MS Office:- It is a
Microsoft package which maintain the information in document format.
Oracle:- It is a database which maintain the information in
tabular format.
Tally:-
It a application software which
maintain account information. A computer is a electronic device which accept
the data from user, according to user seeded. Instructions it produce result
(on) application,
who
using the application is called user, who developing the application is called
programmer.
Language:- A language is a communication
media between two parties.
Programming
languages:- A program language is a special kind of instruction
which is used to communicate with computer.
As a programmer if we know the programming language then
we can’t interact directly with computer because computer can’t understand
programming language code.
In above case we require a mediator called translator as
a programmer give the instruction to the programming language.
Translator will convert
programming language into binary form and according to the given instruction we
will get on application or result.
Programming
principles:-
- Structured programming
- Object oriented programming
The
Programming language support any one of these two principles.
Programming languages are
classified into 3 categories
1.
Low level
language (or) Machine Language (or) Binary language
2.
Middle level language
(or) Assembly language
3.
High level
language
MACHINE LEVEL LANGUAGE
The
only language understood by the computer without using a translation program. Programs
written in machine language can be executed very fast by the computer.
Advantages: - If we know this language we can directly interact with
the system, with out depending on any other applications.
ASSEMBLY LANGUAGE
One of the first steps in improving the program
preparation process was to substitute letter symbols-mnemonics for the numeric
operation codes of machine language. The language, which substitutes letters
and symbols for the numbers in the machine language program, is called an
assembly language or symbolic language.
The translator program that translates an assembly code into the
computer’s machine code is called assembler.
HIGH LEVEL
LANGUAGE
High level languages enable the programmer to write
instructions using English words and familiar mathematical symbols. So it becomes easier for his to concentrate
on the logic of his problem rather than getting involved in programming
details. Every instruction, which the
programmer writes in a high-level language, is translated into many machine
language instructions. This is
one-to-many translation and not one-to-one as in the case of assembly language.
Translators:- It is a system software when is used to convert a
programming language code into binary format.
Translators are classified
into 3 types
1. Compiler 2.
Interpreter 3. Assembler
Compiler:- A compiler is system software when converts
programming language code into binary format in a single step.
Interpreter:- An
interpreter is system software that translates programming language code into
binary format in step by step process.
Assembler:- An
assembler is a system software when is used to convert the assembly language
instruction into binary format in step by step process.
As per the performance wise always recommended to go for
compiler. As per the development recommended to go for an interpreter.
Differences
between Compiler and interpreter
Compiler
|
Interpreter
|
|
1. Compiler converts all
statements at a time, if errors are there, it displays all errors as a list. |
1. Interpreter converts
line by line, at the time of interpreting any error is there, it displays
that error. |
|
2. After Compiling the
whole program, if the program is error free then it will execute the program. |
2. After interpreting the
first line, if it is error free then it will execute that line. |
|
3. After Compilation, it
creates an executable file, using that executable file we can run the program
any number of times. |
3. It does not create any
executable file, every time we need to interpret the program. |
|
4. It is fast. |
4. It is slow. |
What is Debugging?
Bug is an error.
Debugging is a process of
tracing error or finding error.
INTRODUCTION ABOUT C
‘C’ is high level programming
language and c is structured programming language but structured programming is
not language but it is a programming approach of method.
Structured programming= Procedural approach +Modular
approach
WHAT IS C?
C
is a programming language developed at AT & T’s Bell Laboratories of USA in
1972. It was designed and written by a
man named Dennis Ritchie.
ADVANTAGES OF ‘C’
1.
Simple:- C programming language similar to
English and limited concepts are available.
2.
Mid-level:- C programming language can
supports low level programming instructions with the combination of high level
language that’s why it is called middle level programming language.
3.
Modularity:- It is a concept of designing an application in subprograms. i.e. procedure
oriented approach.
4.
Portability:- It is a concept of carrying the
instruction from one system to another system.
.c file
contain source code, we can edit also
.exe file contain application, only we
can execute.
Ø As per above observation when we are copying .exe file
to any other computer which contain windows operating system then it works
properly because the native code of application an OS is same.
Ø Some .exe file when we are copying to any other
computers which contain Unix/Linux OS, then it doesn’t works. So this behavior
is called platform dependency.
Ø When we are copying .exe file from one OS to another
OS then it works properly then it is called platform independent it doesn’t
works then it is called platform dependent.
Ø C programming language is a platform dependent machine
independent i.e. it depends on OS only not an hardware component of the
computer.
APPLICATION OF ‘C’
1. ‘C’ programming language can be used to design the
system software like OS and compilers.
2. By using ‘C’ programming language we can develop
application software like database and spread sheets.
3. Graphical related applications like mobile games and PC.
4. To evaluate any kind of mathematical equations.
CHARACTER SET
OF THE C LANGUAGE
This indicates group of
characters which are useful to write the programming statements.
C uses ASCII code character
set which range from -128 to 127.
Total ASCII code character
are 256(0 to 255)ASCII code characters are in English.
ASCII=American Standard
Code for Information Interchange
It
contains 3 parts.
Ø Alphabets: C language supports upper case letters (A to Z),
lower case letters from (a to z). But both are different. C is a case sensitive
language.
Ø Numeric
digits: C language contains the
numeric digits from 0 to 9.
Ø Special
Characters: The characters other than
alphabets and numeric digits are called as special characters.
Ex: !, @, #, ^, *, (, {, [, |, \, /.
WHITE SPACE
CHARACTERS
These are also called as
escape sequence characters. These are
the controlling characters. These
characters should start with \ , then followed by a single character.
|
White
space character name |
Usage |
|
\a |
Bell sound or beep sound |
|
\n |
New line |
|
\t |
Tab space |
|
\b |
Back space |
|
\r |
Return to starting of the
line |
Tokens of c:-
What is Token?
A token is a smallest
individual unit inside a program.
Tokens:-
1.
Keywords
2.
Constants
3.
Identifiers
4.
Data types
5.
Operators
6.
Separators
![]()
![]()
Ex: 1. int
a=10 ;
separator
Identifier
Operator
|
separator |
|
Identifier |
|
Operator |
KEY WORDS (OR) RESERVED
WORDS
Ø Keywords are the language related words having
specific meaning can be recognized by compiler.
Ø Keywords are reserved words the meaning of these words
can’t be changed by user.
Ø Keywords are predefined words.
Ø In C programming language total no. of keywords are
32.
These are:-
|
auto |
break |
case |
char |
Const |
|
continue |
default |
Do |
double |
Else |
|
enum |
extern |
float |
for |
Goto |
|
if |
int |
long |
register |
Return |
|
short |
signed |
sizeof |
static |
Struct |
|
switch |
typedef |
union |
unsigned |
Void |
|
volatile |
while |
|
|
|
1. Data types:- char,
int, float, double, void
2. Storage classes:- auto, static, register, extern
3. Qualifiers:- short,
long, signed, unsigned
4. Selection statements:- if, else, switch, case, default
5. Loops:- do-while,
while, for.
6. Jumping statements:- break, continue, goto
7. Variable:-
const, enum, return, sizeof, struct, typedef, union, volatile.
Ø All Keywords only lower case.
Ø C is a case-sensitive language.
ü
Constants:- It is a quantity which does not change its value
during the program execution. Constants are 4 types.
1.
Integer Constants: These are the
numbers without decimal point or exponent.
Ex: int a=10;
2.
Float constants: These are the
numbers with decimal point or exponent.
Ex: float
pie=3.14;
3. Single
Character Constants: It is any one of the single character enclosed in single
quotation.
Ex: char ch=’a’;
char section=’b’;
4.
String constants: Group of
characters enclosed with in double quotations.
Ex: char name[20]=
“Chandra”;
char nation[10]= “India”;
ü Variables:- It
is a value that changes its value during program execution.
Ø Variable is container which consist value.
Ø The variables which are used inside main function are
called local variables.
Ø The variables which are used out inside main function
are called global variables.
Ø All local variables must be declared the beginning of
main function.
Variables are 4
types.
1. Integer variables
2. Float variables
3. Single character variables
4. String variables.
Rules to write
variable names:
1. A variable name contains maximum of 30 characters.
2. A variable name includes alphabets and numbers, but it
must start with an alphabet.
3. It cannot accept any special characters, blank spaces
except under score( _ ).
4. It should not be a reserved word.
ü
Identifiers:-
ü What is an
Identifier?
An identifier is user defined word, which identify
data or instructions.
The rules for defining identifier:-
1. They should not be any space
between identifier.
2. Identifier should start with
an alphabet
or special
character (_).
3. Identifier should not
keywords.
4. Maximum length of identifier
is 30 character but preferable length is 8 characters.
5. An identifier can be defined
in uppercase or lowercase.
DATA TYPES
What is data type?
Data
type is an keyword used to allocate memory for data.
Data
types are broadly categorized into 3 types.
These
are
1. Primitive data types or Simple data types or
fundamental data types.
Ex:-
char, int, float, double.
2. Derived data types.
Ex:-
1. arrays, 2. pointers.
3. Structure data types or user defined data types.
Ex:-
1. struct 2. union 3. enum.
Primitive
data types
Each
primitive data type is a keyword used to allocate memory for one value.
These
are
|
Data type |
Range |
Bytes |
Format |
|
signed char |
-128 to +127 |
1 |
%c |
|
unsigned char |
0 to 255 |
1 |
%c |
|
signed int |
-32,768 to +32,767 |
2 |
%d |
|
unsigned int |
0 to 65,535 |
2 |
%u |
|
short int |
-128 to +127 |
1 |
%d |
|
short unsigned int
|
0 to 255 |
1 |
%u |
|
long signed int |
-2147483648 to+2147483647 |
4 |
%ld |
|
long unsigned int |
0 to 4294967295 |
4 |
%lu |
|
Float |
-3.4e38 to +3.4e38 |
4 |
%f |
|
Double |
-1.7e308 to +1.7e308 |
8 |
%lf |
|
long double |
-1.7e4932 to 1.7e4932 |
10 |
%Lf |

STRUCTURE
OF A ‘C’ PROGRAM
/* Comment line section *\ à Documentation optional
# header file section à when we use predefined functions
void main( )
{
Declaration part;àTo declare the variables which are used in the program.
Initialization part; à To initialize i.e. giving values to the variables.
Execution part; à To execute as output.
}
A C program starts with the include statement. This statement is used to link the header files
into our program. This statement should
start with # symbol.
Ex-: # include
<stdio.h>
stdio.h stands for standard input output . header file
Comment Line Section:
In order to give documentation for a program comment line
is includes. It is enclosed in between a /*
*\ because in the compilation process these lines are not includes.
Header file section:
‘C’ program consists of predefined functions for that
reason we should include the files in which they are defined. Which are saved
with .h as extension.
void main( ) :
The compilation and the running process is done with the
help of main( ). A ‘C’ program definitely requires main( ).
Declaration part:
This area is where we declare all the variables which are
used in the program.
Initialization part:
Here, we give values to the declared values.
Executable part:
The output is seen from the executable part. By using
output functions.
Programming rules:
A ‘C’ program should be written in
lower case. Every statement should end with; . The pair of { } should be
matched.
Compilation and Execution
process:
After writing the program we should compile by pressing
on the Compile option of Compile menu. This converts the text format that is
source code into Binary format which is called as object code. After that by
pressing Run option the output can be seen.
THE ‘C’ COMPILATION MODEL
Source Code

Assembly Code
![]()
Libraries
Object Code
![]()
Executable Code
SAMPLE
PROGRAMS
1. To print
some messages
#include<stdio.h>
#include<conio.h>
void
main( )
{
clrscr(
);
printf(“Welcome
to Aptech Solutions Institute”);
getch(
) ;
}
2. Write a
program to add two numbers?
#include<stdio.h>
#include<conio.h>
void
main ( )
{
int
a, b, c;
a=20;
b=30;
c=a+b;
printf(“C
= %d”, c);
getch
( );
}
3. Write a
program to add two numbers by taking values from keyboard?
#include<stdio.h>
#include<conio.h>
void
main ( )
{
int
a, b, c;
printf(“Enter
any two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“Addition
of two numbers is c= %d”, c);
getch();
}
4. Write a
program to calculate area and perimeter of a rectangle.
#include<stdio.h>
#include<conio.h>
main
( )
{
float
l, b, area, perimeter;
clrscr
( );
l=4.5;
b=3.5;
area=l*b;
perimeter=2*(l+b);
printf(“\n
The area of the rectangle is %f sq units”, area);
printf(“\n
The perimeter of the rectangle is %f units”, perimeter);
getch
( );
}
5. Write a
program area and a perimeter of a square by taking the side of a square.
#include
<stdio.h>
#include
<conio.h>
void
main ( )
{
float
side, area, perimeter;
clrscr(
);
printf(“\n
Enter side of the square”);
scanf(“%f
”, &side);
area=side*side;
perimeter=4*side;
printf(“\n
The area of a square is %f squints”, area);
printf(“\n
The perimeter of a square is %f units”, perimeter);
getch(
);
}
6. Write a
program to calculate area and circumference of the circle by taking radius of
the circle.
#include<stdio.h>
#include<conio.h>
main
( )
{
float
r, area,cir;
float
const pi =3.14;
clrscr
( );
printf(“\n
Enter radius of the circle”);
scanf(“%f
”, &r);
area=pie*r*r;
cir=2*pi*r;
printf(“\n
The area of the circle is %f sq units”, area);
printf(“\n
The circumference of the circle is %f units”,cir);
getch(
);
}
7. Write a
program to calculate employee salary.
#
include <stdio.h>
#
include <conio.h>
void
main( )
{
int eno;
float basic_salary,hra,da,gross;
char name[20];
clrscr( );
printf("\n Enter eno, name , basic
salary ");
scanf("%d %s %f", &eno, name, &basic_salary);
hra=basic_salary*15/100;
da=basic_salary*12/100;
gross=basic_salary+hra+da;
printf("\n Employ number is %d",eno);
printf("\n Employ name is %s",name);
printf("\n Basic is %f",basic_salary);
printf("\n Hra is %f",hra);
printf("\n Da is %f",da);
printf("\n Gross is %f",gross);
getch( );
}
OPERATORS
1.
Arithmetic
operators
2.
Relational
operators
3.
Logical operators
4.
Assignment
operators
5.
Increment or
decrement operators
6.
Conditional
operators
ü Arithmetic Operators
Arithmetic
operators are used to perform arithmetic operations like addition, subtraction,
multiplication, division and modular division.
|
Operator |
Name |
Meaning |
Example |
|
+ |
Plus |
Addition |
a+b |
|
- |
Minus |
Subtraction |
a-b |
|
* |
Asterisk |
Multiplication |
a*b |
|
/ |
Slash |
Division |
a/b |
|
% |
Modulator |
Remainder |
a%b |
Ex:-a=10, b=3
a+b = 10+3
=13
a-b =
10 - 3 = 7
a*b = 10 * 3 =30
a/b= 10 / 3
= 3
a%b=10%3=1
b%a =3%10=3
ü Relational operators:-
These operators are used to check the relation
between the values.
Note:-
When we used relational operators the output is seen in the form of 0 or 1. If
the relation is true the output will be in 1. If the relation is false the
output will be 0.
Ex:- a=10;
b=3;
Operator
|
Name |
Example |
Result |
|
< |
Less
than |
a<b |
False or 0 |
|
> |
Greater
than |
a>b |
True or 1 |
|
<= |
Less
than or equal to |
a<=b |
False or 0 |
|
>= |
Greater
than or equal to |
a>=b |
True or 1 |
|
== |
Equal
to |
a= =b |
False or 0 |
|
!= |
Not
equal to |
a!=b |
True or 1 |
ü
Logical
operators: logical operators are used
to combine two or more relational expressions. C language contains 3 logical operators.
|
Operator |
Name |
|
&& |
And |
|
|| |
Or |
|
! |
Not |
i.
&& :
(And)
Statement:- When all arguments are true then only the total
condition is true. Any one of the arguments is false the total condition is false.
Truth Table
(a>=b&&a>=c) a=6,b=5,c=2
|
Expression1 &&
Expression2 |
Result |
|
|
T |
T |
T |
|
T |
F |
F |
|
F |
T |
F |
|
F |
F |
F |
ii.
|| : (Or)
Statement:- When one of the argument is true the total condition
is true. If all the arguments are false then only the condition is false.
Truth Table
(a>=b||a>=c) a=3,b=5,c=2
|
Expression1
||
Expression2 |
Result |
|
|
T |
T |
T |
|
T |
F |
T |
|
|
|
|
|
F |
T |
T |
|
F |
F |
F |
iii.
! (Not):
Statement:-
This is the negative operator, we can place the ‘not’ operator before any one
of the condition. It returns the opposite result of the condition. i.e. It
converts true to false and false to
true.
Truth Table
!(a<=b) a=3,b=2
|
!
expression |
result |
|
T |
F |
|
F |
T |
ü
Assignment
operator: C language contains equal to (=) operator to
assign a value or expression into a variable.
Syntax: +=, -=, *=, /=, %=.
Ex:- a=10;
a+=10;//a=a+10;
ü
Increment and decrement operators:
1) ++ increment operator
2) -- decrement operator
Ø
Increment
operator (+ +)
Increment operator is used to increase the
value by 1.
§
Pre Increment( ++a)
First the value will be incremented,
and then the new value will be printed. Ex:-
printf(“%d”,++a);
§
Post Increment(a++)
First the value will be printed and then
the value will be incremented.
Ex:-
printf(“%d”,a++);
Ø
Decrement
operator ( - - )
Decrement
operator is used to decrease the value by 1.
§
Pre Decrement (--a)
If the value is decreased before execution it is
called as pre decrement.
Ex:- printf(“%d”,--a);
§
Post Decrement (a--)
If the value is decreased after the execution it is
called as post decrement.
Ex:- printf(“%d”,a--)
ü Conditional operators:- C language contains conditional operators (?, : ). By using conditional operators we can get
the output in the form of statements also. ?
and : are called as conditional or
ternary operators.
Syn: (condition) ?
printf(“value 1”) : printf(“ value 2”)
Ex:- (a>b) ? printf(“a is greater than b”):printf(“a is less than b”)
If the condition is
true then value1 will be returned, if the condition is false then value2 will
be returned
1. Write a program
using Arithmetic operators?
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
a, b;
clrscr(
);
printf(“\n
Enter a and b values \t:\t”);
scanf(“%d
%d”, &a, &b);
printf(“\n
The sum of %d & %d is %d”, a,b, a+b);
printf(“\n
The difference of %d & %d is %d”,
a,b, a-b);
printf(“\n
The product of %d & %d id %d”, a,b,
a*b);
printf(“\n
The division of %d & %d is %d”, a,b, a/b);
printf(“\n
The reminder of %d & %d is %d”, a,b, a%b);
getch(
);
}
2. Write a
program by using Relational operators.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void
main( )
{
int
a, b, c;
clrscr(
);
printf(“\n
Enter a and b values”);
scanf(“%d
%d”, &a,&b);
c=a>b;
printf(“%d”,c);
getch(
);
}
3. Write a
program by using logical operators.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void
main( )
{
int m, p, c, d, e;
clrscr( );
printf(“\n Enter the subject marks”);
scanf(“ %d %d %d”, &m, &p, &c);
d=(m>=35 && p>=35 && c>=35);
e=(m>=35 || p>=35 || c>=35);
printf(“\n The output using ‘and’ operator is %d”, d);
printf(“\n The output using ‘or’ operator is %d”, e);
getch( );
}
4. Write a
program using Increment and Decrement operator.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void
main( )
{
int
a,b,c,d,e;
clrscr(
);
printf(“\n
Enter the value of ‘a’”);
scanf(“%d”,
&a);
b=a++;
c=++a;
d=a--;
e=--a;
printf(“\n
The value of b=%d”,b);
printf(“\n
The value of c=%d”,c);
printf(“\n
The value of d=%d”,d);
printf(“\n
The value of e=%d”,e);
getch(
);
}
5. Write a
program to check whether the given number is even or odd using conditional
operator.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
n;
clrscr(
);
printf(“\n
Enter any value”);
scanf(“%d”,&n);
(n%2=
=0) ? printf(“\n The number is Even”) : (“\n The number is Odd”);
getch(
);
}
6. Write a
program to check whether the student is passed or failed, by using conditional
operator.
#include<stdio.h>
#include<conio.h>
main(
)
{
int
s1, s2, s3;
clrscr(
);
printf(“\n
Enter 3 subjects marks \t:\t”);
scanf(“%d
%d %d”, &s1, &s2, &s3);
(s1>=35&&s2>=35&&s3>=35)
? printf(“\n The student is passed”) : printf(“\n The student is failed”);
getch(
);
}
7. Write a
program to find the highest among the three given values.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
a,b,c;
clrscr(
);
printf(“\n
Enter any 3 values”);
scanf(“%d
%d %d”, &a, &b, &c);
(a>b&&a>c)
? printf(“ A is the highest value”) : (b>c) ? printf(“ B is the highest
value”) : printf(“ C is the highest value”);
getch(
);
}
8. Write a
program to take student roll no, student name, 6 subject marks and calculate
total and average for the marks.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
rollno, s1, s2, s3, s4, s5, s6, total;
float
avg;
char
name[20];
clrscr(
);
printf(“\n
Enter rollno”);
scanf(“
%d”, &rollno);
printf(“\n
Enter name of the student”);
scanf(“
%s”, &name);//scanf(“%s”,name);
printf(“\n
Enter subject marks”);
scanf(“
%d %d %d %d %d %d”, &s1, &2, &s3, &s4, &s5, &s6);
total=s1+s2+s3+s4+s5+s6;
avg=total*100/600;
printf(“\n
Rollno=%d”, rollno);
printf(“\n
Name=%s”, name);
printf(“\n
Total=%d”, total);
printf(“\n
Avg=%f”, avg);
getch(
);
}
Priority
of operators:-
|
SNO |
Operator |
|
1 |
() |
|
2 |
!,+,-(unary operator) |
|
3 |
*,/,% |
|
4 |
+,-(binary operator) |
|
5 |
<,>,<=,>=, |
|
6 |
==,!= |
|
7 |
&& |
|
8 |
|| |
|
9 |
?: |
|
10 |
= |
CONDITIONAL
STATEMENTS
Ø
Conditional statements:- The statements which are executed according to some
condition are called as conditional statements.
ü
If:-
Statement: This statement is used to perform conditional
operations.
Syntax1:
if(condition)
statement1;
If the condition is true then statement1 will be
executed.
If the condition is false
then it will not execute statement1.
Syntax 2:
if(condition)
{
statement1;
statement2;
}
If the condition is true then
statement1 and statement2 will be executed.
ü If-else:-
Syntax 1:
if(condition)
statement1;
else
statement2;
If the condition is true
then statement1 will be executed, if the condition is false then statement2
will be executed.
Syntax 2:
if( condition)
{
statement 1;
statement 2;
}
else
{
statement 3;
statement 4;
}
If the condition is true then
statement1 and statement2 will be executed.
If the condition is false then statement3 and statement4 will be
executed.
ü Nested if:-
Statement:- If condition1 is true, then it will check condition2,
if it is true then statement1 will be executed.
If condition1 is false it will not check condition2.
Syntax :
if(condition1)
{
if(condition2)
{
statement1;
}
}
1. Write a
program to check whether a citizen is eligible for voting or not.
#include<stdio.h>
#include<conio.h>
main(
)
{
int
age;
clrscr(
);
printf(“\n
Enter the age of the citizen”);
scanf(“%d”,
&age);
if(age>18)
{
printf(“\n
Eligible for voting”);
}
else
{
printf(“\n
Not eligible for voting”);
}
getch(
);
}
2. Write a
program to check whether the entered year is leap year or not.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
year;
clrscr(
);
printf(“\n
Enter the year”);
scanf(“%d”,
&year);
if((year%4==0&&year/100!=0)||year/400==0);
printf(“\n Leap year”);
else
printf(“\n Non leap year”);
getch( );
}
3. Write a
program to check the least among the three given values.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
a,b,c;
clrscr(
);
printf(“\n
Enter any 3 values”);
scanf(“%d
%d %d”, &a,&b,&c);
if(a<b&&a<c)
printf(“\n %d is the least value”, a);
elseif(b<c)
printf(“\n %d is the least value”, b);
else
printf(“\n %d is the least value”, c);
getch( );
}
4. Write a
program to check whether the given number is divisible by 2, 4 & 6.
#include<stdio.h>
#include<conio.h>
main(
)
{
int
n;
clrscr(
);
printf(“\n
Enter any value”);
scanf(“%d”,&n);
if(n%2=
=0 && n%4= =0 && n%6= =0)
{
printf(“\n
The number is divisible by 2, 4 & 6);
}
else
{
printf(“\n
The number is not divisible by 2, 4 & 6”);
}
getch(
);
}
LOOPS
Looping:- The
process of executing a block of code repeatedly is called as looping.
There are 3 types of loops
in ‘C’ language.
1)
for loop
2)
while loop
3)
do while loop
All the three loops are
used for same process but there syntax is different.
All the three loops have 3
steps in common.
1)
Initialization:- It is the starting point of the loop process.
2)
Condition:- In this step logical test is applied. It is true the
block of code is executed. Till the condition fails.
3)
Updating:- In
order to proceed or stop the loop increment or decrement is required.
FOR LOOP
It is used to execute a set
of statements repeatedly as long as the given condition is true.
Syntax:-
for(initial
value ; test condition ; updating)
{
statements; //body
of for loop
}
When the for
loop is executing for the very first time the initial value is stored in
the given variable. Then the condition will be tested. If it is true, the
statements will be executed. After executing the last statement the control
will return back to the for loop. Then
the value will be incremented / decremented. Again the condition is tested, if
it is false the control will come out of the for loop.
Ex:- for(i=1;
i<=10; i++)
1) Write a
program to print the name 10 times using ‘for loop’.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
i;
clrscr(
);
for
(i=1;i<=10;i++)
{
printf(“\n APTECH INSTITUTE”);
}
getch(
);
}
2) Write a
program to print the numbers among 100 to 200.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
i;
clrscr(
);
for(i=100;i<=200;i++)
{
printf(“\n %d”, i);
}
getch(
);
}
3) Write a
program to print the even numbers from 10 to 50.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
i;
clrscr(
);
for(i=10;i<=50;i++)
{
if(i%2= =0)
{
printf(“\n
%d”, i);
}
}
getch(
);
}
4) Write a
program to print odd numbers from 100 to 200.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
i;
clrscr(
);
for(i=100;i<=200;i++)
{
if(i%2!=0)
{
printf(“%d”,
i);
}
}
getch(
);
}
5) Write a
program to print the Multiplication table of the given number.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
n,i,r;
clrscr(
);
printf(“\n
Enter any number”);
scanf(“%d”,
&n);
for(i=1;i<=10;i++)
{
r =n*i;
printf(“%d*%d=%d\n”,n,
i, r);
}
getch(
);
}
6) Write a
program to find the factorial of a given number.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
i, fact=1, n;
clrscr(
);
printf(“\n
Enter any number”);
scanf(“%d”,
&n);
for(i=1;i<=n;i++)
{
fact=fact*i;
}
printf(“\n
Factorial of %d=%d”, n, fact);
getch(
);
}
WHILE LOOP
While statement:
It
is used to execute a set of statements repeatedly as long as the given
condition is true.
Syntax:
while (condition)
{
statements; //body of while loop
------------;
}
First the condition is tested, if it is true the body
of the while loop will be executed first time, again the control is transferred
back to while loop and checks the condition, If it is false the control will
come out of the while loop.
1)
Write a
program to print the numbers divisible by 5 among 50 to 100.
#include<stdio.h>
#include<conio.h>
void main( )
{
int i=50;
clrscr( );
while(i<=100)
{
if(i%5 = =0)
printf(“%d”, i);
i++;
}
getch( );
}
2)
Write a
program to sum the digits of a given number.
#include<stdio.h>
#include<conio.h>
void main( )
{
int i, n, rem, sum=0;
clrscr( );
printf(“\n
Enter any 3 digit number”);
scanf(“%d”,
&n);
while(n!=0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
if(sum<0)
sum=-sum;
printf(“\n
The sum of digits of given number is %d”, sum);
getch( );
}
3)
Write a
program to reverse the given number.
#include<stdio.h>
#include<conio.h>
void main( )
{
int n, rev=o, rem;
clrscr( );
printf(“\n
Enter any number”);
scanf(“%d”,
&n);
while(n!=0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
printf(“\n
The reverse of the given number is %d”, rev);
getch( );
}
4)
Write a
program to test for given number is Palindrome.
#include<stdio.h>
#include<conio.h>
void main( )
{
int n, rem, rev=0, temp;
clrscr( );
printf(“\n
Enter any number”);
scanf(“%d”,
&n);
temp=n;
while(0<n)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
printf(“\n
The reverse of the number is %d”, rev);
if(rev==temp)
printf(“\n
The number is a Palindrome number”);
else
printf(“\n
The number is not a Palindrome number”);
getch( );
}
5)
Write a
program to test for Armstrong number.
#include<stdio.h>
#include<conio.h>
void main( )
{
int n, rem, sum=0, temp;
clrscr( );
printf(“\n
Enter any number”);
scanf(“%d”,
&n);
temp=n;
while(n>0)
{
rem=n%10;
sum=sum+rem*rem*rem;
n=n/10;
}
if(sum==temp)
printf(“\n
The number is Armstrong number”);
else
printf(“\n
The number is not a Armstrong number”);
getch( );
}
DO WHILE LOOP
Do while loop:- This statement executes a set of statements as long as the condition is
true.
Syntax:
do
{
statements;
statements;
}while(condition);
This is similar to while
loop, but the difference is this loop will execute the statements at least
once.
1)
Write a
program using do while loop.
#include<stdio.h>
#include<conio.h.
void main( )
{
int s1, s2, s3, tot;
char c;
do
{
printf(“\n Enter subject
marks”);
sanf(“%d %d %d”, &s1,
&s2, &s3);
tot=s1+s2+s3;
printf(“\n Total=%d”, tot);
printf(“\n Do you want to
try again”);
scanf(“%c”, &c);
}while(c==’y’||c==’Y’);
getch( );
}
2)
Write a
program to print the natural numbers of the given number.
# include <stdio.h>
# include <conio.h>
void main()
{
int n,i;
clrscr();
printf("\n Enter a number
");
scanf("%d",&n);
i=1;
do
{
printf("\t%d",i);
i=i+1;
}
while(i<=n);
getch();
}
NESTED FOR LOOP
In order to get the output
in the form of rows and columns we use nested for loops. If the outer loop
condition is true it enters into the inner loop. Till the outer loop condition
is false the looping process is continued.
1)
Write a
program to get the *
* *
* * * output
as using nested for loop.
*
* * *
#include <stdio.h>
#include<conio.h>
main( )
{
int n,i,j;
clrscr( );
printf(“\n Enter the value of n”);
scanf(“%d”, &n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf(“*”);
}
printf(“\n”);
}
getch( );
}
2)
Write a
program to get the output as 1
1
2 using nested for loop.
1 2
3
#include<stdio.h>
#include<conio.h>
main( )
{
int n, i, j;
clrscr( );
printf(“\n Enter the value of n”);
scanf(“%d”, &n);
for(i=1;i<=n;i++);
}
for(j=1;j<=i;j++)
{
printf(“%d”, j);
}
printf(“\n”);
}
}
3)
Write a
program to get the output in the form of
1
2 2 by using nested loop.
3 3 3
#include<stdio.h>
#include<conio.h>
main( )
{
int n, i, j;
clrscr( );
printf(“\n Enter the value of n”);
scanf(“%d”, &n);
for(i=1;i<=n;i++);
}
for(j=1;j<=i;j++)
{
printf(“%d”, i);
}
printf(“\n”);
}
getch( );
}
4)
Write a
program to get the output in the form of
1 2 3 4
1 2 3 by
using nested for loop.
1 2
1
#include<stdio.h>
#include<conio.h>
main( )
{
int n, i, j;
clrscr( );
printf(“\n Enter the value of n”);
scanf(“%d”, &n);
for(i=n;i>=1;i--);
}
for(j=1;j<=i;j++)
{
printf(“%d”, j);
}
printf(“\n”);
}
getch( );
}
6)
1 1 2 1 2
3 1 2
3 4 1 2
3 4 5 1 2
3 4 1 2
3 1 2 1
Write a program to get the
output in the form of by using nested for loop.
# include <stdio.h>
# include <conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf("%3d",j);
printf("\n");
}
for(i=4;i>=1;i--)
{
for(j=1;j<=i;j++)
printf("%3d",j);
printf("\n");
}
getch();
}
GOTO STATEMENT
goto statement:
It is used to transfer the control from one place to another place in the
program. It is also called as
unconditional jumping statement
Syntax-: goto <label name>;
Ex:- goto
print;
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
i=1;
clrscr(
);
aptech:
printf(“%d”,
i);
i++;
if(i<=10)
goto
aptech;
getch(
);
}
CONTINUE STATEMENT
Continue statement: It is used to transfer the control to the beginning of the looping
statements. We have to use this continue statement inside a switch statement or
inside any looping statements (for, while, do while)
Ex: continue;
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
i;
clrscr(
);
for(i=1;i<=100;i++)
{
if(i%10=
=0)
continue;
printf(“%d”,i);
}
getch(
);
}
SWITCH STATEMENT
It is used to execute one of the options from
no. of options. It is also called as
multi branching statement.
switch(expression)
{
case
value1:
statements;
case value2:
statements;
-------------------;
--------------------;
default:
statements;
}
The expression value may be int or character type.
The switch statement evaluates the expression.
It will select one of the cases based on expression. It will execute default statements when no
case is selected.
BREAK STATEMENT
It
is used to exit from a looping statement.
We can use this in for, while , do while, and switch statement.
Ex:- break;
1. Write a
program to print the name of the day using switch case.
#include<stdio.h>
#include<conio.h>
void
main( )
{
int
n;
clrscr(
);
printf(“\n
Enter any number”);
scanf(“
%d”, &n);
switch(n)
{
case
0:
printf(“\n
The name of the day is Sunday”);
break;
case
1:
printf(“\n
The name of the day is Monday”);
break;
case
2:
printf(“\n
The name of the day is Tuesday”);
break;
case
3:
printf(“\n
The name of the day is Wednesday”);
break;
case
4:
printf(“\n
The name of the day is Thursday”);
break;
case
5:
printf(“\n
The name of the day is Friday”);
break;
case
6:
printf(“\n
The name of the day is Saturday”);
break;
default:
printf(“\n
Invalid number”);
}
getch( );
}
2. Write a
program to enter date print the name of the day using switch case.
#include<stdio.h>
#include<conio.h>
void main()
{
int dd,mm,yy,nleap;
long int dp;
clrscr();
printf(“Enter year:”);
scanf(“%d”,&yy);
if(yy<=0)
{
printf(“\n Invalid year”);
getch();
goto END;
}
printf(“\n Enter month:”);
scanf(“%d”,&mm);
if(mm<1||mm>12)
{
printf(“\n Invalid month”);
getch();
goto END;
}
printf(“\n Enter day number:”);
scanf(“%d”,&dd);
if(dd<1||dd>31)
{
printf(“\n Invalid day number”);
getch();
goto END;
}
if((mm==4||mm==6||mm==9||mm==11)&&dd>30)
{
printf(“\n Invalid date”);
getch();
goto END;
}
if(yy%4==0&&yy%100!=0||yy%400==0)
{
if(mm==2&&dd>29)
{
printf(“\n Invalid Date”);
getch();
goto END;
}
}
else
{
if(mm==2&&dd>28)
{
printf(“\n
Invalid Date”);
getch();
goto
END;
}
}
nleap=(yy-1)/4-(yy-1)/100+(yy-1)/400;
dp=(yy-1)*365+nleap;
switch(mm)
{
case 12: dp+=30;
case 11: dp+=31;
case 10: dp+=30;
case 9: dp+=31;
case 8: dp+=31;
case 7: dp+=30;
case 6: dp+=31;
case 5: dp+=30;
case 4: dp+=31;
case 3: dp+=28;
case 2: dp+=31;
case 1: dp+=dd;
}
if((yy%4==0&&yy%100!=0||yy%400==0)&&mm>2)
dp++;
printf(“\n %d-%d-%d weekday is:”,dd,mm,yy);
switch(dp%7)
{
case 0: printf(“Sunday”);
break;
case 1: printf(“Monday”);
break;
case 2: printf(“Tuesday”);
break;
case 3: printf(“Wednesday”);
break;
case 4: printf(“Thursday”);
break;
case 5: printf(“Friday”);
break;
case 6: printf(“saturday”);
break;
}
getch();
END:
}
3. Write a
program to check whether the enter alphabet is vowel or consonant.
#include<stdio.h>
#include<conio.h>
void
main( )
{
char
ch;
clrscr(
);
printf(“\n
Enter any Alphabet”);
scanf(“%c”,
&ch);
switch(ch)
{
case
‘a’: printf(“\n It is a vowel”);
beak;
case
‘e’: printf(“\n It is a vowel”);
beak;
case
‘i: printf(“\n It is a vowel”);
break;
case
‘o’: printf(“\n It is a vowel”);
beak;
case
‘u’: printf(“\n It is a vowel”);
break;
default:
printf(“\n
It is a consonant”);
}
getch(
);
}
4. Write a
program Arithmetic operator according to the entered choice.
#include<stdio.h>
#include<conio.h>
main(
)
{
int
a, b;
char
op;
printf(“\n
enter the operator symbol”);
scanf(“%s”,
&op);
printf(“\n
enter a & b values”);
scanf(%d
%d”, &a,&b);
switch(op)
{
case
‘+’:
printf(“\n
The sum of %d and %d is %d”, a,b, a+b);
break;
case
‘-‘:
printf(“\n
The difference of %d and %d is %d”, a,b, a-b);
break;
case
‘*’:
printf(“\n
The product of %d and %d is %d”, a,b, a*b);
break;
default:
printf(“\n
Invalid operator”);
}
getch(
);
}
5.
Write a
program Enter any number to display in words format?
#include<stdio.h>
#include<conio.h>
void main()
{
int n,rev=0,count=0;
clrscr();
printf(“Enter a Value:”);
scanf(“%d”,&n);
while(n)
{
rev= rev*10+n%10;
n=n/10;
++count;
}
while(rev)
{
switch(rev%10)
{
case 0: printf(“ZERO”);
break;
case 1: printf(“ONE”);
break;
case 2: printf(“TWO”);
break;
case 3: printf(“THREE”);
break;
case 4: printf(“FOUR”);
break;
case 5: printf(“FIVE”);
break;
case 6: printf(“SIX”);
break;
case 7: printf(“SEVEN”);
break;
case 8: printf(“EIGHT”);
break;
case 9: printf(“NINE”);
break;
}
Rev=rev/10;
--count;
}
while(count>0)
{
printf(“ZERO”);
--count;
}
getch();
}
ARRAYS
An array is contiguous area in the memory referred by
a common name. The array allows the
storage of a number of data values in one variable. Each array element i.e. each individual data
item is referred by specifying the array name followed by one or more
subscripts. Each subscript is enclosed
with square brackets. Each subscript
indicates the position of the element in the array. Arrays are divided into 2 types.
1)
Single
dimensional arrays. or One dimensional arrays
2)
Multi dimensional arrays
1) One
dimensional arrays:- The array which is using only 1 subscript is
known as one dimensional array. In one
dimensional array the elements are represented in single row or single column.
Syntax:- Data_type variable_name[subscript]
Ex: int a[5]={40, 50, 70,90,100};
float b[4]={20.5, 40.9, 45.7, 23.8};
char c[6]={‘A’,’P’,’T’,’E’,’C’,’H’};
The above declaration states that ‘a’ is an array
variable in which we can store 5 values of integer data type. Similarly ‘b’ is
an array variable in which we can store 4 values of float data type. Similarly
‘c’ is an array variable in which we can store 6 characters.
2) Two
dimensional arrays: The array which is using two subscripts is known
as 2 – dimensional array.
Syntax:-
Data_type variable_name [subscript1][subscript2]
Ex:-
int a[2][3]={{1,2,3},{4,5,6}};
The
above declaration states that ‘a’ is a two dimensional array variable in which
the values are stored in 2 rows and in 3 columns.
Ø
One dimensional Array
1)
Write a program to access the elements from an Array.
#include<stdio.h>
#include<conio.h>
void main( )
{
int
a[5]={40,50,60,90,100};
int
i;
clrscr(
);
for(i=0;i<=4;i++)
{
printf(“%d”, a[i]);
}
getch(
);
}
2)
Write a program to access the elements from an Array
and array elements are taking by the keyboard.
#include<stdio.h>
#include<conio.h>
void main( )
{
int
a[5];
int
i;
clrscr(
);
printf(“Enter
any five elements:”);
for(i=0;i<5;i++)
{
scanf(“%d”,&a[i]);
}
printf(“Array
elements are:\n”);
for(i=0;i<=4;i++)
{
printf(“%d”, a[i]);
}
getch(
);
}
3)
Write the program to print the name from an array.
#include<stdio.h>
#include<conio.h>
void main( )
{
char
c[5]={‘A’,’P’,’T’,’E’,’C’,’H’};
int
i;
clrscr(
);
for(i=0;i<5;i++)
{
printf(“%c”,
c[i]);
}
getch(
);
}
4)
Write a program to add the values of two arrays.
#include<stdio.h>
#include<conio.h>
void main( )
{
int
a[3]={100,102,110};
int
b[3]={60,80,90};
int
i;
clrscr(
);
printf(“\n
Addition of two arrays”);
for(i=0;i<=2;i++)
{
printf(“%d+%d=%d”,
a[i],b[i], a[i]+b[i]);
}
getch(
);
}
5)
Write to print
the entered string in reverse order.
#include<stdio.h>
#include<conio.h>
void main( )
{
char string[6];
int i;
clrscr( );
printf(“\n Enter any string”);
gets (strings);
printf(“\n Reverse of a string”);
for(i=6;i>=0;i--)
{
printf(“%c”,
string[i]);
}
getch( );
}
6)
Write a program
to find the no. of times a character appears in a string.
#include<stdio.h>
#include<conio.h>
void main( )
{
char string[10], f;
int i, c=0;
clrscr( );
printf(“\n Enter the string”);
gets(string);
printf(“\n Enter a letter to find in the
string”);
scanf(“%c”, &f);
for(i=0;i<=9;i++)
{
if(string[i]==f)
c++;
}
printf(“\n The letter %c appears %d
times in the %s”, f, c, string);
getch( );
}
7)
Write a program
to print the name of a city and pincode using arrays.
#include<stdio.h>
#include<conio.h>
void main( )
{
char city[8]={‘N’,’A’,’L’’G’,’O’,’N’,’D’,’A’};
int pin[6]={5,0,8,0,0,1};
int i;
clrscr( );
for(i=0;i<8;i++)
{
printf(“%c”, city[i]);
}
printf(“-“);
for(i=0;i<6;i++)
{
printf(“%d”, pin[i]);
}
getch();
}
8)
Write a program
to print the no. of days in a month.
#include<stdio.h>
#include<conio.h>
void main( )
{
int
month[12]={1,3,5,7,8,10,12,4,6,9,11,2};
int i, mm;
clrscr( );
printf(“\n Enter number of month”);
scanf(“%d”, &mm);
for(i=0;i<=11;i++)
{
if(mm= =month[i])
goto compare;
}
printf(“\n Invalid month”);
exit (0);
compare:
if(“month (%d) contains 28 days”,
month[i]);
if(i+1<8)
printf(“month(%d)contains 31 days”,
month[i]);
if(i+1>7&&i+1!=12)
printf(“month (%d) contains 30 days”,
month[i]);
getch( );
}
Ø
Two dimensional Array
1)
Write a program
to access the elements of a two dimensional array.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int i, j;
clrscr( );
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf(“%d”,
a[i][j]);
}
printf(“\n”);
}
getch( );
}
2)
Write a program
to enter the values of matrix in the output and display
them.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[3][3];
int I,j;
clrscr( );
printf(“\n Enter values into3*3
matrix”);
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
scanf(“%d”,
&a[i][j]);
}
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf(“%3d”,
a[i][j]);
}
printf(“\n”);
}
getch( );
}
3)
Write a program
to add 2 matrices.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[2][2], b[2][2], c[2][2];
int i,j;
clrscr( );
printf(“\n Enter the values in ‘a’
matrix”);
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
scanf(“%d”,
&a[i][j]);
}
}
printf(“\n Enter the values of
‘b’ matrix”);
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
scanf(“%d”,
&b[i][j]);
}
}
printf(“\n Addition of matrices”);
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf(“%d”,
c[i][j]);
}
printf(“\n”);
}
getch( );
}
4)
Write a program
to enter rows and columns into matrix and output display them.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10][10];
int i, j, r, c;
clrscr( );
printf(“\n Enter
no. of Rows and Columns”);
scanf(“%d %d”,
&r, &c);
printf(“\n Enter
the values into matrix”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(“%d”,
a[i][j]);
}
printf(“\n”);
}
getch( );
}
5)
Write a program
to convert transpose matrix of the enter
rows and columns into matrix and display transpose matrix.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10][10],t[10][10];
int i, j, r, c;
clrscr( );
printf(“\n Enter
no. of Rows and Columns”);
scanf(“%d %d”,
&r, &c);
printf(“\n Enter
the values into matrix”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
t[j][i]=a[i][j];
}
}
printf(“Transpose matrix is:\n”);
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
printf(“%d”, t[i][j]);
}
printf(“\n”);
}
getch( );
}
5)
Write a program
multiplication of matrix.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a[10][10], b[10][10], c[10][10];
int m1,n1,m2,n2,i, j, k;
printf(“\n Enter
the matrix ‘a’ no. of Rows and Columns”);
scanf(“%d %d”,
&m1, &n1);
printf(“\n Enter the values in ‘a’
matrix”);
for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++)
{
scanf(“%d”,
&a[i][j]);
}
}
printf(“\n Enter
the matrix ‘b’ no. of Rows and Columns”);
scanf(“%d %d”,
&m2, &n2);
printf(“\n Enter the values in ‘b’
matrix”);
for(i=0;i<m2;i++)
{
for(j=0;j<n2;j++)
{
scanf(“%d”,
&b[i][j]);
}
}
printf(“Matrix multiplication Logic: ”);
if(n1==m2)
{
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
c[i][j]=0;
for(k=0;k<=n1;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
}
else
{
printf(“Matrix ‘a’ columns and Matrix
‘b’ rows is not equal so matrix multiplication is not possible ”);
getch();
exit(0);
}
printf(“\n
Product of two matrices:”);
for(i=0;i<m1;i++)
{
for(j=0;j<n2;j++)
{
printf(“%3d”,c[i][j]);
}
printf(“\n”);
}
getch( );
}
STRING
FUNCTIONS
A character array is defined as a string.
A group of characters is called a string. We cannot handle with string same
like integers or real values.
For
example, if you want to compare an integer value with another int value.
We
can do that by using = = operator. But the same procedure cannot be applied for
strings.
In
order to handle with strings there are same string handling functions.
1) strlen( ):- This function is
used to find the length of a string.
Syntax:- strlen(string);
Note:- When we are using string functions we
have to include a header file
<string.h>
2) strcpy( ):- This function
copies a string from one string variable to another string variable.
Syntax:- strcpy(target_string , source_string);
3) strcat( ): (String concatenation)
This function adds a string at the end of
another string
Syntax:- strcat(string1,stirng2);
4) strcmp( ): (String
comparison)
This
compares one string with another string, if two strings are equal this function
returns 0, else it returns the numeric difference between the non-matching characters.
Syntax:-
strcmp(string1, string2);
5) stricmp( ): This function is similar to strcmp, but this
function ignores the case sensitivity.
Syntax:- stricmp(string1,
string2);
6) strrev( ): This function reverses the given string
Syntax:- strrev(string);
7) strupr( ): This function
converts the given string into upper case(capital letters)
Syntax:- strupr(string);
8) strlwr( ): This function converts the given string into
lower case.
Syntax:- strlwr(string);
Single
character:-
1) toupper( ) :- This
function converts a single character to upper case.
Syntax:- toupper(character);
2) tolower( ) :- This function
converts a single character to lower case.
Syntax:- tolower(character);
Note:- when we are using single character
functions we have to include a header file <ctype.h>
1.
Write a program
to find the length of an entered string.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void
main( )
{
int length;
char string[20];
clrscr( );
printf(“\n Enter any string”);
gets(string);
length=strlen(string);
printf(“\n The length of the string=%d”, length);
getch( );
}
2)
Write a program to copy a string into another string.
#
include <stdio.h>
#
include <conio.h>
#
include <string.h>
void
main( )
{
char name[20],name1[20];
clrscr( );
printf("\n Enter your string ");
scanf("%s",name);
strcpy(name1,name);
printf("\n The given string is %s",name);
printf("\n The new string is %s",name1);
getch( );
}
3)
Write a program to compare one string to another
string.
#
include <stdio.h>
#
include <conio.h>
#
include <string.h>
void
main( )
{
char name[20],name1[20];
clrscr( );
printf("\n Enter your first string ");
scanf("%s",name);
printf("\n Enter your second string ");
scanf("%s",name1);
if(strcmp(name,name1)= =0)
printf("\n Two strings are equal
");
else
printf("\n Two strings are not
equal");
getch( );
}
4)
Write a program to print the reverse string of the
given string.
#
include <stdio.h>
#
include <conio.h>
#
include <string.h>
void
main( )
{
char name[20];
clrscr( );
printf("\n Enter your first string ");
scanf("%s",name);
printf("\n The given string is %s",name);
strrev(name);
printf("\n The reverse string is %s",name);
getch( );
}
5)
program to input a string and convert it into upper case and lower
case
#
include <stdio.h>
#
include <conio.h>
#
include <string.h>
void
main( )
{
char name[20];
clrscr( );
printf("\n Enter your string ");
scanf("%s",name);
printf("\n The given string is %s",name);
strupr(name);
printf("\n the string in upper case
is %s",name);
strlwr(name);
printf("\n The string in lower case
is %s",name);
getch( );
}
6)
Write a program to convert uppercase string to lower
case string by using
Ascii code.
#include<stdio.h>
#include<conio.h>
#include<string.h>
main(
)
{
char
str[30];
int
i=0;
clrscr(
);
printf(“\n
Enter any string”);
gets(str);
while(str[i]!=’\0’)
{
if(str[i]>=’A’&&str[i]<=’Z’)
str[i]=str[i]+32;
i++;
}
printf(“\n
Converted given string from uppercase to lowercase is %S”, str);
getch(
);
}
7)
Single Character Functions
//toupper(),
tolower()
#
include <stdio.h>
#
include <conio.h>
#
include <ctype.h>
void
main( )
{
char name[20];
int i=0;
clrscr( );
printf("\n Enter a string ");
scanf("%s",name);
while(name[i]!='\0')
{
printf("%c",toupper(name[i]));
i++;
}
getch( );
}
8)
Write a program using all sting functions.
#
include <stdio.h>
#
include <conio.h>
#
include <string.h>
void
main( )
{
char str1[20],str2[20];
int ch=0,len;
clrscr( );
while(ch<6)
{
printf("\n 1.STRLEN ");
printf("\n 2.STRCPY ");
printf("\n 3.STRCMP ");
printf("\n 4.STRCAT ");
printf(“\n 5. STRREV ”);
printf("\n 6.EXIT ");
printf("\n Enter your choice ");
scanf("%d",&ch);
switch(ch)
{
case
1:
printf("\n Enter your name ");
scanf("%s",str1);
len=strlen(str1);
printf(“Length
of the string is:%d”,len);
break;
case
2:
printf("\n
Enter Source string ");
scanf("%s",&str2);
strcpy(str1,str2);
printf("\n
The copied string is: %s",str1);
break;
case
3:
printf("\n
Enter your first string ");
scanf("%s",str1);
printf("\n
Enter your second string ");
scanf("%s",str2);
strcmp(str1,str2);
break;
case
4:
printf("\n
Enter your first name ");
scanf("%s",str1);
printf("\n
Enter your last name ");
scanf("%s",str2);
strcat(str1,str2);
printf("\n
Your full name is %s",str1);
break;
case
5:
printf(“Enter
any string:”);
scanf(“%s”,str1);
strrev(str1);
printf(“Reverse
string is:%s”,str1);
break;
case
6:
exit(0);
break;
}
printf(“Please try again:”);
scanf(“%d”,&ch);
}
getch( );
}
FUNCTIONS

What is function?
Ø A function is self contained
block which contain or consist set of instructions
Ø A function is reusable module.
Ø A function is a sub program
within a program.
Ø A function is a named block.
What is an advantage of use function?
1.
Modularity:- Dividing programming instructions according its
operations into small programs.
2.
Reusability:- Functions are reused in one or more than one
program.
i.e Write once use many
times.
3.
Simple:- Easy to understand application, functionality.
4.
Efficiency:- With reusability the size of the program reduced. So
efficiency of the program is increased.
A function is a set of
statements that performs a specific task.
Functions are 2 types
1)
Pre defined
functions or Standard functions
2)
User defined
functions
1)
Pre
defined Functions:-
Ø
Functions
developed by some other user called predefined functions.
Ø These functions which are already defined (in built)
along with C are called as pre defined functions.
Ex:- printf( ),
scanf( ),puts(),gets(), sqrt(),pow( ), strlen( ), strcpy( ), toupper( ),……
2)
User
defined functions:- These functions defined by the user in order
to work with complex program and to develop the efficiency of the program are
called as user defined functions. In order to define a function we have 3
types.
ü
Function
definition
ü
Function
prototype
ü
Invoking a
function
ü
Function definition:-
a) Function
heading
i.
Return type:- Return
is called as data type mention according to the type of value returned from the
function.
Note:- When there is no return statement we should mention
void as a default return type.
ii.
Function name:- Here we mention the name of a function. It is just like a variable name
iii.
Specification of parameters: - specifying the number of values or variables taken by
the called function from main program.
Note:-The parameters mentioned in the main program for calling a function are called as
actual parameters.
The
parameters mentioned in the function which are received from the main program
are called formal parameters.
b) Block of
code:- The code which is written with
in the braces of a function is called as block of code.
c) Return
statement:- This is the last
statement of a function it is to written a value from the user defined function
to the main program.
ü
Function Prototype
It
is declared in the main program about the function.
Note:-Function prototype is optional if the function is defined before the
main. It is compulsory if the function is defined after the main.
ü
Invoking a Function
From
here we call the function. A function as no life when it is not Invoked.
Uses of functions:
a.
Dividing the task
into sub tasks.
b.
If a particular
task is repeated number of times in a program we can create a function and call
that function wherever we want.
c.
Whenever a
function is called in a statement the control will be transferred to that
called function. After executing all statements it returns back to the calling
function.
d.
The length of the
source program will be reduced by using functions at appropriate places.
e.
A function can be
used in other programs also.
Syntax of a function
Return_type
function_name (argument list)
{
declarations;
statements;
-------------
return value;
}
Return statement:
It returns a value of the expression to the calling
function.
Syntax:- return(expression)
Ex:-
1.
return(0);
2.
return(a);
3.
return(a+b);
4.
return a;
5.
return;
1)
Write a program with parameters with return value by
using functions.
#include<stdio.h>
#include<conio.h>
int
sum(int x, int y)
{
return(x+y);
}
void main( )
{
int a, b, c;
clrscr( );
printf(“\n Enter a & b values”);
scanf(“%d %d”, &a, &b);
c=sum(a,b);
printf(“\n c=%d”, c);
getch( );
}
2)
Write a program to print the multiplication table
using with parameters, no return value by using functions.
#include<stdio.h>
#include<conio.h>
void
table (int n)
{
int i,r;
for (i=1;i<=10;i++)
{
r=n*i;
printf(“%d * %d = %d”, n,i,r);
}
}
void main( )
{
int no;
clrscr( );
printf(“\n Enter any number”);
scanf(“ %d”, &no);
table (no);
getch( );
}
3)
Write a program to calculate sum of digits of a given
number using functions.
#include<stdio.h>
#include<conio.h>
long
sum_digits(long n)
{
int rem;
long sum=0;
while (n>0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
return sum;
}
void main( )
{
long no;
clrscr( );
printf(“\n Enter any long number”);
scanf(“ %ld”, &no);
printf(“\n Sum of digits = %ld”, sum_digits(no));
getch( );
}
4)
Write a program to find the largest value among 3
given values.
#include<stdio.h>
#include<conio.h>
int
compare(int a, int b, int c)
{
if(a>b&&a>c)
{
return a;
}
else
if(b>c)
{
return b;
}
else
{
return c;
}
}
void main( )
{
int x, y, z;
int compare(int, int, int);
clrscr ( );
printf (“\n Enter any 3 values”);
scanf (“%d %d %d”, &x, &y, &z);
printf (“\n Highest value is %d”, compare(x,y,z);
getch ( );
}
5)
Write a program the reverse of the given number using
functions.
#include<stdio.h>
#include<conio.h>
void
reverse(int n)
{
int rev=0, rem;
while(n>0)
{
rem=n%10;
rev=rev*10+rem;
n=n/10;
}
printf(“Reverse of the given number = %d”, rev);
{
void main( )
{
int no;
clrscr( );
printf(“\n Enter any number”);
scanf(“%d”, &no);
reverse(no);
getch( );
}
Functions
with Arrays
1)
Write a program to print 10 numbers.
#include<stdio.h>
#include<conio.h>
void
display(int b [] )
{
int i;
for(i=0;i<10;i++)
{
printf(“\n %d”, b[i] );
}
}
void main( )
{
int a[10], i;
clrscr( );
printf(“\n Enter 10 values”);
for(i=0;i<10;i++)
{
printf(“\n Enter %d value”, i);
scanf(“%d”, &a[i]);
}
display(a);
getch( );
}
2)
Write a program to print 5 students, 3 subject marks
and calculate total.
#include<stdio.h>
#include<conio.h>
int
total(int s1, in s2, int s3)
int
tot;
tot=s1+s2+s3;
return
tot;
}
void main( )
{
int i, sno, sub1, sub2, sub3;
char name[20];
clrscr( );
for(i=0;i<=4;i++)
{
printf(“\n Enter student no”);
scanf(“%d”, &sno);
printf(“\n Enter student name”);
scanf(“%s”, &name);
printf(“\n Enter 3 subject marks”);
scanf(“%d %d %d”, &sub1, &sub2, &sub3);
printf(“total = %d”, total(sub1, sub2, sub3));
}
getch(
);
}
RECURSIVE
FUNCTION
Recursion:- It is a
mechanism where a function is calling itself it means the calling function and
called function are the same.
Ø
Recursion
will provide a looping effect.
Ø
If
it is not controlled properly it will enter into infinite loop.
Ø
A
recursive function will be written by using if-else, return statement and some
time using static variables.
1)
Write a program
to calculate the factorial of a given number using a recursive function.
# include <stdio.h>
# include <conio.h>
int fact(int);
void main( )
{
int n;
clrscr( );
printf("\n enter a number ");
scanf("%d",&n);
if(n>0)
printf("\n The factorial of %d is %d
",n,fact(n));
getch( );
}
int fact(int
num)
{
int f;
if(num= =1)
return 1;
else
f=num*fact(num-1);
return f;
}
2)
Write a program
to calculate the sum of first n natural numbers using Recursive function.
# include <stdio.h>
# include <conio.h>
void main()
{
int n;
int sum(int);
clrscr( );
printf("\n enter a number ");
scanf("%d",&n);
printf("\n The sum of first %d numbers is
%d ",n,sum(n));
getch( );
}
int sum(int num)
{
int s;
if(num= =1)
return 1;
else
s=num+sum(num-1);
return s;
}
POINTERS
A pointer is a variable
which holds the address of another variable.
Since addresses are whole numbers pointers would always contain whole
numbers.
Consider
the following declaration
Ex:-
int i=10;
The declaration tells the C compiler,
1)
Reserve space in
memory to hold the integer value.
2)
Associate the
name ‘i’ with memory location.
3)
Store the value
10 at this location.
Memory map:-
10
i
65524
‘i’ -
Location name
10 - Value at location
65524 – Location number or address.
Declaration of a pointer:
int
a, *x;
float
b, *y;
char
c, *z;
Pointer variable is same as
normal variable. But a * symbol is added before the variable.
Usage of pointers:- As pointers work with addresses accessing through addresses first then
through a normal variable. When the values are called with the help of address
by a function the modifications done to the variables shows the reflection.
Indirectly we can get the
value of a variable by using *. So * is called as indirection operator.
Whatever the data type may be a pointer variable occupies only 2 bytes of
memory.
1)
Program to display the address of a variable.
#
include <stdio.h>
#
include <conio.h>
void
main( )
{
int i=10;
clrscr( );
printf("\n The value of i is
%d",i);
printf("\n The address of i is
%u",&i);
printf("\n The value of i is
%d",*(&i));
getch( );
}
Note:-In the above program '&' is called 'address of
operator', '*' is called 'value at address' operator.
2)
Example for a pointer
#
include <stdio.h>
#
include <conio.h>
void
main( )
{
int i=10,*j;
j=&i;
clrscr( );
// *j=50;
printf("\n the address of i is %u
",&i);
printf("\n the address of i is
%u",j);
printf("\n the value of i is %d
",i);
printf("\n the value of i is
%d",*(&i));
printf("\n the value of i is
%d",*j);
printf("\n the address of j is
%u",&j);
printf("\n the value of j is %u",j);
getch( );
}
Note:- j -- address of i
-- 65524 &j -- j's own address – 65522 *j -- value at j i.e i value – 10
2.
W.A.P. to swapping of two numbers using pointers.
#
include <stdio.h>
#
include <conio.h>
void
main( )
{
int *p,*q,temp;
clrscr( );
printf("\n Enter two values ");
scanf("%d%d",p,q);
temp=*p;
*p=*q;
*q=temp;
printf(“Swapping of two numbers is:%d \t%d”,*p,*q);
getch();
}
3.
W.A.P. To calculate all arithmetic operations of two numbers
using pointers
#
include <stdio.h>
#
include <conio.h>
void
main( )
{
int
a,b,add,sub,mul,div;
int *x,*y;
clrscr( );
x=&a;
y=&b;
printf("\n
Enter a,b values ");
scanf("%d%d",&a,&b);
// scanf("%d%d",x,y);
add=*x + *y;
sub=*x - *y;
mul=*x * *y;
div=*x / *y;
printf("\n
Addition is %d",add);
printf("\n
Subtraction is %d",sub);
printf("\n
Multiplication is %d",mul);
printf("\n
Division is %d",div);
getch( );
}
Parameter passing mechanism
Ø
Call by value
Ø
Call by address
ü
Call by value:-
When the function calls the parameters by taking values the modifications done
to the parameters by the function doesn’t reflect.
ü
Call by address;- When the parameters are called by address the changes done to the
values within the function shows the reflection.
1)
Example program for call by value
#
include <conio.h>
#
include <stdio.h>
void
main( )
{
int a,b;
clrscr( );
printf("\n
Enter a, b values ");
scanf("%d%d",&a,&b);
printf("\n
the values of a and b are %d %d",a,b);
swap(a,b);
printf("\n
the values of a and b after swap function %d
%d ",a,b);
getch( );
}
swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
return a;
return b;
printf("\n
In function swap the values are %d %d ",x,y);
}
2)
Example program for call by address
#
include <stdio.h>
#
include <conio.h>
void
main( )
{
void swap(int *,int *);
int a, b;
clrscr( );
printf("\n Enter a , b values ");
scanf("%d %d", &a, &b);
printf("\n Before swap function the
values of a and b are %d %d", a, b);
swap(&a, &b);
printf("\n After swap function the values
of a and b are %d %d ", a, b);
getch( );
}
void
swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf("\n In swap function the values of
a and b are %d %d ",*x,*y);
}
STRUCTURES
Structure is a user defined
data type. A structure is a collection
of variables that is referenced under a single name. A structure contains a number of data types
grouped together. These data types may
or may not be of the same type.
Definition of a structure: - Structure is a collection of variables which are of
dissimilar data types.
Declaring a structure:-
struct
<structure name>
{
structure element 1;
structure element 2;
---
structure element n;
};
structure variables;
Ex:-
struct student
{
int sno;
char name[20];
int total;
};
struct book
{
int pages;
char author[20];
float price;
}a,b,c;
The
above declaration states that struct is a keyword which is called as a data
type in variables is declared which are of different data types.
In
the above declaration book is called Tag name and pages, Author, price are
called as data members of the structure.
Declaring a
variable for a structure
Ex:- Student
S1;
The
data members of the structure are called by the variable using ( . ) operator.
For example: -
S1. sno = 1;
S1.name = kranthi;
S1.marks= 500;
Features
of a structure: -
With the help of structure we can maintain a data in a systematic order. We can
handle a structure within a structure. And also we can call the structure
variable through functions and Arrays also can be implemented through
structures. Pointer to structure is also possible.
1)
Write a program
to initialize the structure variable and print them.
# include <stdio.h>
# include <conio.h>
void main( )
{
struct student
{
int sno;
char name[20];
int tot;
};
struct student s={1,"Kranthi",500};
clrscr( );
printf("\n the struct values are
");
printf("\n %d %s
%d ",s.sno,s.name,s.tot);
getch( );
}
Note:- In the above
program student is the name of the structure. sno,name,tot are the members of the
structure. 's' is the structure variable.
2)
Write a program
to take the values of structure elements and display
them
back.
#include<stdio.h>
#include<conio.h>
main( )
{
struct employee
{
int emp_id;
char
emp_name[20];
float emp_sal;
};
clrscr( );
struct employee
e1;
printf(“\n Enter
employee id no, employee name & employee salary”);
scanf(“%d %s
%f”, &e1.emp_id, e1.emp_name, &e1.emp_sal);
printf(“\n
Employee Id no = %d”, e1.emp_id);
printf(“\n
Employee name = %s”, e1.emp_name);
printf(“\n
Employee salary = %f”, e1.emp_sal);
getch( );
}
3)
Write a program
to print the details using structures.
# include <stdio.h>
# include <conio.h>
void main( )
{
struct item
{
char name[10];
int qty;
int rate;
int amount;
};
struct item a;
clrscr( );
printf("\n Enter item name, qty,
rate ");
scanf("%s%d%d",a.name,&a.qty,&a.rate);
a.amount=a.qty*a.rate;
printf("\n The values are");
printf("\n %s %d %d %d",a.name,a.qty,a.rate,a.amount);
getch( );
}
Array of Structures
1)
Write a program
to print more details using array of structures.
#include<stdio.h>
#include<conio.h>
Void main( )
{
int i;
struct student
{
int sno;
char sname[20];
};
struct student
s[5];
for(i=0;i<5;i++)
{
printf(“Enter
student number”);
scanf(“%d”,
&s[i].sno);
printf(”Enter
student name”);
scanf(“%s”,
s[i].sname);
}
clrscr( );
for(i=0;i<5;i++)
{
printf(“Student
number is %d \n”, s[i].sno);
printf(“Student
name is %s \n”, s[i].sname);
}
getch( );
}
Nested structures
1)
Example program
for nested structures
# include <stdio.h>
# include <conio.h>
void main( )
{
struct address
{
char phone[15];
char city[15];
long pin;
};
struct emp
{
char name[10];
struct address a;
};
struct emp
e={"Naveen","55353434","hyderabad",500010};
clrscr( );
printf("\n %s %s
%s %ld",e.name, e.a.phone, e.a.city,
e.a.pin);
getch( );
}
2)
Example program
for nested structures
# include <stdio.h>
# include <conio.h>
void main( )
{
struct address
{
char phone[15];
char city[15];
long pin;
};
struct emp
{
char name[20];
struct address a;
};
struct emp e;
clrscr( );
printf("\n Enter emp name ");
scanf("%s", e.name);
printf("\n Enter emp phone no ");
scanf("%s", e.a.phone);
printf("\n Enter emp city ");
scanf("%s", e.a.city);
printf("\n Enter pin code ");
scanf("%ld",&e.a.pin);
printf("\n %s %s
%s
%ld",e.name,e.a.phone,e.a.city,e.a.pin);
getch( );
}
Structures with pointers
3)
Example program
for pointer to a structure
# include <stdio.h>
# include <conio.h>
void main( )
{
struct student
{
int sno;
char name[20];
int total;
};
struct student a,*ptr;
clrscr( );
ptr=&a;
printf("\n Enter student number ");
scanf("%d",&a.sno);
printf("\n Enter student name ");
scanf("%s",a.name);
printf("\n Enter student marks ");
scanf("%d",&a.total);
printf("\n the size of a is
%d",sizeof(a));
printf("\n the size of ptr is
%d",sizeof(ptr));
printf("\n The address of a is
%u",&a);
printf("\n The address of sno is %u the value is %d",&a.sno,a.sno);
printf("\n The address of name is %u the value is %s",a.name,a.name);
printf("\n The address of total is
%u the value is
%d",&a.total,a.total);
printf("\n
Student number is %d",ptr->sno);
printf("\n Student name is
%s",ptr->name);
printf("\n Student marks %d",ptr->total);
getch( );
}
4)
Example program
for displaying the address of a struct variable
# include <stdio.h>
# include <conio.h>
void main( )
{
struct student
{
int sno;
char name[20];
int total;
};
struct student a;
clrscr( );
printf("\n Enter student details ");
printf("\nEnter student no ");
scanf("%d",&a.sno);
printf(" Enter student name ");
scanf("%s",a.name);
printf(" Enter student marks ");
scanf("%d",&a.total);
printf("\n The address of a is
%u",&a);
printf("\n The address of sno is %u the value is %d",&a.sno,a.sno);
printf("\n The address of name is %u the value is %s",a.name,a.name);
printf("\n The address of total is
%u the value is
%d",&a.total,a.total);
getch( );
}
5)
Example program
for passing the address of a structure into a function
# include <stdio.h>
# include <conio.h>
void display(struct student *);
struct student
{
int sno;
char name[20];
int total;
};
void main( )
{
struct student a;
clrscr( );
printf("\n Enter student number ");
scanf("%d",&a.sno);
printf("\n Enter student name
");
scanf("%s",a.name);
printf("\n Enter student marks
");
scanf("%d",&a.total);
display(&a);
getch( );
}
void
display(struct student *ptr)
{
printf("\n Student number is %d",ptr->sno);
printf("\n Student name is %s",ptr->name);
printf("\n Student marks
%d",ptr->total);
}
Functions with Structures
1)
Example program
for passing the struct values individually into a function and display them in
the function
# include <stdio.h>
# include <conio.h>
void main( )
{
struct student
{
int sno;
char name[20];
int total;
};
struct student a;
void display(int,char[],int);
clrscr( );
printf("\n Enter student details ");
printf("\nEnter student no ");
scanf("%d",&a.sno);
printf(" Enter student name ");
scanf("%s",a.name);
printf(" Enter student marks ");
scanf("%d",&a.total);
display(a.sno,a.name,a.total);
getch( );
}
void display(int no, char n[],int tot)
{
printf("\n Student no is %d",no);
printf("\n
Student name is %s",n);
printf("\n Student total is %d
",tot);
}
2)
Example program
for passing a struct variable into a function
# include <stdio.h>
# include <conio.h>
void
display(struct student);
struct student
{
int sno;
char name[20];
int total;
};
void main( )
{
struct student a;
clrscr( );
printf("\n Enter student details ");
printf("\nEnter student no ");
scanf("%d",&a.sno);
printf("\n Enter student name ");
scanf("%s",a.name);
printf("\n Enter student total marks ");
scanf("%d",&a.total);
display(a);
getch( );
}
void display(struct student b)
{
printf("\n Student no is %d",b.sno);
printf("\n Student name is
%s",b.name);
printf("\n Student total is %d
",b.total);
}
Note:- If we write the
structure definition out side of main( ), then that is treated as a global
structure, we can declare variables of this type in all functions throughout
the program.
Structure
sorting
1)
Write a program using structure sorting.
#
include <stdio.h>
#
include <conio.h>
#
include <string.h>
void
main( )
{
char
name[20],ch,tmp;
int i,j,len;
clrscr( );
printf("\n
Enter a string ");
scanf("%s",name);
len=strlen(name);
for(i=0;i<len;i++)
for(j=i+1;j<len;j++)
if(name[j]<name[i])
{
tmp=name[i];
name[i]=name[j];
name[j]=tmp;
}
printf("\n
the result is %s",name);
getch( );
}
STORAGE CLASSES
1.
Where the
variable would be stored
2.
What will be the
initial value of the variable, if the initial value is not specifically
assigned?
3.
What is the scope
of the variable, i.e. in which functions the value of the variable would be
available.
4.
What is the life
of the variable? i.e. how long would the variable exist.
There are 4
storage classes in C
1)
Automatic storage
classes
2)
Register storage
classes
3)
Static storage
classes
4)
External storage
classes
1)
Automatic
storage classes
1.
Storage - memory
2.
Default initial
value - garbage value
3.
Scope - local to
the block in which the variable is defined
4. Life - till the control remains with in the block in
which the variable is defined.
2)
Register
storage classes
1. Storage - CPU registers
2. Default initial value - garbage value
3. Scope - local
to the block in the variable is defined
4. Life - till the control remains in the block in which
the variable is defined.
3)
Static
storage classes
1. Storage - memory
2. Default initial value - 0
3. Scope - local to the block in the variable is
defined
4. Life - value of the variable persists between
different function calls.
4)
External
storage classes
1. Storage - memory
2. Default initial value - 0
3. Scope - global
4. Life - As long as the program execution does not come
to an end.
1)
Write a program automatic storage classes.
#
include <stdio.h>
#
include <conio.h>
void
main( )
{
auto
int j, i=10;
clrscr(
);
{
auto int i=5;
printf("\n The value of i is %d",i);
}
printf("\n The value of i is %d",i);
printf("\n The value of j is %d",j);
getch( );
}
2)
Write a program using register storage classes.
#
include <stdio.h>
#
include <conio.h>
void
main( )
{
register int n;
clrscr( );
for(n=1;n<=100;n++)
printf("\t %d",n);
getch( );
}
3)
Write a program using static storage classes.
#
include <stdio.h>
#
include <conio.h>
void
display( )
{
static int n;
printf("\n The value of n is %d",n);
n++;
}
void
main( )
{
clrscr( );
display( );
display( );
display( );
getch( );
}
Note-: In static, only first time the compiler initializes
the value of the variable, from second time onwards it continues with the previous
value.
4)
#
include <stdio.h>
#
include <conio.h>
int
n;
void
display( )
{
printf("\n
In display function the value of n=%d", n);
}
void
main( )
{
clrscr( );
printf("\n The value of n before assignment
is %d ",n);
display( );
n=100;
printf("\n The value of n after
assignment is %d", n);
display( );
getch( );
}
FILES
A file is a collection of
information on a storage device with a particular file name.
Ø Uses of a file:-
1) Stores the data in the
form of a file and we can retrieve it whenever we require.
2) Using the data from the
file in different programs.
Ø
Opening a
file:- we can open a file by
using fopen( )
Syntax: - fopen(file
name, opening mode);
Ex: - FILE *fp;
fp=fopen(“file1.txt”,”w”);
ü
File opening modes:-
1)
w :- Writing the data into a file. If the file already exists its contents will
be over written.
2)
r:- Reading data
from a file.
3)
a:- Adds data into
an existing file. (Appending)
4)
w+ :- We can
write data into , file and we can read data from the file. If the file already exists its contents will
be, over written, else creates a new file.
5)
r+ :- Reading existing contents, writing new
contents, modifying existing contents of a file.
6)
a+ :- Reading existing contents, appending new
contents at the end of a file.
ü Closing a
file:- When the file processing is
over, the file must be closed. We can close a file by using fclose( ).
Syntax:- fclose(file pointer);
Ex:- fclose(fp);
Ø
File functions:-
1)
getc( )
This function is used to read a character from a file.
Syntax
:- getc(file pointer);
Ex:- getc(fp);
2)
putc( )
This function is used to write a character into a file.
Syntax:- putc(character,
file pointer);
Ex:- putc(ch,fp);
3)
fprintf( ):- This function writes formatted data into a
file.
Syntax:- fprintf(file
pointer, “formatted string”, list of variables)
Ex:- fp=fopen(“student.dat”,”w”);
fprintf
(fp , “%d %s %d”, sno ,name, marks);
4)
fscanf( ):- This function reads formatted data from a
file.
Syntax:- fscanf(file
pointer, “formatted string”, list of variables)
Ex:- fp=fopen(“student.dat”,”r”);
fscanf(fp , “%d %s %d”, &sno, name, &marks);
1)
Write a program to create a text file
#
include <stdio.h>
#
include <conio.h>
void
main( )
{
FILE *fp;
char ch;
clrscr( );
fp=fopen("file1.txt","w+");
printf("\n
Enter few lines ^z to stop ");
while((ch=getchar( ))!=EOF)
putc(ch,fp);
fclose(fp);
}
2)
W.A.P. To display the contents of file1.txt file.
#
include <stdio.h>
#
include <conio.h>
#
include <stdlib.h>
void
main( )
{
FILE *fp;
char ch;
clrscr( );
fp=fopen("file1.txt","r");
if(fp==NULL)
{
printf("\n Unable to open the file");
getch( );
exit(0);
}
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
getch( );
}
3)
Write a program to add new text at the end of
file1.txt file
#
include <stdio.h>
#
include <conio.h>
void
main( )
{
FILE *fp;
char ch;
clrscr( );
fp=fopen("file1.txt","a");
printf("\n
Enter few lines ^z to stop ");
while((ch=getchar( ))!=EOF)
putc(ch,fp);
fclose(fp);
}
4)
Write a program to store 5 students details in a file
called student.dat
#
include <stdio.h>
#
include <conio.h>
void
main( )
{
FILE *fp;
int
sno,total,i;
char name[20];
fp=fopen("student.dat","w");
for(i=1;i<=5;i++)
{
printf("\n
Enter %d student details", i);
scanf("%d%s%d", &sno, name, &total);
fprintf(fp,"\n %d %s %d", sno, name, total);
}
fclose(fp);
}
5)
Write a program to display all 5 students details from
student.dat
#
include <stdio.h>
#
include <conio.h>
#
include <stdlib.h>
void
main( )
{
FILE *fp;
int
sno,total,i;
char name[20];
clrscr( );
fp=fopen("student.dat","r");
if(fp==NULL)
{
printf("\n Unable to open the file");
getch( );
exit(0);
}
printf("\n
The details of 5 students are \n");
printf("\nSNO\t NAME \t\t MARKS");
for(i=1;i<=5;i++)
{
fscanf(fp,"\n%d%s%d",&sno,name,&total);
printf("\n
%d \t%s \t\t%d",sno,name,total);
}
getch( );
fclose(fp);
}
COMMAND LINE ARGUMENTS.
C supports a
feature that facilities the supply of arguments to the main( ) function. These
arguments are supplied at the time of invoking the program. They are typically
used to pass the names of data files. For example
C:\>EXAM
DATA RESULTS
Here exam is the
name of the file contains the program to be executed and data and results are
the file names passed to the program as command line arguments.
The command line
arguments are typed by the user and are delimited by a space. The first argument
is always the file name and contains the program to be executed. The main( )
function which we have been using up to now without any arguments can take two
arguments as shown below.
void main(int argc, char *argv[ ])
The first argument argc is known as
argument counter represents the number of arguments in the command line. The
second argument argv is known, as argument vector is an array of char type
pointer that point to the command line arguments. The size of this array will
be equal to the value of argc. For example
C:\>EXAM
DATA RESULTS
The value of argc
would be 3 and argv would be an array of 3 pointers to strings as shown below
argv[0]---------
exam
argv[1]---------
data
argv[2]---------
results
Note:-
that argv[0] always represents the command name that invokes the program.
RANDOM ACCESS FILES (OR) BINARY FILES
1) ftell( ) :- This function
tells us the current position of the file in bytes.
Syntax:- ftell(file pointer)
Ex:- n=ftell(fp);
2) rewind( ):-
This function moves the record pointer to the starting position of the file.
Syntax:- rewind(file pointer);
Ex:- rewind(fp);
3) fseek( ) :-
This function moves record pointer to a
particular place in the file.
Syntax:- fseek(file pointer, offset , position);
if position is 0 i.e.
from starting position (SEEK_SET)
if position is 1 i.e.
from current position (SEEK_CUR)
if position is 2 i.e.
from end position (SEEK_END)
Offset:-
long int type number or variable.
Position is the numeric value. It may be positive or negative. Offset may be
numeric value or a variable of long type. It indicates number of bytes to move
from position. If it is positive value
to move forward, negative value to move backward.
4) fwrite( ):-
This function is used to write the information in a binary file.
Syntax:
- fwrite(address of struct
variable, size of
struct variable, no.of blocks, file pointer);
Ex:
- fwrite(&b,
sizeof(b),1,fp);
5) fread( ):- This function is used to read the data from a binary
file.
Syntax:- fread(address of struct variable, size of struct
variable , no. of blocks, file pointer);
Ex:- fread(&b,sizeof(b),1,fp);
GRAPHS
1)
Program to draw circles from the screen centre with
different colors.
#
include <stdio.h>
#
include <conio.h>
#
include <graphics.h>
#
include <stdlib.h>
#
include <dos.h>
void
main( )
{
int gd,gm,i;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
while(!kbhit())
{
for(i=10;i<=200;i++)
{
setcolor(random(16));
circle(320,240,i);
delay(50);
}
for(i=200;i>=10;i--)
{
setcolor(random(16));
circle(320,240,i);
delay(50);
}
}
closegraph( );
}
2)
#
include <stdio.h>
#
include <conio.h>
#
include <graphics.h>
#
include <stdlib.h>
#include<dos.h>
void
main( )
{
int gd,gm,i;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
setcolor(4);
settextstyle(7,0,3);
outtextxy(100,200,"HELLO");
bar(200,200,400,400);
floodfill(50,50,RED);
setcolor(RED);
while(!kbhit( ))
{
putpixel(random(640),random(480),random(15));
setcolor(random(16));
arc(random(640),random(480),10,100,150);
delay(100);
}
getch( );
closegraph(
);
}
3)
Example program to print flash news.
#
include <stdio.h>
#
include <conio.h>
#
include <graphics.h>
#
include <stdlib.h>
#
include <dos.h>
void
main( )
{
int gd,gm,i;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
setcolor(BLUE);
settextstyle(6,0,5);
setfillstyle(1,WHITE);
while(!kbhit( ))
{
for(i=640;i>=-450;i-=10)
{
bar(0,390,640,470);
outtextxy(i,400,"Sample flash
news");
delay(100);
}
}
closegraph( );
}
4)
Example for ellipse and fill ellipse.
#
include <stdio.h>
#
include <conio.h>
#
include <graphics.h>
void
main( )
{
int gd,gm,i;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
setcolor(WHITE);
ellipse(400,200,0,360,180,70);
setfillstyle(1,BLUE);
fillellipse(100,100,50,30);
getch( );
closegraph( );
}
5)
Program to print different font styles.
#
include <stdio.h>
#
include <conio.h>
#
include <graphics.h>
#
include <stdlib.h>
#
include <dos.h>
void
main( )
{
int gd,gm,i;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
setcolor(GREEN);
for(i=0;i<=10;i++)
{
cleardevice( );
settextstyle(i,0,10);
outtextxy(50,150,"SISI CMTES");
delay(1000);
}
getch( );
closegraph( );
}
6)
Example program for bar 3D and fill style.
#
include <stdio.h>
#
include <conio.h>
#
include <graphics.h>
#
include <stdlib.h>
#
include <dos.h>
void
main( )
{
int
gd,gm,i=0,x,y;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
for(i=0;i<13;i++)
{
setcolor(WHITE);
setfillstyle(i,GREEN);
bar3d(220,140,420,340,50,1);
delay(1000);
}
getch( );
closegraph( );
}
7)
Program to print Indian flag.
#
include <stdio.h>
#
include <conio.h>
#
include <graphics.h>
#
include <stdlib.h>
void
main( )
{
int gd,gm;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
setfillstyle(1,BROWN);
bar(0,0,640,100);
setfillstyle(1,WHITE);
bar(0,101,640,200);
setfillstyle(1,GREEN);
bar(0,201,640,300);
setcolor(BLUE);
circle(320,150,50);
line(270,150,370,150);
line(320,100,320,200);
line(295,107,348,192);
line(347,107,290,190);
getch( );
closegraph( );
}
8)
#
include <stdio.h>
#
include <conio.h>
#
include <graphics.h>
#
include <stdlib.h>
void
main( )
{
int gd,gm;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
setfillstyle(1,BLUE);
bar(100,100,105,300);
setfillstyle(1,BROWN);
bar(106,100,180,120);
setfillstyle(1,LIGHTGRAY);
bar(106,121,180,141);
setcolor(BLUE);
circle(144,131,10);
setfillstyle(1,GREEN);
bar(106,142,180,162);
setfillstyle(1,LIGHTBLUE);
bar(90,300,115,320);
setfillstyle(1,CYAN);
bar(80,321,125,341);
setfillstyle(1,BROWN);
bar(70,341,135,361);
getch( );
closegraph( );
}
9.
Program to a
“WELCOME TO APTECH” in middle of screen.
gotoxy():- conio.h
To move cursor particular position console window or output window.
Syntax:-
gotoxy(Column No,Row No);
#include<stdioh>
#include<conio.h>
int
main()
{
clrscr();
gotoxy(20,5);
textcolor(RED);
cprintf(“WELCOME TO APTECH”);
return 0;
}
10. Write a program DRAW A BOX.
#include<stdio.h>
#include<conio.h>
#include<dos.h>
#include<graphics.h>
int
main()
{
int
r,c;
clrscr();
c=5;
do
{
delay(200);
gotoxy(c,5);
textcolor(RED);
cprintf(“*”);
delay(200);
gotoxy(c,15);
cprintf(“*”);
c++;
}
while(c<=40);
r=5;
do
{
delay(200);
gotoxy(5,r);
textcolor(GREEN);
cprintf(“*”);
gotoxy(40,r);
textcolor(GREEN);
cprintf(“*”);
r++;
}while(r<=15);
return
0;
}
Comments
Post a Comment