Programming Language1
Programming Language1
2079
Prepared by:-
Mr. Upendra Malla
(9858077977)
1
Table of contents:
1 Programming Language .......................................................................................................................................... 4
1.1 Translator ......................................................................................................................................................... 4
1.2 Structured programming ................................................................................................................................ 6
1.3 Coding: .............................................................................................................................................................. 6
1.4 What is debugging?.......................................................................................................................................... 6
1.5 Documentation ................................................................................................................................................. 7
2 Introduction of C program:- ................................................................................................................................... 9
3 Fundamental in C .................................................................................................................................................. 12
3.1 Character set used in c................................................................................................................................... 12
3.2 Use of comment .............................................................................................................................................. 13
3.3 C tokens........................................................................................................................................................... 13
3.4 Identifier ......................................................................................................................................................... 13
3.5 Keyword .......................................................................................................................................................... 13
3.6 Data types in c ................................................................................................................................................ 14
3.7 Constant and variables .................................................................................................................................. 15
Variables ..................................................................................................................................................................... 16
3.8 Specifier Used in c program-......................................................................................................................... 16
3.9 Escape sequences ............................................................................................................................................ 17
3.10 Operator.......................................................................................................................................................... 17
3.1 printf():- .......................................................................................................................................................... 27
3.2 Scanf() ............................................................................................................................................................. 27
3.3 Other input / output functions ......................................................................... Error! Bookmark not defined.
3.3.1 getchar() ................................................................................................................................................... 27
3.3.2 putchar() ................................................................................................................................................... 28
3.4 gets() and puts(): ............................................................................................................................................ 31
4 Control structure...................................................................................................................................................... 32
4.1 Branching statements ...................................................................................................................................... 32
4.1.1 if statements ............................................................................................................................................ 32
4.1.2 switch statement ....................................................................................................................................... 36
4.1.3 Conditional statement ............................................................................................................................ 38
4.2 Looping statements ........................................................................................................................................ 39
4.2.2 Jumping statements ............................................................................................................................... 46
5 Array ....................................................................................................................................................................... 52
2
5.1 One dimensional array ..................................................................................................................................... 53
5.2 Multi-dimensional array................................................................................................................................... 53
5.2.1 Character array: ........................................................................................................................................ 57
5.2.2 Examples ..................................................................................................... Error! Bookmark not defined.
6 Functions: ............................................................................................................................................................... 70
6.1 Components of function: ............................................................................................................................... 71
6.1.1 Function prototype: ............................................................................................................................... 71
6.1.2 Function definition ................................................................................................................................. 71
6.1.3 Call the function or function call: ......................................................................................................... 72
6.2 Types of functions: ......................................................................................................................................... 73
6.2.1 Library function: .................................................................................................................................... 73
6.2.2 User defined function: ........................................................................................................................... 75
6.3 Concept of recursion in function: ................................................................................................................. 79
7 Structure ................................................................................................................................................................. 82
8 Union ....................................................................................................................................................................... 89
9 What are Pointers? ................................................................................................................................................ 94
10 File handling ....................................................................................................................................................... 95
10.1 Concept of data files: ..................................................................................................................................... 95
10.1.1 Defining and opening data file .............................................................................................................. 95
10.1.2 Closing data file ...................................................................................................................................... 95
10.1.3 getc() and putc() functions: ................................................................................................................... 95
10.1.4 getw() and putw() functions: ................................................................................................................. 96
10.1.5 fscanf() and fprintf() functions: ............................................................................................................ 96
3
1 Basic concept of Programming Language
Program:- A set of statement with instruction in step wise procedure is called program.
Software:- A collection of program which is capable in particular task.
A language is a means of communication. A programming language is a
well-defined set of rules for specifying a program’s sequence of
instructions. Example: C, C++, FORTRAN, JAVA, BASIC, prolog, Pascal
etc.
Every programming language consists of symbols, characters, syntax and
rules that permit people to communicate with computers. There are five
levels/ generation of programming languages:
Two types
Low level
i. Machine level language (1GL)
ii. Assembly level language (2GL)
High level
iii. High level language
1. Procedural oriented language C, QBASIC (3GL)
2. Problem oriented language ( Object oriented
language)(4GL)
iv. Natural language (5GL)
4
c) Interpreter :- In computer science, an interpreter is a
computer program that directly executes instructions written in a
programming or scripting language, without requiring them previously to
have been compiled into a machine language program.
/////////
5
1.2 Structured programming
Structured programming takes a top-down approach that breaks programs into
modular forms where a system is divided into compositional subsystems.
The point of structured programming is to make programs more efficient and
better organized and to have better notations so that they have clear and correct
descriptions. It uses standard logic tools called control structures. It is the most
popular design approach at present. Its key design considerations are:
a) Top-down design
b) Modular design
c) Structured theorem
1.3 Coding:
Once the design has been developed and reviewed, the next step is the actual
writing of the program is called coding. Coding is the process of translation from
a detailed design to program statements in a programming language.
1.4 What is debugging?
Debugging is a processes of detecting, locating and removing errors in a program.
Debugging checks, detects and corrects errors or bugs to allow
proper program operation according to set specifications.
Mistakes may be three types they are:
a) Syntax error
b) Logical error (semantic error)
c) Run time error
6
1.5 Documentation
Documentation is the process of collecting, organizing, storing and maintaining a
complete record of system and other documents used or prepared during the
different phases of the life cycle of system.
Programming designing tools:
1. Algorithm
Step by step solution
Write an algorithm to display area of rectangular box.
A=lxb
Step 1:- start
Step 2:- read l, b
Step 3:- area=l x b
Step 4:- display area
Step 5:-stop
Write an algorithm to display the smallest number among
any three numbers.
Step1:- start
Step 2:- read n1, n2 and n3
Step 3:- is n1<n2 and n1<n3 ?
Yes display n1 is smallest number
No go to step 4
Step 4:- is n2<n1 and n2<n3 ?
Start
Yes display n2 is smallest number
No display n3 is smallest number.
Step 5:- stop
2. Flowchart
Read n1, n2, n3
Pictorials representation of algorithm.
Draw the flowchart to display the smallest number among
any three numbers.
Is n1<n2
and start /end
n1<n3 ?
Input/Output
process
decision
data flow
7
Start
No
Yes
Is n1<n2
and
n1<n3 ?
display n1 is smallest
number
Is n2<n1 Yes
and n2<n3
?
display n2 is smallest
No number
display n3 is smallest
number
END
8
3. Pseudo code
2 Introduction of C program:-
The classical method of learning English is to first learn the alphabets used in the
language, then learn to combine these alphabets to form words, which in turn are
combined to form sentences and sentences are combined to form paragraphs.
Learning C is similar and easier. Instead of straight-away learning how to write
programs, we must first know what alphabets, numbers and special symbols are
used in C, then how using them constants, variables and keywords are
constructed, and finally how are these combined to form an instruction. A group
of instructions would be combined later on to form a program.
C is programming language developed at AT & T’s bell laboratories of USA in
1970s. It was designed and developed by Dennis Ritchie. C seems so popular
because it is reliable, simple and easy to use. C stands in between high level
language and low level language. That is why it is often called a middle level
language.
Features in c program
1. Portability
2. Faster and efficient
3. Supports structured programming
4. Extendibility
5. Flexible
Advantaged of c language
a) It is more efficient than unstructured code because of minimized
branching of the code.
b) Correction of errors is easier.
c) Adding new feature is easier and faster.
d) Maintenance the c code is easy due to readability of the code.
e) It is easier to interact with hardware
f) It is easy to learn.
g) Program code is secured.
h) It is compact and efficient to use.
9
Structure of C program
Home work:
Q.no.1. What is c program ? explain with history of c program.
Q.no.2. Write advantages of c program with features.
10
Q.no.3. What is coding?
Q.no.4. What is debugging? write with errors types.
Compiling process
11
Editor :-
An Editor is a system or program which allows a user to edit text. It is a
specialized word processor used to prepare source code in a programming
language.
Preprocessor :-
C Preprocessor is just a text substitution tool and it instructs the compiler to do
required pre-processing before the actual compilation. All preprocessor
commands begin with a hash symbol (#).#define, #include, #undef, #error
etc.
Compiler :-
A compiler translates the code written in one language to some other language
without changing the meaning of the program.
Linker :-
A linker combines one or more object files and possible some library code
into either some executable, some library or a list of error messages. Linker is
a computer program that links and merges various object files together in
order to make an executable file.
Executable file :-
An executable file (exe file) is a computer file that contains an encoded sequence
of instructions that the system can execute directly when the user clicks the file
icon.
Executable files commonly have an EXE file extension, but there are hundreds of
other executable file formats. Some executable files can run on any compatible
system without requiring the existence of another program. Such files, which are
considered to pose a high security risk, include
EXE, BAT, COM, CMD, INF, IPA, OSX, PIF, RUN and WSH.
3 Fundamental in C
3.1 Character set used in c
A character set in c contains any alphabet, digit or special symbol used to
represent information.
Alphabets => A,B,C,D……………………X,Y,Z
a, b, c, d…………………….x,y,z
Digits => 0,1,2,3,4,5…………..9
12
Symbols => @ {}, [ ], ( ), *, “ ”, ‘ ’, :, #. %, &, !, `, ~, /
3.2 Use of comment
a. Single line comment
//single line comment only used on C++
b. Multiline comment
/* this is c program.
And its example of multiline
comment. */
3.3 C tokens
The basic and smallest element used to develop the program and recognized
by the c compiler is called c tokens.
C tokens includes:-
3.3.1 Identifier
Names are given to various program elements such as variables,
functions, labels, and other user-defined items are known as an
identifier.
a) It can be a combination of Number, alphabet, and special
symbols.
b) The first character of an identifier must be an alphabet or an
underscore.
c) Identifiers are both case accept and it is also case sensitivity.
d) Identifiers are strings of alphanumeric characters that don’t begin
with a numbers
a. Eg. Sum, a_b, _temp, Year2019 etc =valid identifiers
i. 1count, high….level, Roll no, 2019Year= not valid
3.3.2 Keyword
The keyword is a reserved word that has standard and predefined
meaning in c. The ANSI C defines 32 keywords. All data types are
keyword but all keywords are not data type.
auto Const Double float Int short struct unsigned
break Continue Else for Login signed switch void
case Default Enum goto register sizeof typedef volatile
char Do Extern If Return static union while
13
3.3.3 Data types in c
The data type is an instruction that is used to declare the category or
type of variable being used in the program. Data type can be:
1) It can be declared before using method.
2) It determines the way a computer organizes data in
memory.
3) It determines how much space it occupies in storage and
how the bit pattern stored is interpreted.
Types of data type can be either pre-defined or derived.
Predefined data types
Type Size (bytes) Format Specifier
Int` at least 2, usually 4 %d
Char 1 %c, %s
Float 4 %f
Double 8 %lf
short int 2 usually %hd
unsigned int at least 2, usually 4 %u
long int at least 4, usually 8 %li
long long int at least 8 %lli
unsigned long int at least 4 %lu
unsigned long long int at least 8 %llu
signed char 1 %c
unsigned char 1 %c
long double at least 10, usually 12 or 16 %lf
14
3.3.4 Constant and variables
Constant :- A constant is a quantity that doesn’t change during
program execution. C has four basic types of constants. They are:-
a) Integer constant
b) Floating point constant
c) Character constant
d) String constant
a) Integer constant
An integer constant is an integer valued number. It consists of a sequence
of digits. It must have at least one digit and must not contain any decimal
point. Integer always must be positive and without commas.
C allows three types of integer constants: valid not valid
1. Decimal integer constants 1234354 12,234
2. Octal integer constants o3234 3434
3. Hexadecimal integer constants ox A2B AB3D
b) Floating point constant
A floating constant in fractional form must have at least one digits
before a decimal point and at least one digit after the decimal point.
Valid floating number invalid number
7.0 7
17.34 17.
-14.78 -14/5
3243432.45 34,234.56
1213E05 3343e
c) Character constant
A character constant is a single character, enclosed in apostrophes (single
quotation marks). When the c compiler encounters such a characters constant, it
translates it into the corresponding ASCII code and stores that number in the
program.
Valid invalid
‘a’ ‘surkhet’
‘b’ ‘@nepal’
‘5’ ‘34543abc’
15
d) String constant
String constants, also known as string literals, are a special type of constants
which store fixed sequences of characters. A string literal is a sequence of any
number of characters surrounded by double quotes:
%c single character
%d decimal integer
%e floating point value in exponent form
%f floating point value with out exponent form
%i signed decimal integer
%o octal integer without leading zero
16
%s string
%u unsigned decimal integer
%x hexadecimal number
%id long integer
3.5 Escape sequences
The backslash symbol “\” is considered as an “escape character”. It causes
an escape from the normal interpretation of a string so that the next
character is recognized as one having special meaning. All escape sequence
is represented by back slash(\), followed by a character.
Some common escape sequences are shown below:
Character Escape
Newline \n
Null character \
Horizontal tab \t
Bell(alert) \a
Quotation mark \”
Apostrophe(‘) \’
Backslash(\) \\
Carriage return \r
3.6 Operator
Operators are the foundation of any programming language. Thus the
functionality of C language is incomplete without the use of operators.
Operators allow us to perform different kinds of operations on operands. In
C operators, it can be categorized in following categories:
I. Arithmetic operator
II. Relational operator
III. Equality operator
IV. Logical operator
V. Assignment operator
VI. Increment / decrement operator
VII. Conditional operator
VIII. Bitwise operator
IX. Special operator
17
i. Arithmetic operator
Arithmetic operator is symbol used for basic operation like mathematical and
arithmetic calculations. It usually takes two operands and returns the result of the
mathematical calculation. C contains five arithmetic operators, they are:-
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of B % A = 0
after an integer division.
res = a + b;
printf("a+b is %d\n", res);
res = a - b;
printf("a-b is %d\n", res);
res = a * b;
printf("a*b is %d\n", res);
res = a / b;
printf("a/b is %d\n", res);
res = a % b;
printf("a%b is %d\n", res);
return 0;
}
18
ii. Relational operator
Relational operator is a symbol that determines the relationship between two
different operands. C provides four relational operators in which all operators are
binary for comparing numbers and characters.
operator Example
> (A > B) is not true.
< (A < B) is true.
>= (A >= B) is not true.
<= (A <= B) is true.
19
iii. Equality operator :-
Equality operator is a symbol used to compare two operands if they are equal or
not. It is a binary operator.
Operator Description Example
== Checks if the values of two operands are If a=10, c=10
equal or not. If yes, then the condition (A = = C) is true.
becomes true.
!= Checks if the values of two operands are (A != C) is not
equal or not. If the values are not equal, true.
then the condition becomes true.
20
v. Assignment operator
Assignment operator is a symbol used to assign a value or a result of an
expression to an identifier.
Operator Description Example
= Simple assignment operator. Assigns C=A+B
values from right side operands to left will assign the value
side operand of A + B = C
+= Add AND assignment operator. It adds C += A
the right operand to the left operand is equivalent to
and assign the result to the left C=C+A
operand.
-= Subtract AND assignment operator. It C -= A
subtracts the right operand from the is equivalent to
left operand and assigns the result to C=C-A
the left operand.
*= Multiply AND assignment operator. It C *= A
multiplies the right operand with the is equivalent to
left operand and assigns the result to C=C*A
the left operand.
/= Divide AND assignment operator. It C /= A
divides the left operand with the right is equivalent to
operand and assigns the result to the C=C/A
left operand.
%= Modulus AND assignment operator. It C %= A
takes modulus using two operands and is equivalent to
assigns the result to the left operand. C=C%A
21
// Working of assignment operators
#include <stdio.h>
int main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %d\n", c);
c += a; //c=c+a; // c is 10
printf("c = %d\n", c);
c -= a;
printf("c = %d\n", c);
c *= a;
printf("c = %d\n", c);
C /= a; // c is 5
printf("c = %d\n", c);
C %= a; // c = 0
printf("c = %d\n", c);
return 0;
}
22
vi. Increment / decrement operator
The increment operator (++) adds 1 to its operand, and the
decrement operator (--) subtracts 1 from its operand.
23
2) Expressions
An expression statement consists of an expression followed by a
semicolon. The execution of an expression statement causes the
expression to be evaluated. Expression statement are those that
consist of any valid c expression.
For example:
Algebraic expression c expression
Sum=a+b sum=a+b;
2
(4PIr )/2 (4*PI*r*r)/2;
2
3x +2x+1 3*x*x+2*x+1;
25
Q.no.2. WAP to find square root of input numbers.
/* to square root of input numbers. */
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
float s;
printf(“enter the value x :-”);
scanf(“%d”,&x);
s=sqrt(x);
printf(“\n %d square root value is %f”, x,s);
getch();
}
Q.no.3. WAP to calculate and print simple interest (SI) and net amount (A), given
that SI=PTR/100 and A=SI+P.
/* to calculate and print simple interest (SI) and net amount (A), given that
SI=PTR/100 and A=SI+P.
*/
#include<stdio.h>
#include<conio.h>
void main()
{
int si, a, p=20000, T=2, r=12;
si=p*t*r/100;
a=si+p;
printf (“ to simple interest = %d \n and net amount = %d”,si,a);
getch();
}
3. input /output functions
All Input/output operations are carried out through printf() and scanf()
function. There exist several functions that have more or less become
standard for input and output operations in C. these functions are
26
collectively known as the standard I/O library because it can take or accept
any type of data.
C language consists of some I/O functions like :
getchar(), putchar(), scanf(), printf(), gets(), puts(), getch(), putch(),
getche() etc.
3.1 printf():-
It can be used to display some conversion characters along with some
unchanged characters along with some changed characters.
Syntax:
Printf(“control string”, arg1, arg2,arg3);
Example1 :
Printf(“hello”);
Example 2:
Int a=5;
Printf(“%d:”,a);
Example 3:
Float a=0.5;
Float b=33242.3434
Printf(“%f and %.3f”,a,b);
Output:
0.500000
33242.343
3.2 Scanf()
scanf() is formatted Input function. It can be used to get inputs from the
user.
Syntax:
scanf(“control string”,arg1, arg2..);
Example:-
int a;
float b;
char name[30];
scanf(“%d%f%s”,&a,&b,&name);
3.3 getchar()
the getchar() function is used to read a single character. It cannot take
more than one character.
Syntax: variable_name=getchar();
27
3.4 putchar()
the putchar() function is used to display the character contained in the
variable name at the terminal.
Syntax:
putchar(variable_name);
#include <stdio.h>
int main()
{
int n=x
char n;
printf("enter your character\n");
n=getchar();
putchar (n);
return 0;
}
28
Some example:-
For just practice:-
a) #include<stdio.h>
#include<conio.h>
void main()
{
Printf(“my name is upendra malla”);
Getch();
}
b) #include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
Printf(“value of A is =%d”,a);
Getch();
}
c) #include<stdio.h>
#include<conio.h>
void main()
{
int a;
Printf(“enter the value for a”);
Scanf(“%d”,&a);
Getch();
}
d) #include<stdio.h>
#include<conio.h>
void main()
{
int a;
Printf(“enter the value for a”);
Scanf(“%d”,&a);
Getch();
}
29
e) Write a program to enter your name and display in times.
f) Write a program to enter your name, address, age and phone and
display it.
g) Write a program to find the sum of any two integer number.
h) Write a program to display the following pattern.
*
**
***
****
*****
Facebook/gmail./email/ twitter/mobile
30
3.5 gets() and puts():
The gets() function is used for a completely different purpose. It reads a
string (group of characters) from the standard input and store in the
given variable.
The puts() function is used to display text in the monitor which is stored
in the variable. But variable is always string data type.
Syntax:
gets(variable);
puts(variable);
Example:
#include <stdio.h>
int main()
{
char name[30];
printf("enter your name\n");
gets(name);
puts("that is name:");
puts(name);
return 0;
}
Q.no.1.What is a variable? Write example and syntax.
Q.no.2.What is an operator? Explain with syntax and example.
Q.no.3. Write about I/O functions with example.
Q.no.4. Define the identifier. List the useful identifier.
31
4 Control structure
A control structure is a block of programming that analyzes variables
and chooses a direction in which to go based on given parameters. The
term flow control details the direction the program takes (which
way program control "flows"). Control structures are the statements that
control the flow of the source code. There are three categories of flow
controls:
4.1 Branching statements
These are the decision making statements. There are three of them:
sequential
4.1.1 if statements
If statement is used to express conditional expression. If the given
condition is true then it will execute the statements; otherwise it will
execute optional statements.
4.1.1.1 simple if statement
Syntax:- if (condition is true)
{
Execute this statement
}
32
4.1.1.2 if else statement
If else statements in C is also used to control the program flow based
on some condition, only the difference is: it's used to execute
some statement code block if the expression is evaluated to true,
otherwise execute else statement code block.
Syntax:- if (condition is true)
{
Execute this statement
}
else
{
execute other statement
}
4.1.1.3 if ladder statement / if..else if… else
If else ladder statement in C programming language is used to test set
of conditions in sequence. An if condition is tested only when all
previous if conditions in if-else ladder is false.
Syntax:- if (condition is true)
Execute this statement
Else if (condition is true)
execute other statement
Else if (condition is true)
execute other statement
Else
execute other statement
33
34
#include <stdio.h>
#include<conio.h>
int main()
{
int ch;
printf("\n\t 1. select for the addtion ");
printf("\n\t 2. select for the subttraction ");
printf("\n\t 3. select for the multiply ");
printf("\n\t 4. select for the exit \n");
scanf("%d",&ch);
if (ch==1)
{
int a=5, b=4, c;
c=a+b;
printf("sum of two number %d",c);
}
else if (ch==2)
{
int a=5, b=4, c;
c=a-b;
printf("subtract of two number %d",c);
}
else if(ch==3)
{
int a=5, b=4, c;
c=a*b;
printf("product of two number %d",c);
}
else
{
printf("thans for visit it. exit the program");
}
return 0;
}
Class work
Q.no.1. Write a c program to read a number and display it.
Q.no.2. Write a c program to input your name and address and display it.
Q.no.3. What is keyword?
q.no.4. what is data type?
q.no.5. What is control structure? Explain with examples
q.no.6. what is If statement? Write syntax and example.
35
Example :-
/* a c program is example of if statement */
#include <stdio.h>
#include<conio.h>
void main()
{
int x,y,z;
printf(“Enter the value of x, y, z \n”);
scanf(“%d %d %d”,&x,&y,&z);
if(x==y || x==z)
{
printf(“All numbers are equal”);
}
else if(y>z)
{
printf(“second number y is greater than others”);
}
else
{
printf(“third number z is greater than others”);
}
getch();
}
Syntax:
switch (variable or an integer expression)
{
case constant:
//C Statements
36
;
case constant:
//C Statements
;
default:
//C Statements
;
}
Example:
#include <stdio.h>
int main()
{
int num;
printf("enter 1 for girls \n");
printf("enter 2 for boys \n");
printf("enter 3 for exit\n");
scanf("%d",&num);
switch(num)
{
case 1:
printf("Case1: well come all girls ");
break;
case 2:
printf("Case1: well come all boys");
break;
case 3:
printf("Case1: good byee");
break;
default:
printf("Default: try again (1/2/3)");
break;
}
return 0;
}
37
4.1.3 Conditional statement
When a series of decision is required, nested if-else is used. Nesting
means using one if-else construct within another one.
Syntax:-
if (condition is true)
{
if (condition is true)
Execute this statement
Else
Execute other statement
}
Else
Execute the other statement.
Example:
#include<stdio.h>
int main()
{
int num;
printf(“enter the numeric value \n”);
scanf(“%d”,&num);
if(num<10)
{
if(num>5)
{
printf("The value is :%d\n",num);
}
else
{
printf("The value is than 5");
}
}
else
{
printf("The value is greater than 10");
}
38
return 0;
}
4.2 Looping statements
These statements are used when there is a need to repeat a particular
block of code a finite number of times. They are also called iterating
statements. There are three of them:
4.2.1.1 while loop
A while loop in C programming repeatedly executes a target statement as
long as a given condition is true.
Syntax
while(condition)
{
statement(s);
}
Example
/* Using while loop */
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}
return 0;
}
WAP to display the 1 to 50 natural numbers using while loop.
40
4.2.1.3 for loop
A for loop is a repetition control structure that allows you to efficiently
write a loop that needs to execute a specific number of times.
Syntax
for ( init; condition; increment )
{
statement(s);
}
Example
#include <stdio.h>
int main ()
{
int a;
/* for loop execution */
for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", a);
}
return 0;
}
Q.no.1. WAP to display the multiplication table of 8 and using for loop.
Soln.
8 x1=8
8x2=16
8x3=24
.
.
.
.
.
8x10=80
42
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=1,i, j, multi;
for(i=1; i<=3; i++)
{
for(j=1;j<=10; j++)
{
multi=a*j;
printf(" %d x %d = %d\n", a,j,multi);
}
printf("\n ");
a=a+1;
}
getch();
#include<stdio.h>
#include<conio.h>
void main()
for(j=1;j<=i; j++)
printf("\n ");
a=a+1;
getch();
44
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, multi;
for(i=1; i<=3; i++)
{
for(j=1;j<=10; j++)
{
printf(" surkhet\n”);
}
printf("\t ");
}
getch();
45
4.2.2 Jumping statements
As the name suggests, these allow the cursor to jump to another block of
code, on reaching them in the program. These are further three:
4.2.2.1 Continue statement
Continue statement is used to continue the normal flow of program
statement execution in loop and skipping particular iteration in the loop
as soon as certain condition is satisfied.
example:
void main( )
{
int j;
for(j=1; j<=5; j++)
{
if(j==2)
continue;
printf("%d\t",j);
}
}
46
4.2.2.2 Break statement:
Break statement is used to break the normal flow of program statement
execution in control structure and program move on the next statement
when condition is not satisfied.
Example:-
Write a program to check whether a number is prime or not.
/* a program is check the number which is prime or not.*/
#include<stdio.h>
#include<conio.h>
int main()
{
int n, i;
printf (“\n enter the number :- ”);
scanf(“%d”,&n);
for (i=2; i<=n/2; i++)
{
If(n%i==0)
{
Break;
}
}
If(i>n/2)
{
Printf(“\n %d is prime number ”,n);
}
Else
Printf(“\n %d is not prime number”,n);
Return 0;
}
}
Q.no.1. Explain break, continue and goto statement with suitable example.
Q.no.2. Write a program to display the following output.
333
22
1
Q.no.3. Write a program to calculate and display sum of the digits present in
the given number.
#include<stdio.h>
void main()
{ Enter a number:78
int n,r,sum=0; R=78%10=8
printf("\n enter a number:"); Sum=0+8=8
scanf("%d",&n); N=7/10=0.7=0
do While (n!=0)
{
r=n%10; E
sum=sum+r;
n=n/10;
}while(n!=0)
printf("\n sum of the digits=%d", sum);
Return 0;
Getch();
}
Q.no.4. Write a program to check the given number is palindrome or not.
#include<stdio.h>
48
void main()
{
int n, temp, sum=0,d;
printf("\n enter a number");
scanf("%d",&n);
temp=n;
while(n!=0)
{
d=n%10;
sum=sum*10+d;
n=n/10;
}
if(temp= =sum)
printf("\n the number is palindrome");
else
printf("\n the number is not palindrome");
}
Home work
1. Write a menu driven program which reads a number from the user and performs
the following task:
a. Calculate factorial of the 6 number
b. Print the multiplication table of 9 number
c. To check whether the given number is palindrome number
d. To check whether the given number is prime or composite.
e. Exit from the program.
2. Write a program to calculate and display the following series:
1 3 5 …………..10th terms.
3. WAP to display square series of first n natural numbers.
4. WAP to calculate and display the Fibonacci series having n terms.
5. WAP to display the prime series up 2 3 5 7 11 up to n terms.
49
Q.no.5. Write a program to convert from decimal number system into binary
number system.
#include<stdio.h>
void main()
{
int d,n, sum=0, i=1;
printf("\n enter decimal number less than 31:");
scanf("%d",&n);
while (n!=0)
{
d=n%2;
sum=sum+d*i;
n=n/2;
i*=10;
}
printf("\n the binary number is %d",sum);
}
Q.no.6. Write a program to convert the given binary number into equivalent
decimal number.
#include<stdio.h>
void main()
{
int d,n, p=0,sum=0;
printf("\n enter binary number :");
scanf("%d",&n);
while (n!=0)
{
d=n%10;
sum=sum+pow(2,p)*d;
n=n/10;
p++;
}
printf("\n the binary number is %d", sum);
}
50
Q.no.7. Write a program to check whether the given number is prime or
composite number.
#include<stdio.h>
void main()
{
int n, i;
printf("\n enter number to check prime:");
scanf("%d", &n);
for(i=2;i<=n; i++)
{
if(n%i==0)
break;
}
if(i==n)
printf ("\n the given number is prime");
else
printf ("\n the given number is composite");
A[0]=10
A[1]=4
A[2]=42
A[4]=5
Int employee_ID[100]
2 2 A[0]+a[2]=2+0=2
0 1
2
5 Array
In c language, arrays are referred to as structured data types. An array is defined
as finite ordered collection of homogenous data, stored in contiguous memory
locations.
Here the words,
52
Finite means data range must be defined.
Ordered means data must be stored in continuous memory address.
Homogenous means data must be of similar data types.
where array are used.
To store list of employee or students name.
To store marks of students
Or to store list of numbers or characters in same variables name.
Since arrays provide an easy way to represent data, it is classified amongst the
data structures in c. Other data structures in c are
o Structure,
o Lists,
o Queues,
o Trees etc.
Array can be used to represent not only simple list of data but also table of data
in two or three dimensions.so types of arrays are:
5.1 One dimensional array
5.2 Multi-dimensional array
A[3]x[5]
10 2 4
12 59 82
5 6 8
12 59 82
5 6 8
A[0][0]=10
A[0][1]=2
A[0][2]=4
…….
…
…
…
A[4][2]=11
Declaring an one dimensional array
53
Like any other variable, arrays must be declared before they are used. General
form of array declaration is:
Syntax:
Data_type array_name[array_size];
Example:
int ar[10];
int a[3]={12,333,43};
int marks[4]={40,57,89 , 93};
#include<stdio.h>
void main()
{
int i, num[5];
for(i=0;i<5; i++)
{
printf("enter array elements\n");
scanf("%d",&num[i]);
}
printf("\n array elements are: ");
for(i=0;i<5; i++)
{
printf("%d \t",num[i]);
}
}
Q.no.2. Write a program to input any 100 students Marks in an array and display
them.
Q.no.3. write a program to input all subjects mark of a student and to find the
percentage and display them.
54
Declaration of two dimensional array:
c language supports multidimensional arrays also the simplest form of a
multidimensional array is the two dimensional array. Both the row's and column's
index begins from 0.
Syntax:
data-type array_name[row-size][column-size];
Example:
int a[3][4];
A two-dimensional array can be considered as a table which will have x number
of rows and y number of columns. A two-dimensional array, which contains
three rows and four columns can be shown as follows −
Thus, every element in the array a is identified by an element name of the form a[
i ][ j ], where 'a' is the name of the array, and 'i' and 'j' are the subscripts that
uniquely identify each element in 'a'.
Example:-
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
Int a[2][2]={{32,32},
{23,34},
{23,34},
{23,34}};
55
other methods are:
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
a[0][0]=0
a[2][2]=5
56
Q.no.2. WAP to enter the number of 2x2 matrix and display this matrix.
/* 2x2 matrix where enter the elements*/
#include <stdio.h>
# include <conio.h>
int main()
{
int a[2][2],i,j;
printf("Enter elements of matrix\n");
for (i = 0; i < 2; ++i)
{
for (j = 0; j < 2; ++j)
{
printf("Enter a[%d][%d] :- ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
}
for (i = 0; i < 2; ++i)
{
for (j = 0; j < 2; ++j)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
return 0;
}
5.2.1 Character array:
Character array is represent a character easily by char data type whereas
the string is the group of characters can only be represent by character
array. In character array used in null character in the end of the string so
we most used '\0' character on the array.
example:
char a[3]={'a','s','m','\0'};
#include<stdio.h>
#include<conio.h>
void main(){
char language[5][10] = {"Java", "Python", "C++", "HTML", "SQL"};
for(int i=0; i<5; i++)
{
for(int j=0; j<3; j++)
{
printf("%s \t", language[i]);
}
printf("\n");
}
}
Enter 5 names:
Emma
Olivia
Ava
Isabella
Sophia
#include<stdio.h>
#include<conio.h>
void main(){
char name[5][10] = {" Emma", " Olivia", " Ava", " Isabella", "
Sophia"};
for(int i=0; i<5; i++)
{
printf("%s\n",name[i]);
58
}
getch();
}
Enter 5 cast:
Emma thapa
Olivia shahi
Ava rijal
Isabella chand
Sophia sanjyal
59
Q.no.3. Write a c program to find out the average of 4 integers using array.
#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;
int num[4];
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}
avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}
Q.no.4. WAP to display the matrix following patterns:
a) 0 1 b) 1 0 0
1 0 0 1 0
0 1 0 0 1
60
H.W.
WAP to display the following patterns.
Name
1. Ram thapa
2. Shyam thapa
3. Ganesh thapa
4. Sita thapa
5. Gita thapa
6. Rita thapa
#include<stdio.h>
#include<conio.h>
void main()
{
Int x;
Char name[6][20]={“1. Ram thapa”,
“2. Shyam thapa”,
“3. Ganesh thapa”,
“4. Sita thapa”,
“5. Gita thapa”,
“6. Rita thapa”,”\0”};
For (x=0; x<6; x++)
{
printf(“%s \n”, name);
}
getch();
}
Write a c program to find out the average of 10 integers using array.
Write a c program to find out the sum of odd number in 1 to 20 using array.
#include<stdio.h>
#include<conio.h>
Void main()
{
61
Int i, a[100 ], odd=1, sum;
For(i=0; i<20; i++)
{
If (a[i]<20)
{
Sum=odd+sum;
Odd=odd+2;
A[i]=odd;
}
Printf(“sum of odd number is %d ”, sum);
}
Getch();
}
#include <stdio.h>
void main() {
int i, j, m[3[[3], n[3[[3],addition, subtraction;
62
}
getch();
}
64
Write a program to input data in two dimensional array for example 3x3 matrix and display
in matrix form
Soln.
/* a program to input data in two dimensional array*/
#include<stdio.h>
#include<conio.h>
Void main()
{
int i, j, a[3][3];
for(i=0; i<3; i++)
{
For(j=0; j<3; j++)
{
printf(“Input the elements of array \n”);
scanf(“%d”,&a[i][j]);
}
}
for(i=0; i<3; i++)
{
For(j=0; j<3; j++)
{
printf(“%d \t”, a[i][j]);
}
printf(“\n”);
}
getch();
}
65
Write a program to input 2x3 matrix and display in transpose form that is in 3x2 matrix.
2 3 4
1 6 7
4. wAP to find the smallest number among 10 numbers.
5. wAP to input 10 numbers and sort them in descending orders
66
6. Write a program to input two matrices, add two matrices and
display in proper format.
#include <stdio.h>
#include <conio.h>
int main()
{
int a[3][3], b[3][3], sum[3][3], i, j;
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < 3; ++i)
for (j = 0; j < 3; ++j)
{
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
return 0;
}
Class work
1. WAP to input data of any two matrices(3x3) and subtract each other and display
it.
2. Write a program to input data for 2x2 matric and add to each other and also display
it.
68
#include <stdio.h>
#include <conio.h>
void main()
int a[2][3],b[2][3],c[2][3],i,j;
clrscr();
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<2;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
for(i=0;i<2;i++)
for(j=0;j<3;j++)
printf("%5d",c[i][j]);
printf("\n");
69
getch();
6 Functions:
A function is a self-contained subprogram, which means to do some specific,
well-defined task. It is a self-contained block of code that performs a particular
task. Every function will carry out its intended action whenever it is accessed
from some other portion of the program.
A function is a group of statements that together perform a task. Every c program
has at least one function, which is main(), and all the most trivial programs can
define additional functions.
Advantage of function:
Function increases code reusability.
The length of the source program can be reduced
The program development will be faster.
The program debugging will be easier.
Large number of programmer can be in involved.
The program can be tested and compiled independently by different member of
a programming team.
70
6.1 Components of function:
1. function prototype
2. function definition
3. call the function
6.1.1 Function prototype:
Function prototype provides the following information to the computer
The type of the value returned
The name of the function
The number and the type of the arguments that must be supplied in a function
call
Syntax:
return_value function_name(arg1, arg2)
Example:
int sum(int x, int y)
6.1.2 Function definition
A function definition has two principle components:
Function header or function declaratory
Body of the function (logic part)
Syntax:
data_type function_name(arg1, arg2)
{
statement;
}
71
Example:
#include <stdio.h>
int abc(int);
void main()
{
int a,b;
printf("\n enter a number");
scanf("%d",&a);
b=abc(a);
getch();
}
int abc(int a)
{
int p;
p=a*a;
printf("the value of numbers %d",p);
return (p);
}
72
6.2 Types of functions:
Functions are of two types:
6.2.1 Library function:
C has the facility to provide some library function to the programmer for doing
some operations. As an example c has a mathematical function, string handling
function, graphic function etc.
Example :
#include<stdio.h>
#include<math.h>
void main()
{
int n;
printf("enter the number");
scanf("%d",&n);
printf("\n the square root of %d is %f",n, sqrt(n));
}
String functions:
There are various string library functions defined under the header file
string.h
I. strlen( )
this function gives the number of characters as an output, excluding
the terminating null character.
Example:-
/* using strlen() function */
#include <stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
Char s[300];
Int len;
printf(“enter a string”);
scanf(“%s”, &s);
len = strlen(s);
printf (“the string \ %s \ has %d characters \n”, s, len);
getch ();
}
73
enter a string ram bahadur thapa badal
the string ram bahadur thapa badal has 23 characters
II. strcat( )
this function combines two strings together to form a whole string.
/* using strcat() function */
#include <stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
Char abh[30], t[30];
printf(“enter a string source”);
scanf(“%s”, &abh);
III. strcmp()
this function compares two strings such that if two strings are equal then this
function returns 0 else if it return -1 or 1 if either of the string are not equal.
/* using strcmp() function */
#include <stdio.h>
#include<conio.h>
#include<string.h>
74
void main()
{
Char source[30], target[30];
Int cm;
printf(“enter a string source”);
scanf(“%s”, & source);
Void info()
{
Char d;
Printf(“enter your name:”);
Scanf(“%s”,&d);
printf(“my name is %s”,d);
}
b) Function returning no value but passing arguments.
#include<stdio.h>
#include<conio.h>
int sum(int,int);
void main()
{
int a,b,s;
76
printf("enter the two number :");
scanf("%d%d",&a,&b);
s=sum(a,b);
getch();
}
77
c) Function returning value and passing no arguments
#include<stdio.h>
#include<conio.h>
void sum();
void main()
{
int s;
s=sum();
printf("sum of two number is %d",s);
getch();
}
202
sum( )
{
int a,b,c;
printf("enter the two number :");
scanf("%d%d",&a,&b);
c=a+b;
return (c);
}
78
d) Function returning no value and passing no arguments
#include<stdio.h>
#include<conio.h>
void sm();
void main()
{
sm( );
getch( );
}
void sm( )
{
int a, b, c;
c=a+b;
printf(“sum of two number is %d”,c);
}
79
6. WAP to input a number and check whether it is even or odd using
function.
7. WAP to display the your name using function
8. WAP to display the 1 to 20 even number using function
9. WAP to display the following pattern using function
a. 1 3 6 9 15 ………30
b. 2 4 8 16 32……..256
10. WAP to display the sum of n number using function
11. WAP to display the multiplication table of 8 using function
12. WAP to display the numbers which are 101 to 201 using function.
80
13.
Q.no.1. Write a program to calculate sum of 'n' natural numbers using
recursion.
#include<stdio.h>
#include<conio.h> /*Without recursion*/
int sum(int); #include<stdio.h>
void main() #include<conio.h>
{ void main()
int n,f; {
printf("enter the last number"); int n,f,i;
scanf("%d",&n); printf("enter the last number");
f=sum(n); scanf("%d",&n);
printf("sum is %d", f); for(i=1; i<=n; i++)
} {
f=f+i;
int sum(int n) }
{ printf("sum is %d", f);
if(n<=0) getch();
}
return 0;
else
return(n+sum(n-1));
}
N=5
F=15
Sum(){
If n<0
{
5+4
5+4+3
5+4+3+2
5+4+3+2+1=15=sum()
}
}
81
7 Structure
Syntax:
Struct structure_name
{
dataType member1;
dataType member2;
.
.
.
.
};
Example:-
struct employee
{
char name[35];
unsigned int age;
char address[35];
float salary;
}
82
Q.no.2. C Program to Store Information of students Using Structure
#include <stdio.h>
#include <conio.h>
struct StudentData
{
char stu_name;
int stu_id;
int stu_age;
};
void main()
{
struct StudentData k;
k.stu_name = "ram ";
k.stu_id = 12;
k.stu_age = 30;
printf("Student Name is: %s", student.stu_name);
printf("\nStudent Id is: %d", student.stu_id);
printf("\nStudent Age is: %d", student.stu_age);
getch();
}
83
Q.no.3. WAP to store information of 50 students using structure.
#include <stdio.h>
#include <conio.h>
struct student
{
char firstName[50];
int roll[50];
float marks[50];
} s[50];
void main()
{
int i;
printf("Enter information of students:\n");
for (i = 0; i < 50; ++i)
{
s[i].roll = i + 1;
printf("\nFor roll number%d,\n", s[i].roll);
printf("Enter first name: ");
scanf("%s", &s[i].firstName);
printf("Enter marks: ");
scanf("%f", &s[i].marks);
}
printf("Displaying Information:\n\n");
84
Q.no. 4. Write a c program that takes input from the user and stores
std_no, name and percentage of 'n' students in a structure and display
them all records.
#include<stdio.h>
#include<conio.h>
struct studentFolder
{
int std_no[50];
char name[50];
float per[50];
};
void main()
{
int i,n;
struct studentFolder s[100];
printf("enter the number of students");
scanf("%d",&n);
for(i=0; i<n;i++)
{
printf("enter the std_no of students");
scanf("%d",&s[i].std_no);
86
Structure and function:
#include <stdio.h>
#include<conio.h>
void display(char[50], float, unsigned);
struct book
{
char name[50];
float price;
unsigned int pages;
};
void main()
{
printf("\nenter book name %s,\n", b.name);
scanf("%s",&b.name);
printf("\nenter price %d,\n", b.price);
scanf("%d",&b.price);
printf("\nenter pages %d,\n", b.pages);
scanf("%d",&b.pages);
display(b.name,b.price,b.pages);
getch();
}
display(char nam[50], float p, unsigned int pg)
{
clrscr();
printf("\nbook's name =%s",nam);
printf("\nbook's page no %d",p);
printf("\nbook's page no %f",pg);
}
87
Q.no.5. Write a c program that takes input from the user and stores name,
rollno , subject and total of '20' students in a structure and display them
all records in ascending order.
#include<stdio.h>
#include<conio.h>
struct student
{
char name[30];
int rollno;
int sub[3];
int total;
};
void main()
{
int i, n, j;
struct student st[20], temp;
clrscr();
printf("Enter number of students data you want to enter:\n");
scanf("%d",&n);
for(i=0;i < n;i++)
{
printf("Enter name of student %d\n",(i+1));
scanf("%s",&st[i].name);
printf("Enter Roll No of student %d\n",(i+1));
scanf("%d",&st[i].rollno);
printf("Enter marks for 3 subjects of student %d\n",(i+1));
scanf("%d%d%d",&st[i].sub[0],&st[i].sub[1],&st[i].sub[2]);
st[i].total = (st[i].sub[0]+st[i].sub[1]+st[i].sub[2]);
printf("Total Marks of %d student = %d\n",(i+1), st[i].total);
}
for(i=0;i < (n-1);i++)
{
for(j=0;j < (n-i-1);j++)
{
if(st[j].total < st[j+1].total)
{
88
temp = st[j];
st[j] = st[j+1];
st[j+1] = temp;
}
}
}
printf("\n\n\n\t\t******Sorted in descending order******");
for(i=0; i < n;i++)
{
printf("\nName of student: %s",st[i].name);
printf("\nRoll No of student: %d",st[i].rollno);
printf("\nTotal of student: %d\n",st[i].total);
}
getch();
}
8 Union
A union is a special data type available in C that allows to store different data
types in the same memory location. The union statement in the same way as
you did while defining a structure. You can define a union with many
members, but only one member can contain a value at any given time. Unions
provide an efficient way of using the same memory location for multiple-
purpose. The format of the union statement is as follows −
Syntax:-
union [union tag]
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
89
Example:-
union Data
{
int i;
float f;
char str[20];
} data;
Q.no.1 Write a c program where find out the memory location of data
variable in union.
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
90
Example 2:-
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
void main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
}
91
Difference between Structure and Array
ARRAY STRUCTURE
Structure refers to a collection
Array refers to a collection consisting consisting of elements of heterogenous
of elements of homogenous data type. data type.
Array uses subscripts or “[ ]” (square Structure uses “.” (Dot operator) for
bracket) for element access element access
Instantiation of Array objects is not Instantiation of Structure objects is
possible. possible.
Array size is fixed and is basically the Structure size is not fixed as each
number of elements multiplied by the element of Structure can be of different
size of an element. type and size.
Bit filed is not possible in an Array. Bit filed is possible in an Structure.
Array declaration is done simply using Structure declaration is done with the
[] and not any keyword. help of “struct” keyword.
Arrays is a primitive datatype Structure is a user-defined datatype.
Array traversal and searching is easy Structure traversal and searching is
and fast. complex and slow.
struct sruct_name
data_type array_name[size]; {
data_type1 ele1;
data_type2 ele2;
};
Structure elements may or may not be
Array elements are stored in continuous stored in a continuous memory
memory locations. location.
Array elements are accessed by their Structure elements are accessed by their
index number using subscripts. names using dot operator.
92
Differences between Structure and Union
93
9 What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e.,
direct address of the memory location. Like any variable or constant, you
must declare a pointer before using it to store any variable address. The
general form of a pointer variable declaration is −
Syntax:
type *var-name;
Example:
int *ip;
double *dp;d
float *fp;
char *ch c;
Example 1:-
#include <stdio.h>
void main ()
{
int b = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &b; /* store address of b in pointer variable*/
printf("Address of b variable: %x\n", &b );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
}
94
10 File handling
10.1 Concept of data files:
A data file is defined as the collection of data or information which is
permanently stored inside secondary memory as a single unit. We can read,
write, append and delete data in data file as per our requirements. C
language supports number of functions to perform various operations such
as defining file ,opening file, reading file, writing file, appending file and
closing file.
The mode defines the purpose of the file which can be one of the following:
r open an existing file for reading
w open a new file for writing
a open an existing file for appending
r+ open an existing file for both reading and writing
w+ open a new file for both reading and writing
a+ open an existing file for both reading and appending
10.1.2 Closing data file
fclose(filepointer);
10.1.3 getc() and putc() functions:
ch=getc(fp);
putc(ch,fp);
95
10.1.4 getw() and putw() functions:
x=getw(fp);
putw(x,fp);
Q.no.1. Write program to write roll, name and percentage of 5 students to a file.
#include<stdio.h>
void main()
{
FILE *fp;
int roll;
char name[30];
float per;
int i;
fp=fopen("info.txt","w");
for(i=0; i<5; i++)
{
printf("\n enter roll number:");
scanf("%d"&roll[i]);
96
Q.no.2. Write program to write and read roll, name and percentage of 5
students to from data file using fprintf() and fscanf().
#include<stdio.h>
void main()
{
FILE *fp;
int roll;
char name[30];
float per;
int i;
fp=fopen("info.txt","w");
do
{
printf("\n enter roll number:");
scanf("%d"&roll[i]);
fp=fopen("info.txt","r");
printf(" data from the file\n");
while((fscanf(fp," %d\t %s\t %f", &roll, &name, &per))!=EOF)
{
printf(","\n %d\t %s\t %f", roll,name,per);
}
fclose(fp);
}
97