0% found this document useful (0 votes)
13 views

Notes

Uploaded by

akashtj.y
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Notes

Uploaded by

akashtj.y
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

PROGRAMMING IN C

1. What are the various types of


operators?
C supports the following types of
operators Unary
Binary
Unary Plus + Unary Minus -
Increment ++
Decrement --

Arithmetic +,-,*,/,%
Relational <,>,<=,>=,==,!=
Logical &&,||,!
Bitwise &,|,^,<<,>>
Assignment =
Shorthand assignment +=, -=,*=,/=,
%=
Ternary ? :

List different datatypes available in C


Data types are used to specify the type of a variable. In c, the data types are
classified into 3 category. They are,
Primary or Built-in : int , char, float
Derived : array, enum,
pointer User defined : function, structure

1. Write a C program to find factorial of a given number using


Iteration void main()
{
int N=5,I,fact=1;
for(i=1;i<=N; i++)
fact=fact*i;
printf(The factorial value of %d is =%d, N, fact);
}

2. What is the variable? Illustrate with an example


- Variable is a named storage area
- Used to assign a name to a value
- To declare a variable, we need to specify the data type of the value and the variable
name
Data type variable _name ;
- Example
int reg; float avg;

3. What is the importance of keywords in


C? Keywords are reserved identifiers
They performs a specific task , specifies the data type
Keyword can not be used as an identifier
Ex: for , if , int

4. List out various Input & output statements in C


The input & output statements are classified into formatted & unformatted I?O
Formatted I/O : User can able to design/format the output
Unformatted I/O: doesn‘t allow the users to design the output

Type Input Output


Formatted scanf() printf()
Unformatted getch(), getche() putch(), putchar()
getchar() puts()
gets()
7. Explain the decision making statement in c with example programs.

DECISION STATEMENTS
It checks the given condition and then executes its sub-block. The decision statement decides the
statement to be executed after the success or failure of a given condition.

Decision making is about deciding the order of execution of statements based on certain conditions
or repeat a group of statements until certain specified conditions are met. C language handles
decision-making by supporting the following statements,

 if statement

 switch statement

 conditional operator statement (? : operator)

 goto statement

Decision making with if statement

The if statement may be implemented in different forms depending on the complexity of conditions
to be tested. The different forms are,

1. Simple if statement

2. if....else statement

3. Nested if....else statement

4. Using else if stateme

Simple if statement
The general form of a simple if statement is,

if(expression)

statement inside;

statement outside;

If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.
Example:

if...else statement
The general form of a simple if...else statement is,

if(expression)
#include <stdio.h>
{

statement block1;

void
} main( )

{else

{ int x, y;

xstatement
= 15; block2;

} y = 13;

if (x > y )

printf("x is greater than y");

x is greater than y

If the expression is true, the statement-block1 is executed, else statement-block1 is skipped


and statement-block2 is executed.
Example:
#include <stdio.h>

void main( )

int x, y; x =

15;

y = 18;

if (x > y )

printf("x is greater than y");

else

printf("y is greater than x");

y is greater than x

Nested if....else statement


The general form of a nested if...else statement is,

if( expression )

if( expression1 )

statement block1;

else

{
statement block2;

else

statement block3;

}
if expression is false then statement-block3 will be executed, otherwise the execution continues
and enters inside the first if to perform the check for the next if block, where if expression 1 is true
the statement-block1 is executed otherwise statement-block2 is executed.
Example:

#include <stdio.h>

void main( )

int a, b, c;

printf("Enter 3 numbers...");

scanf("%d%d%d",&a, &b, &c);

if(a > b)

if(a > c)

printf("a is the greatest");

else

printf("c is the greatest");

}
else

if(b > c)

printf("b is the greatest");

else

printf("c is the greatest");

else if ladder
The general form of else-if ladder is,

if(expression1)

statement block1;

else if(expression2)

statement block2;

else if(expression3 )

statement block3;

else
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as a true condition is
found, the statement associated with it is executed.
Example :

#include <stdio.h>

void main( )

int a;

printf("Enter a number...");

scanf("%d", &a);

if(a%5 == 0 && a%8 == 0)

printf("Divisible by both 5 and 8");

else if(a%8 == 0)

printf("Divisible by 8");

else if(a%5 == 0)

printf("Divisible by 5");

else

printf("Divisible by none");

}
2. Explain the looping statement in c with example programs.
LOOP CONTROL STATEMENTS

Loop is a block of statements which are repeatedly executed for certain number of times. Types
1. For loop
2. Nested for loops
3. While loop
4. do while loop

'C' programming language provides us with three types of loop constructs:


1. The while loop
2. The do-while loop
3. The for loop

While Loop

A while loop is the most straightforward looping structure. The basic format of while loop is as
follows:
while (condition) {
statements;
}
It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body of the
loop. If a condition is true then and only then the body of a loop is executed. After the body of a
loop is executed then control again goes back at the beginning, and the condition is checked if it is
true, the same process is executed until the condition becomes false. Once the condition becomes
false, the control goes out of the loop.
After exiting the loop, the control goes to the statements which are immediately after the loop. The
body of a loop can contain more than one statement. If it contains only one statement, then the curly
braces are not compulsory. It is a good practice though to use the curly braces even we have a single
statement in the body.
In while loop, if the condition is not true, then the body of a loop will not be executed, not even
once. It is different in do while loop which we will see shortly.
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
The above program illustrates the use of while loop. In the above program, we have printed series
of numbers from 1 to 10 using a while loop.

1. We have initialized a variable called num with value 1. We are going to print from 1 to 10
hence the variable is initialized with value 1. If you want to print from 0, then assign the
value 0 during initialization.
2. In a while loop, we have provided a condition (num<=10), which means the loop will
execute the body until the value of num becomes 10. After that, the loop will be terminated,
and control will fall outside the loop.
3. In the body of a loop, we have a print function to print our number and an increment
operation to increment the value per execution of a loop. An initial value of num is 1, after
the execution, it will become 2, and during the next execution, it will become 3. This
process will continue until the value becomes 10 and then it will print the series on console
and terminate the loop.
\n is used for formatting purposes which means the value will be printed on a new line.

Do-While loop

A do-while loop is similar to the while loop except that the condition is always executed after the
body of a loop. It is also called an exit-controlled loop.
The basic format of while loop is as follows:
do {
statements
} while (expression);
As we saw in a while loop, the body is executed if and only if the condition is true. In some cases,
we have to execute a body of the loop at least once even if the condition is false. This type of
operation can be achieved by using a do-while loop.
In the do-while loop, the body of a loop is always executed at least once. After the body is executed,
then it checks the condition. If the condition is true, then it will again execute the body of a loop
otherwise control is transferred out of the loop.
Similar to the while loop, once the control goes out of the loop the statements which are
immediately after the loop is executed.
The critical difference between the while and do-while loop is that in while loop the while is written
at the beginning. In do-while loop, the while condition is written at the end and terminates with a
semi-colon (;)
The following program illustrates the working of a do-while loop:
We are going to print a table of number 2 using do while loop.
#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=10);
return 0;
}
Output:
2
4
6
8
10
12
14
16
18
20
In the above example, we have printed multiplication table of 2 using a do-while loop. Let's see
how the program was able to print the series.
1. First, we have initialized a variable 'num' with value 1. Then we have written a do-while
loop.
2. In a loop, we have a print function that will print the series by multiplying the value of num
with 2.
3. After each increment, the value of num will increase by 1, and it will be printed on the
screen.
4. Initially, the value of num is 1. In a body of a loop, the print function will be executed in this
way: 2*num where num=1, then 2*1=2 hence the value two will be printed. This will go on
until the value of num becomes 10. After that loop will be terminated and a statement which
is immediately after the loop will be executed. In this case return 0.
For loop

A for loop is a more efficient loop structure in 'C' programming. The general structure of for loop is
as follows:
for (initial value; condition; incrementation or decrementation )
{
statements;
}
 The initial value of the for loop is performed only once.
 The condition is a Boolean expression that tests and compares the counter to a fixed value
after each iteration, stopping the for loop when false is returned.
 The incrementation/decrementation increases (or decreases) the counter by a set value.

Following program illustrates the use of a simple for loop:


#include<stdio.h>
int main()
{
int number;
for(number=1;number<=10;number++) //for loop to print 1-10 numbers
{
printf("%d\n",number); //to print the number
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
The above program prints the number series from 1-10 using for loop.
1. We have declared a variable of an int data type to store values.
2. In for loop, in the initialization part, we have assigned value 1 to the variable number. In the
condition part, we have specified our condition and then the increment part.
3. In the body of a loop, we have a print function to print the numbers on a new line in the
console. We have the value one stored in number, after the first iteration the value will be
incremented, and it will become 2. Now the variable number has the value 2. The condition
will be rechecked and since the condition is true loop will be executed, and it will print two
on the screen. This loop will keep on executing until the value of the variable becomes 10.
After that, the loop will be terminated, and a series of 1-10 will be printed on the screen.
In C, the for loop can have multiple expressions separated by commas in each part.
For example:
for (x = 0, y = num; x < y; i++, y--) {
statements;
}
Also, we can skip the initial value expression, condition and/or increment by adding a semicolon.
For example:
int i=0;
int max = 10;
for (; i < max; i++) {
printf("%d\n", i);
}
Notice that loops can also be nested where there is an outer loop and an inner loop. For each
iteration of the outer loop, the inner loop repeats its entire cycle.
Consider the following example, that uses nested for loops output a multiplication table:
#include <stdio.h>
int main() {
int i, j;
int table = 2;
int max = 5;
for (i = 1; i <= table; i++) { // outer loop
for (j = 0; j <= max; j++) { // inner loop
printf("%d x %d = %d\n", i, j, i*j);
}
printf("\n"); /* blank line between tables */
}}
Output:
1x0=0
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5

2x0=0
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
The nesting of for loops can be done up-to any level. The nested loops should be adequately
indented to make code readable. In some versions of 'C,' the nesting is limited up to 15 loops, but
some provide more.

4. Explain operators in C
C language supports a rich set of built-in operators. An operator is a symbol that tells the compiler
to perform a certain mathematical or logical manipulation. Operators are used in programs to
manipulate data and variables.
C operators can be classified into following types:

 Arithmetic operators

 Relational operators

 Logical operators

 Bitwise operators

 Assignment operators

 Conditional operators

 Special operators

ARITHMETIC OPERATORS
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic
operators.

Operator Description

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denominator

% remainder of division

++ Increment operator - increases


integer value by one

-- Decrement operator - decreases


integer value by one
Relational operators
The following table shows all relation operators supported by C.

Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on


the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right


operand

<= Check if operand on left is smaller than or equal to right


operand

Logical operators

C language supports following 3 logical operators. Suppose a = 1 and b = 0,

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false


Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of
bits from right to left. Bitwise operators are not applied to float or double(These are datatypes, we will
learn about them in the next tutorial).

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

Now lets see truth table for bitwise &, and ^

a b a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

The bitwise shift operator, shifts the bit value. The left operand specifies the value to be shifted and
the right operand specifies the number of positions that the bits in the value have to be shifted
Assignment Operators
Assignment operators supported by C language are as follows.

Operator Description Example

= assigns values from right side a=b


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

-= subtracts right operand from a-=b is same


the left operand and assign the as a=a-b
result to left operand

*= mutiply left operand with the a*=b is same


right operand and assign the as a=a*b
result to left operand

/= divides left operand with the a/=b is same


right operand and assign the as a=a/b
result to left operand

%= calculate modulus using two a%=b is


operands and assign the result same as
to left operand a=a%b

Conditional operator

The conditional operators in C language are known by two more names

1. Ternary Operator

2. ? : Operator
It is actually the if condition that we use in C language decision making, but using conditional
operator, we turn the if condition statement into a short and simple operator.
The syntax of a conditional operator is :

expression 1 ? expression 2: expression 3


Explanation:

 The question mark "?" in the syntax represents the if part.

 The first expression (expression 1) generally returns either true or false, based on which it is
decided whether (expression 2) will be executed or (expression 3)

 If (expression 1) returns true then the expression on the left side of " : " i.e (expression 2) is
executed.

 If (expression 1) returns false then the expression on the right side of " : " i.e (expression 3)
is executed.

Special operator

Operator Description Example

sizeof Returns the size of sizeof(x) return size


an variable of the variable
x

& Returns the &x ; return address


address of an of the variable x
variable

* Pointer to a *x ; will be pointer to


variable a variable x

UNIT- II
Define Array
Array is a collection of similar type of values
All values are stored in continuous memory locations
All values share a common name
Linear data structure. The elements are organized in a sequential order.

1. Name any two library functions for handling string


strlen() – finds the length of a string. It returns an integer value. It counts the no. of
characters except null character & returns the count
strlen(str)
strcpy() – copies the source string into destination string. So, the source string should be
enough to store the destination string.
strcpy(source,destination)
2. Declare a float array of size 5 and assign 5 values to
it Declaration : float price[5];
Initialization : float price[5]={200.50,150.25,25.5,55.75,40.00}; (or)
float price[]={1.2,3.4,6.5,7.8,9.8};

3. Give an example for initialization of string array


String is a character array.
Collection of one or more characters- enclosed with in double quotes
Declaration : char name[10];
Initialization : char name[10]=‖India‖;
car name[10]={‗I‘,‘n‘,‘d‘,‘i‘,‘a‘};
The char array is terminated by ‗\0‘

4. How a character array is declared


Declaration : char name[n];
This array can store n-1 characters.
Initialization : char name[10]=‖India‖;
char name[10]={‗I‘,‘n‘,‘d‘,‘i‘,‘a‘};
The char array is terminated by ‗\0‘

5. Write example code to declare two dimensional array


Two dimensional array is an array with two subscript values. First subscript specifies the
row & second subscript specifies the column. Used to process matrix operations.
Declaration : datatype array_name [r][c];
int matrix A[10][10];
This matrix A can store 100 elements in a row major order.

1. Write a c program to read and display elements of a 2D matrix .


#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
printf(“enter the elements ”);
for(i=0; i<2; i++)
{ for(j=0;j<3;j++) {
scanf(“%d”,&disp[i][j]);

printf(“The elements of the matrix are\n”);


for(i=0; i<2; i++)
{
for(j=0;j<3;j++)
{
printf(“%d”, disp[i][j]);
}
printf(“\n”);
}
2. C program to perform Matrix addition

#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and
100): "); scanf("%d", &r);
printf("Enter the number of columns (between 1 and
100): "); scanf("%d", &c);
printf("\nEnter elements of 1st
matrix:\n"); for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

printf("Enter elements of 2nd


matrix:\n"); for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}

// adding two
matrices for (i =
0; i < r; ++i)
for (j = 0; j < c; ++j) {
sum[i][j] = a[i][j] +
b[i][j];
}

// printing the result


printf("\nSum of two
matrices: \n"); for (i = 0; i < r;
++i)
for (j = 0; j < c; ++j) {
printf("%d ",
sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}

return 0;
}

1. What is a function?
 Function is a set of instructions
 Self contained block
 Performs a specific task
 Used to avoid redundancy of code
2. What is the need for functions?
 To reduce the complexity of large programs
 To increase the readability
 To achieve reusability
 To avoid redundancy of code
 To save Memory
3. What are the uses of pointer?
 Saves Memory Space
 Used for dynamic memory allocation
 Faster execution
 Used to pass array of values to a function as a single argument
4. What is an Address operator & Indirection operator?
 Address operator: & -used to assign the address to a pointer variable,
Referencing operator
 Indirection operator : *- Dereferencing operator is used to access the value at
the pointer variable
Ex: int a=5;
i nt *p=&a;

printf(“%d”,*(p));
5. Compare actual parameter & formal argument
Actual argument: Specified in the function call statement. Used to supply the
input values to the function either by copy or reference

Formal argument: Specified in the function definition statement. It takes either copy
or address of the actual arguments

6. How is pointer arithmetic done?


Pointer Arithmetic:
Valid operation
 Pointer can be added with a constant
 Pointer can be subtracted with a Constant
 Pointer can be Incremented or Decremented Not
Valid
 Two pointers can not be added,subtracted,multiplied or divided
Ex: int a=10
int *p=&a; p
2000 10a
p=p+1;
2002

 The pointer holds the address 2000. This value is added with 1.
 The data type size of the constant is added with the address. p=
2000+(2*1)=2002
7. What is a function prototype?
 Function prototype is a function declaration statement.
Syntax
return_type function_name( parameters_list)

Example: int factorial(int);


8. What are the steps in writing a function in a program?
Function Declaration (Prototype declaration):
 Every user-defined functions has to be declared before the main().
Function Callings:
 The user-defined functions can be called inside any functions like main(),
userdefined function, etc.
Function Definition:
 The function definition block is used to define the user-defined
functions with statements.

9. State the advantages of user defined functions over pre-defined function.


 A user defined function allows the programmer to define the exact function of the
module as per requirement. This may not be the case with predefined function. It
may or may not serve the desired purpose completely.
 A user defined function gives flexibility to the programmer to use optimal
programming instructions, which is not possible in predefined function.

10. Write the advantages and disadvantages of recursion.


Recursion makes program elegant and cleaner. All algorithms can be defined recursively
which makes it easier to visualize and prove.
If the speed of the program is vital then, you should avoid using recursion.
Recursions use more memory and are generally slow. Instead, you can use loop.

11. What is meant by Recursive function?


 If a function calls itself again and again, then that function is called
Recursive function.

Example:
void recursion()

recursion(); /* function calls itself */

}
int main()

recursion();

}
}

1. Explain about pointers and write the use of pointers in arrays with suitable example.
Ans: Pointers in C language is a variable that stores/points the address of another variable. A
Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable might
be belonging to any of the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that ―p‖ is pointer variable and not a normal
variable. #include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p =
&a[0] for (i = 0; i < 5; i++)
{
printf("%
d", *p);
p++;
}

return 0;
}

STRUC
TRES

1. Compare arrays and structures.


Comparison of arrays and structures is as follows.
Arrays Structures
A structure is a collection of data items of
An array is a collection of data items of same different data types. Structures can be declared
data type. Arrays can only be declared. and defined.

There is no keyword for arrays. The keyword for structures is struct.


An array cannot have bit fields. A structure may contain bit fields.
An array name represents the address of the A structure name is known as tag. It is a
starting element. Shorthand notation of the declaration.

2. Compare structures and unions.

Structure Union
Every member has its own memory. All members use the same memory.
The keyword used is struct. The keyword used is union.
All members occupy separate memory location, Different interpretations for the same memory
hence different interpretations of the same location are possible. Conservation of memory
memory is
location are not possible. Consumes more space possible
compared to union.

3. Define Structure in C.
C Structure is a collection of different data types which are grouped
together and each element in a C structure is called member.
If you want to access structure members in C, structure variable should be declared.
Many structure variables can be declared for same structure and
memory will be allocated for each separately.
It is a best practice to initialize a structure to null while declaring, if we don‘t
assign any values to structure members.
4. What you meant by structure definition?
A structure type is usually defined near to the start of a file using a
typedef statement. typedef defines and names a new type, allowing its use
throughout the program. typedefs usually occur just after the #define and
#include statements in a file.
Here is an example
structure definition.
typedef struct { char
name[64];
char course[1 28];

int
ag
e;

int year;
} student;

This defines a new type student variables of type student can be declared as
follows. student st_rec;
5. How to Declare members in Structure?
A struct in C programming language is a structured (record) type that
aggregates a fixed set of labeled objects, possibly of different types, into a
single object.
The syntax for a structure definition in C is:
struct tag_name
{
type attribute;

type attribute2;
/* ... */
};
6. What is meant by Union in C?
A union is a special data type available in C that enables you to store
different data types in the same memory location. 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 multi-
purpose.
7. How to define a union in C.
To define a union, you must use the union statement in very similar
was as you did while defining structure. The union statement defines a new
data type, with more than one member for your program. The format of the
union statement is as follows:
union [union tag]

{
member

definition;
member
definition;
...
member definition;
} [one or more union variables];

1. Write a C program to create mark sheet for students using self referential structure.

#include<stdio.h>

#include<conio.h>

struct mark_sheet{

char name[20];

long int rollno;

int marks[10];

int total;

float

average; char

rem[10];

char cl[20];

}students[100];

int main(){

int

a,b,n,flag=1;

char ch;
clrscr();

printf("How many students : \n");

scanf("%d",&n);

for(a=1;a<=n;++a)

{
clrscr();

printf("\n\nEnter the details of %d students : ", n-

a+1); printf("\n\nEnter student %d Name : ", a);

scanf("%s", students[a].name);

printf("\n\nEnter student %d Roll Number : ", a);

scanf("%ld", &students[a].rollno);

students[a].total=0;

for(b=1;b<=5;++b){

printf("\n\nEnter the mark of subject-%d : ", b);

scanf("%d", &students[a].marks[b]);

students[a].total += students[a].marks[b];

if(students[a].marks[b]<40)

flag=0;

students[a].average = (float)(students[a].total)/5.0;

if((students[a].average>=75)&&(flag==1))

strcpy(students[a].cl,"Distinction");

else

if((students[a].average>=60)&&(flag==1))

strcpy(students[a].cl,"First Class");

else

if((students[a].average>=50)&&(flag==1))

strcpy(students[a].cl,"Second Class");

else

if((students[a].average>=40)&&(flag==1))

strcpy(students[a].cl,"Third Class");

if(flag==1)
strcpy(students[a].rem,"Pass");

else

strcpy(students[a].rem,"Fail");

flag=1;

for(a=1;a<=n;++a)

{ clrscr();

printf("\n\n\t\t\t\tMark Sheet\n");

printf("\nName of Student : %s", students[a].name);

printf("\t\t\t\t Roll No : %ld", students[a].rollno);

printf("\n ");

for(b=1;b<=5;b++)

printf("\n\n\t Subject %d \t\t :\t %d", b, students[a].marks[b]);

printf("\n\n \n");

printf("\n\n Totl Marks : %d", students[a].total); printf("\t\t\

t\t Average Marks : %5.2f", students[a].average); printf("\n\

n Class : %s", students[a].cl);

printf("\t\t\t\t\t Status : %s", students[a].rem);

printf("\n\n\n\t\t\t\t Press Y for continue . . . ");

ch = getche();

if((ch=="y")||(ch=="Y"))

continue;

return(0);

}
FILE PROCESSING
1. Why files are needed?
 When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the
contents of the file using few commands in C.
 You can easily move your data from one computer to another without any changes.

2. Types of Files
When dealing with files, there are two types of files you should know about:

1. Text files
2. Binary files

Text files

Text files are the normal .txt files that you can easily create using Notepad or any simple text
editors. When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents. They take minimum effort to maintain, are easily
readable, and provide least security and takes bigger storage space.

Binary files

Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they store it
in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security
than text files.

3. Enlist the File Operations.


In C, you can perform four major operations on the file, either text or binary:

1. Creating a new file


2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
Working with files
When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and program.

FILE *fptr;

4. How to open a file?


Opening a file is performed using the library function in the "stdio.h" header file: fopen().
The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode") where fileopen is the name of the file to be opened.

5. List the opening modes in standard I/O

File Meaning of Mode During Inexistence of file


Mod e

r Open for reading. If the file does not exist, fopen() returns
NULL.
If the file exists, its contents are
w Open for writing.
overwritten. If the file does not exist, it
will be created.
Open for append. i.e, Data is
a If the file does not exists, it will be created.
added to end of file.
r+ Open for both reading and writing. If the file does not exist, fopen() returns
NULL.
If the file exists, its contents are
w+ Open for both reading and writing.
overwritten. If the file does not exist, it
will be created.
a+ Open for both reading and the file does not exists, it will be created.
appending.
6. How to close a file?
The file (both text and binary) should be closed after
reading/writing. Closing a file is performed using library
function fclose().

Syntax is fclose(fptr); //fptr is the file pointer associated with file to be


closed. Reading and writing to a text file

For reading and writing to a text file, we use the functions fprintf() and fscanf().

They are just the file versions of printf() and scanf(). The only difference is that,
fprint and fscanf expects a pointer to the structure FILE.

7. Write short notes on fprintf ().


This function is same as the printf() function but it writes the data into the file,
so it has one more parameter that is the file pointer.
Syntax: fprintf(fptr, "controlcharacter",variable-names);
Where fptr is a file pointer
Control character specifies the type of data to be printed into file.
Variable-names hold the data to be printed into the file.

8. Write short notes on fscanf ().


This function is same as the scanf() function but this reads the
data from the file, so this has one more parameter that is the file
pointer.

Syntax: fscanf(fptr, "control character", &variable-names);


Where fptr is a file pointer
Control character specifies the type of data to be read from the file.
Address of Variable names are those that hold the data read from the file.

Types of File Operations

Files are not made for just reading the Contents, we can also Perform Some other
operations on the Files those are Explained below As :

1) Read Operation: Meant To Read the information which is Stored into the Files.
2) Write Operation: For inserting some new Contents into a File.
3) Rename or Change the Name of File.
4) Copy the File from one Location to another.
5) Sorting or Arrange the Contents of File.
6) Move or Cut the File from One Place to Another.
7) Delete a File
8) Execute Means to Run Means File Display Output.

1. Write a C program to read name and marks of n number of students from


user and store them in a file.
#include <stdio.h>
#include<conio.h>
int main(){
char name[50];
int marks,i,n;
clrscr();
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr; fptr=(fopen("C:\\
student.txt","w")); if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
getch();
return 0;
}
2. Write a C program to read name and marks of n number of students from
user and store them in a file. If the file previously exits, add the
information of n students.
#include <stdio.h>
#include<conio.h>
int main(){
char name[50];
int marks,i,n;
clrscr();
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr; fptr=(fopen("C:\\
student.txt","a"));
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
getch();
return 0;
}
fclose(fptr);
getch();
}

You might also like