You are on page 1of 38

Q) Define algorithm and flowchart?

Ans:An algorithm is a step by step description of how to arrive at a solution. It is finite set of instructions which
when followed in sequence solves a particular task. Start
Once algorithm is written, it can be implemented in any high level language.
Algorithm to add two numbers
Step 1: Input the first number as A Read A, B
Step2: Input the second number as B
Step3: Set Sum = A + B
Step4: Print Sum Sum=A+B
Step 5: End
Flow chart is a graphical or symbolic representation of an algorithm. Print Sum
Flow chart to add two numbers and display the sum is as shown in the figure
Start
Q) What is Token and explain?
Ans: Tokens are basic building blocks of C Programming. Each and every smallest individual units in a C
program are known as C tokens.
No Token Type Example
1 Keyword Keywords are reserved words by compiler. while
2 Variables Variables are named locations in memory. sum
3 Constants Constants are assigned to variables 89
4 Special Symbols Used in different declarations in C ( ), {}
5 Operators Used in expressions /,*,+
6. String Sequence of characters “hello”

Q) Difference between while and do-while Flow chart for while loop
Flow chart for do-while loop

Body of loop
False
Condition
?
False
Conditio
n? True
True
True Body of loop
False
StatementX StatementX

Ans: The only difference is


In a do-while loop, test condition is tested after the body of the loop. Hence body of loop is executed atleast
once even if the condition is false. The do-while loop is also called post test or exit controlled loop.
In while loop, test condition is tested before the body of the loop. only if the condition is true, the body of the
loop is executed. The while loop is also called pre test or entry controlled loop.

Q) What is software?
Ans:
Software is a set of programs. A program is a set of instructions arranged in a sequence to guide a computer to
solve a problem.
Computer software is written by programmers using a programming language. Computer software is divided
into 2 categories
• System software
• Application software
System software allows a user to interact with the computer hardware.and provides a platform for running
application software. System software is responsible for controlling and managing hardware components of a
computer system. Ex: Operating System, Compiler, BIOS, Device Drivers.
Application Software performs specific task with the help of system software. Ex: Word processors, Image
editors, Spread sheets etc..

Q) Write about constants in C


Constants are identifiers whose value do not change during the execution of a program.
Constants can be declared using const keyword or using the preprocessor command define
Ex: const float pi = 3.14; pi is a constant whose value cannot be changed
#define PI 3.14
Types of C constants:
S.n Constant type Example Rules for constructing C constant
o
1 Integer constants 53762, -478, • Must have atleast one digit
• It must not have a decimal point
2 Real or Floating point 10.45, 0.5e2,14E-2 • Must have atleast one digit
constants • It must have a decimal point
5 character constants ‘A’ , ‘B’, ‘C’ Single character enclosed in single quotes
6 string constants “ABCD” , “Hai” Sequence of characters enclosed in double
quotes

Q) Write any two header files in C.


Ans:
It is not possible to write our own output functions every time we wanted to communicate with the computer.
So we use header files that have standard functions which can be included in our programs. Header files names
end with ‘dot h’ (.h) extension.
Example of standard header files are :
1. stdio.h : Contains standard Input and output and file operation functions. Some functions defined in
stdio.h are
S.no Function Description
1 printf() Prints the output on the screen
2 scanf() Reads a character, string, numeric data from keyboard.
3 gets() It reads line from keyboard
4 getchar() It reads character from keyboard
5 puts() It writes line to o/p screen
6 putchar() It writes a character to screen
7 fflush() flushes a file
2. conio.h: provide console input/output functions. Some of the functions defined in conio.h are
S.n Function Description
o
1 clrscr() This function is used to clear the output screen.
2 getch() It reads character from keyboard
3 getche() It reads character from keyboard and echoes to o/p screen
Long Answer Questions
1. Explain data types in C .Explain with examples.
Ans: The data type of a variable determines how much space it occupies in memory. It defines the type of data and
operations that can be performed on the data.
Basic data types and their size in bytes in a 16 bit computer is shown in the table below.
Keyword Size in Range Use Example
used bytes

character data char 1 -128 to 127 To store characters char gender = ‘m’;
type
Integer data type int 2 -32767 to 32768 To store integers int num=10;

Floating point float 4 3.4E-38 to To store floating float discount = 12.5;


data type 3.4E+38 point numbers

Double data type double 8 1.7E-308 to To store big floating double sal = 1234567.12345;
1.7E+308 point numbers

Valuless Void 0 --- ---

There are 4 type modifiers that can be applied to the basic data types. They are:
unsigned, signed, short and long.
All the modifiers (long, short, unsigned and signed) can be applied to integer data type.
Only signed and unsigned can be applied to character data type.
Only long can be applied to double data type.

Detailed list of data types

Keyword used Size in bytes Range Example

char 1 -128 to 127 signed char status= ‘u’


signed char
int 2 -32767 to 32768 short int num = -12;
signed int
short int
signed short int

unsigned int 2 0 to 65535 unsigned short int num = 12;


unsigned short int

long int 4 -2147483648 to 2147483647 long int num = -12345678;


signed long int

unsigned long int 4 0 to 4294967295 unsigned long int=1234567890;

long double 10 3.4E-4932 to 1.1E+4932 long double population = 123456789.1234567

Q) Explain decision making statements in C.


Ans: Many programs require a logical condition to become true for executing a particular statement / group of
statements. These statements are known as decision making statements.

a) If statement: The if statement is used to control the flow of execution of statements. The syntax and flowchart of is
statement is as shown below.

Example:

/* program to give a discount of Rs.500 if the total amount is above 5000*/

#include <stdio.h>
output: Total amount to be paid = 5500
void main()

int amount = 6000;

if (amount > 5000)

amount = amount-500;

printf(“Total amount to be paid = %d”,amount);

if-else statement: In if else control statement, group of statements are executed when condition is true. If condition is
false, then else part statements are executed.
Example:

#include <stdio.h>

int main()
Output:
{
m and n are not equal
int m=40,n=20;

if (m == n)

printf("m and n are equal");

else

printf("m and n are not equal");

Switch statement:

The switch makes one selection when there are several choices to be made.

The break statement is used inside each case of switch . It causes


immediate exit from the switch statement and continue onto the next
statement outside the switch statement.

When we execute this form of switch statement, first the test


expression is evaluated. the value of expression is compared one –by-
one, with value-1, value--2 …valuen . When a match is found, the
program executes the following that case. The execution continues till a break statement is found or the switch
statement is completed.

If there is no match the statements in the default case gets executed. Syntax of switch is as follows

Switch(test expression)

case value-1: statementblock-1; break;

case value-2: statementblock-2; break;

default: defaultblock;

Q) Write a c program to perform all arithmetic operations using switch-case.

#include<stdio.h>
#include<conio.h>
void main()
{
int ch;
float a,b,res;
clrscr();
printf(“Enter two numbers:”);
scanf(“%f%f”,&a,&b);
printf(“\nMenu\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division”);
printf(“\nEnter your choice:”);
scanf(“%d”,&ch);

switch(ch)
{
case 1: res=a+b;
break;
case 2: res=a-b;
break;
case 3: res=a*b;
break;
case 4: res=a/b;
break;
default: printf(“Wrong choice!!nPress any key…”);
}
printf(“nResult=%f”,res);
getch();
}

Q) Explain hardware components of a computer.

Ans: A computer is made up of many parts:


• Input/Output (I/O) devices – These allow you to send information to the computer or get information from the
computer.
• Central Processing Unit – CPU or Processor for short. The brain of a computer. Does all the
computation/work for the computer.
• Memory –any form of electronic storage is referred to as memory. There are two types of memories.
1. Primary memory
2. Secondary memory
Primary memory
a) RAM holds data and instructions as long as the program is being processed by the processor.
RAM is a volatile memory as data in the RAM is lost when the power is switched off.
The cpu can access any other location in memory directly in random manner and hence it is called random
access memory.

b) ROM: ROM is a non- volatile memory as data in the ROM is not lost when the power is switched off.
ROM can also be accessed randomly.

Secondary memories are used to store large amounts of data. They are inexpensive than primary memories.
They are also non-volatile.
A drive is used to read the contents of a hard disk, CD , DVD or a floppy.
a) hard disk drive (HDD)
Accessing the hard drive for information takes time.
b) CD ROM drive– A device used to read CD-ROMs. CD-RW drive is used to read data/ write data from/to
CD-RW disks.
c) DVD ROM drive – A device that is used to read DVDs. DVD-RW drive is used to read data/ write data
from/to DVD-RW disks.

c) Floppy Drive – A device that is used to read/write to floppy diskettes.

• Motherboard – A circuit board that allows the CPU to interact with other parts of the computer.
• Power Supply – Gives your computer power by converting alternating current (AC) supplied by the wall
connection to direct current (DC).
• Expansion Cards – Used to add/improve functionality to the computer.
a. Sound Card – Used to input and output sound under program control. Sound cards provide better sound
quality than the built in sound control provided with most computers.
b. Graphics Card – Used to convert the logical representation of an image to a signal that can be used as input
for a monitor.
c. Network Card – Used to provide a computer connection over a network. Transmit data at 10/100/1000 Mb/s.
• Fan – Keeps your computer cool. If the inside of your computer becomes too hot, then the computer can
overheat and damage parts.
• Heatsink – Used to disperse the heat that is produced inside the computer by
the CPU and other parts by increasing surface area.
• Ports – Means of connecting peripheral devices to your computer.
Q) Explain different sections of a C program. (or) Explain the structure of C

Ans:
Documentation section
pre-processor directives
global declarations
main()
{
local variables to function main ;
statements associated with function main ;
}
f1()
{
local variables to function 1 ;
statements associated with function 1 ;
}
f2()
{
local variables to function f2 ;
statements associated with function 2 ;
}
Preprocessor Directives: It is not possible to write our own output functions every time we wanted to
communicate with the computer. So we use header files that have standard functions which can be included in
our programs.
All pre-processor directives begin with a # and the must written in the beginning of the c program
#include <stdio.h>
Documentaion section contains a set of comments giving the name of the program, the author and other
details which the programmer would like to use later. Comments are non-executable
 Single Line Comment Starts with ‘//’ . used to comment out just Single Line in the Code written after //.
 Multi line comments starts with /* and ends with */.
Multi line comments comment out multiple lines written between /* and */

main()
All C programs will consist of at least one function. The only function that has to be present is the function
called main. Execution of a C program starts with main().
User Defined Functions
Any number of user defined functions can be written. All functions including main() are divided into 2 parts.
1. declaration section
2. statement section
declaration section is used to describe the data that will be used in the function. The data declared within a
function will be visible only within the function and will be removed from memory once the control goes out of
the function.
statement section contains the code that manipulates the data to perform a specified task.
Global declarations : globally declared variables are accessed through out the program and will be in memory
until the program runs.

Q)Explain different types of operators in C.

Ans:
S.no Types of Operators Description
1 Arithmetic operators These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus
2 Assignment operators These are used to assign values to variables.
(=)
3 Relational operators These are used to compare the values of two variables
4 Logical operators These operators are used to perform logical operations on expression.
5 Bit wise operators These operators are used to perform bit operations on variables.
6 Conditional (ternary) Conditional operators return one value if condition is true and returns
operators another value if condition is false.
7 Increment/decrement These operators are used to either increase or decrease the value of the
operators variable by one.
8 Special operators &, *, sizeof( )
Arithmetic Operators in C:
S.no Arithmetic Operators Operation Example
1 + Addition A+B
2 - Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
Assignment operators in C:
Operators Example Explanation
Simple assignment operator = sum = 10 10 is assigned to variable sum
Compound assignment operators += sum += This is same as sum = sum + 10
(+=, *=, /=, %=, etc.. 10

Relational operators in C:
S.no Operators Example Description
1 > x>y x is greater than y
2 < x<y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y
Logical operators in C:
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and logical NOT (!).
S.no Operators Name Example Description
1 && logical AND (x>5)&&(y<5) It returns true when both conditions are true
2 || logical OR (x>=10)||(y>=10) It returns true when at-least one of the condition is true
3 ! logical NOT ! It reverses the state of the operand
((x>5)&&(y<5))
Bit wise operators in C:
Decimal values are converted into binary values and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR), << (left shift)
and >> (right shift).
Truth table for bit wise operation Bit wise operators
x y x|y x & y x ^ y Operator_symbol Operator_name
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
<< Left Shift
>> Right Shift

Conditional or ternary operators in C:


Conditional operators return one value if condition is true and returns another value is condition is false.
This operator is also called as ternary operator.
Syntax : (Condition? true_value: false_value);
Example : (A > 100 ? 0 : 1);.
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional
statements.
Increment/decrement Operators
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: - - var_name; (or) var_name - -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : - – i ; i – - ;
Special Operators in C:
Below are some of special operators that C language offers.
S.no Operators Description
1 & This is used to get the address of the variable.
Example : &a will give address of a.
2 * This is used as pointer to a variable.
Example : * a where, * is pointer to the variable a.
3 Sizeof () This gives the size of the variable.
Example : size of (char) will give us 1.

Q) Write a program to find biggest among three numbers.


#include <stdio.h>
void main()
{
float a, b, c;
Output:
printf("Enter three numbers: "); Enter three numbers:3
scanf("%f %f %f", &a, &b, &c); 4
if(a>b && a>c) 5
printf("Largest number = %f", a); Largest number = 5
else if(b>c)
printf("Largest number = %f", b);
else
printf("Largest number = %f", c);

Q)Explain about the looping making statements in C.


loop control statements : repeatedly executes a statement/ block of statements as long as a given condition is
true.
Control comes out of the loop statements once condition becomes false.
Types of loop control statements in C:
There are 3 types of loop control statements in C language. They are,
1. for 2. while 3. do while
While loop:
/* Program to print the natural numbers from 1 to 5 using while loop*/
#include <stdio.h>
void main()
The syntax of while loop is as follows:
{
while(condition)
int i=1; {
statement(s);
while(i < 5) }
{
printf(“%d\n”,i);
i++;
}
}

Do while loop:
/* Program to print the natural numbers from 1 to 5 using do - while loop*/
#include <stdio.h>
void main() Syntax of do while loop is as follows:
{
int i=1;
do
{ do {
printf(“%d\n”,i); statements;
i++; Syntax of for loop is as follows:
} while(i < 5); }
for (exp1; exp2; expr3)
{ while (condition);
}
statements;
For loop:
}
/* Program to print the natural numbers from 1 to 10 using for loop*/
Where,
#include <stdio.h> exp1 – variable initialization
( Example: i=0, j=2, k=3 )
void main()
exp2 – condition checking
{ ( Example: i>5, j<3, k=3 )
exp3 – increment/decrement
( Example: ++i, j–, ++k )
int i;
for(i=1;i < 5;i++)
{
printf(“%d\n”,i);
}
}

Output: 1
2
3
4
5
Q) Whys is clrscr() used?
clrscr() will clear the output of previous execution. It is defined in conio.h header file.

Q) Explain about the execution of c program.

Source code
is the program written by user.
ex: factorial.c

Compiler
converts the c program into
machine level language

Object code
ex: factorial.obj

Object code of header Linker


files included
Ex: stdio.h

Executable

ex: factorial.exe
Functions
Definition: Functions are self contained and independent block of statements.
C allows a big program to be divided into segments known as functions.
Need for functions
1. Code reuse.
2. Dividing a program into functions allows each function to be tested separately.
3. A large program may not fit in main memory.
Using Functions
While using functions we use the following terminology
1. If a function f() uses another function g().
f() is called calling function and g() is called called function
2. Function call
When a function is called, the compiler jumps to the called function to execute the statements of called function.
When the called function is executed, the program control passes back to the calling function

main() int f1(int z) Here main() is calling function and f1() is called function
{ {
3. int x, y; …… Inputs given to function are called parameters / arguments.
y= f1(x); return z; Arguments are 2 types
……. } i) Actual arguments: arguments given in function call.
} Here x is actual argument
ii) Formal arguments : arguments given in function
definition. Here z is called formal argument.

4. Return statement:
return statement terminates the execution of a function and returns the control to the calling function.
5. Function declaration/ Function prototype
Before using function, the compiler must know about its return type and number and type of arguments the
function takes
Syntax: return_type function_name (datatype variable1…..);
6. Function definition
When a function is defined space is allocated for that function in memory f1()
A function definition consists of {
i) Function header : …..
Syntax: return_type function_name (datatype variable1…..) …..
ii) Function body : }
contains code to perform specific task
Passing arguments to functions
Arguments can be passed by calling function in 2 ways
1. Call by value: In this method, the called function creates new variables and
copies the values of arguments passed to it.
If the values of arguments are modified, the modified values can be sent to caller using return statement.
Advantages: variables, literals (Ex: 6), expressions (x+1) can be passed using call by value
Disadvantage: copying arguments requires more memory and takes lot of time.
2. Call by reference : In this method, the function receives address of the
arguments. Changes made to arguments in called function will also change the values in calling function
Advantages: A function can return only one value. To return multiple values, call by reference is used
/* swapping using call by value */ /* swapping using call by reference */
void swap(int , int); void swap(int *, int *);
void main() void main()
{ {
int a ,b; int a ,b;
clrscr(); clrscr();
printf(“enter two numbers”); printf(“enter two numbers”);
scanf(“%d%d”, &a,&b); scanf(“%d%d”, &a,&b);
printf(“values before swapping = %d \t%d”, a, b); printf(“values before swapping = %d \t %d”, a, b);
swap(a,b); swap(&a,&b);
getch(); getch();
} }
void swap ( int x, int y) void swap ( int *x, int *y)
{ {
int temp; int temp;
temp =x; temp =*x;
x=y; *x=*y;
y=temp; *y=temp;
printf(“values after swapping = %d\t %d”, x, y); printf(“values after swapping = %d \t %d”, *x, *y);
} }

Types of functions:
There are 2 types of functions
1. Built in / pre-defined functions: these are stored as library files. Ex: printf, scanf, abs(), strlen()
2. User defined functions: these functions are defined by the user with his own logic. Ex: main(), factorial()
Categories of functions
1. Functions with arguments and with return type
2. Functions with arguments and without return type
3. Functions without arguments and without return type
4. Functions without arguments and with return type
Recursion
Recursive function is a function that calls itself.
Every recursive function must have an exit condition/ terminating condition / stop condition. If not,
recursive function will call itself indefinitely.
When the problem can be defined in recursive manner, then recursion can be used.
Advantages:
1. Recursive solutions are shorter and simpler than non- recursive solutions.
2. Code is clearer and easier to use.
3. Follows divide and conquer to solve problems
Disadvantages:
1. Recursion is difficult concept to some programmers
2. Recursion uses system stack. If the system stack is limited, it is difficult to implement recursion
3. uses more memory and time to execute
4. it is difficult to find errors.
Example: 1 if a=1
factorial(a) =
a*factorial(a-1) if a > 1

Types of Recursion
1. Direct recursion: a function is said to be directly recursive if it is explicitly calls itself.
2. Indirect Recursion: a function is said to be indirectly recursive if it calls another function which
ultimately calls it.
3. Tail Recursion: if no operations are pending to be performed when the recursive function returns to its
caller.
4. Linear Recursion: when the pending operation (if any) does not make another recursive call to the
function
5. Non linear / Tree recursion: when the pending operation makes another recursive call to the function
Scope of a variable
Scope is accessibility and visibility of the variables.
Variables in C has 4 types of scope
1. block scope:
a statement block is a group of statements enclosing within { and }. If a variable is declared
within a statement block , as soon as control exits the block, the variable will be removed from
memory. Such a variable is said to have block scope.
2. function scope: variable is accessible and visible from the beginning to end of a function
3. program scope: variable is accessible and visible from the beginning to end of a program
4. file scope: variable is accessible and visible from the beginning to end of a file

Storage Classes
The storage class defines scope (visibility) and lifetime of variable and functions declared within a C program.
The storage class will determine
1. where the variable will be allocated memory ( in register or main memory etc...)
2. how long the variable stays in memory (life time )
3. scope of the variable i.e, the part of C program in which the variable is accessible or visible.
4. whether the variable will be automatically initialized or not.
C supports 4 storage classes.
1. automatic
2. register
3. external
4. static

Comparison of storage classes


Feature Storage class
auto extern register static
Accessibility Within function or block in Within all Within function or Local: Within
which it is declared program files that block in which it is function or block in
are part of a declared which it is declared
program Global: Within the
program in which it
is declared
Storage Main memory Main memory CPU register Main memory
Existence Exists in memory as long as Exists through out Exists in memory as Local: Exists
the control is within the the execution of long as the control is through out the
block or function in which it the program within the block or execution of the
is declared. Once the control function in which it is program
returns from function or declared. Once the Global: Exists
block, it is removed from control returns from through out the
memory function or block, it is execution of the
removed from memory program files
Default Garbage Garbage Garbage zero
Value

Array: It is collection of similar data type elements. All Elements of array are stored in contiguous memory
locations.

Declaration of Arrays:
An array can be declared by specifying 3 things
1. Data type: what kind of values it can store Ex: int , char , float etc..
2. Name: to identify the array
3. Size: the maximum number of values the array can hold
Syntax:
type name[size]

Example: int marks[3];


marks is an array of integer type and it can hold maximum 3 elements. marks is pointer that holds the address of
first element (&marks[0])

Initialization of array (or) storing values in arrays


All Elements of array are stored in contiguous memory locations.
Memory location
1000 1002 1004
addresses
95 96 97
marks[0] marks[1] marks[2]
1. Initialization at the time of declaration
int marks[3] = { 95,96,97}
Here since marks stores integer values. Each element in array requires 2 bytes. If marks[0] is stored at memory
location 1000 then second element (marks[1]) is stored at memory location 1002 and so on.
2. Taking values of all the array elements (marks[0], marks [1], marks[2]) from user
Ex:
for(i=0;i<3;i++)
{
printf (“enter marks of student no. %d”,i);
scanf(“%d”,&marks[i];
}

3. Giving values to individual elements


marks[0] = 95;
marks[1] = 96;
marks[2] = 97;

We can change the marks of individual elements using the above method. In marks[2] data element, 2 is the
index or subscript. It is the (index+1) i.e, 5th element in the array marks as index starts with zero in arrays.

Displaying the elements of an array


for(i=0;i<5;i++)
{
printf (“%d”, marks[i]);
}
Operations that can be performed on arrays
1. Traversal: acessing every element of array
2. Insertion : inserting a new element
3. Deletion: deleting existing element
4. Merging: merge 2 arrays
5. Search : search for a value in an array
6. Sorting : arrange the values in array in either ascending or descending order.

Types of arrays:
1. One dimensional arrays (1D)
2. Two dimensional arrays (2D)
3. Multi dimensional arrays (3D)

1. 1D array is represented using one index ‘[ ]’ .It is mostly used for searching and sorting
2. 2D array is represented using two indexes ‘[][]’. One subscript denotes rows and other denotes columns.
It is mostly used for matrix representation. Example: int marks[3][3]; (3 rows and 3 columns)
3. Multi dimensional arrays have more than 2 indices. Example: int m[3][2][2]
m is an array of three 2D arrays.

Program to read and print the values of 1D Find the sum of the elements of an array
array void main()
void main() {
{ int marks[5], i, sum;
int marks[5], i; clrscr();
clrscr(); sum=0;
printf(“Enter marks of 5 students”); printf(“Enter marks of 5 students”);
for (i=0;i<5;i++) for (i=0;i<5;i++)
{ {
scanf(“%d”,&marks[i]); scanf(“%d”,&marks[i]);
printf(“\n marks = %d”, marks[i]); sum = sum+ marks[i];
} }
getch(); printf(“sum = %d”, sum);
} getch();
}

Search an element in an array using linear search Search an element in an array using binary search
void main() void main()
{ {
int a [10], i, n, s, flag = 0; int a [10], i, n, s, left, right, mid, flag=0;
printf(“Enter the number of elements”); printf(“Enter the number of elements”);
scanf(“%d”, &n); scanf(“%d”, &n);
printf (“enter %d elements”,n); printf (“enter %d elements”,n);
for (i=0;i<n;i++) for (i=0;i<n;i++)
{ {
scanf(“%d”,&a[i]); scanf(“%d”,&a[i]);
} }
printf(“enter the search element”); printf(“enter the search element”);
scanf(“%d”, &s); scanf(“%d”, &s);
for (i=0;i<n;i++) left=0;
{ right=n-1;
if ( s == a[i]) mid = (left+right)/2;
{ while (left < = right)
flag = 1; {
break; if ( s = = a[mid])
} flag =1;
} else if ( s< a[mid])
if( flag = = 1) right = mid-1;
printf(“Element found”); else
else left = mid+1;
printf(“Element not found”); mid = (left+right)/2;
getch(); }
} if( flag = = 1)
printf(“Element found”);
else
printf(“Element not found”);
getch();
}
Program to sort the given elements using bubble sort. Program to read and print values of 2D array
#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>
void main() void main()
{ {
int a [10], i, n, j, t; int a[5][5],i,j,r,c;
printf(“Enter the number of elements”); clrscr();
scanf(“%d”, &n); printf(“enter the order of matrix”);
for (i=0;i<n;i++) scanf(“%d %d”, &r,&c);
scanf(“%d”,&a[i]); printf(“Enter %d elements”, r*c);
for ( i=0; i< n; i++) for(i=0; i<0r;i++)
{ for(j=0; j<c;j++)
for ( j = i+1; j < = n; j++) scanf(“%d”, &a[i][j]);
{
if( a[i] > a[j]) for(i=0; i<r;i++)
{ {
t= a[i]; for(j=0; j<c;j++)
a[i]=a[j]; printf(“%3d”, a[i][j]);
a[j]=t; printf(“\n”);
} }
} getch();
} }
printf(“\n sorted array”);
for (i =0; i< n; i++)
printf(“%5d”, a[i];
getch();
}

Two dimensional Arrays


Declaration:
Syntax:
data_type name [row_size][column_size];
Example:
int marks[3][2];
marks is a 2D array that can store 3*2 = 6 elements. (row_size * column_size)
Initialization of 2D array
1. Initialization at the time of declaration
int marks[3][2] ={ 80,81,82,83,84,85};
(or)
int marks[3][2] = {{80,81},{82,83},{84,85}};
2. Giving values to individual elements
marks[0][0]=80; marks[0][1]=81; marks[1][0]=82; marks[1][1]=83;
marks[2][0]=84; marks[2][1]=85;
3. Taking values of all array elements from user
for(i=0; i<3;i++)
for(j=0; j<2;j++)
scanf(“%d”, &marks[i][j]);

memory 1004 1008 1010 1012 1014 1016


addresses
80 81 82 83 84 85
marks[0][0] marks[0][1] marks[1][0] marks[1][1] marks[2][0] marks[2][1]
marks[0] marks[1] marks[2]
The two dimensional matrix marks is an array of three 1D arrays (marks[0], marks[1] marks[2])

Arrays and Functions

1. 1D arrays and passing them as arguments to functions can be as shown in the diagram below
Passing entire array to function
When entire array is passed to function, they are always passed by address. In arrays there is no call by value
and there is only call by reference.

When the address of array is passed there is no way the function will come to know about the size of the array.
so size of the array must also be passed.
Example: One dimensional
int soe(int *, int ); arrays
void main()
{
int marks[3] = {65,67,69};
int sum;
sum = soe(&marks[0], 3);
printf(“sum of elements in array =%d”,sum); One dimensional Passing entire
} arrays array
int soe(int *b, int size)
{
int i, s=0;
for ( i=0; i< size, i++)
s=s+(*(b+i));
return s; Passing data Passing
} values addresses

Note: marks (or) &marks[0] (or) (marks + 0) are the same


&marks[1] (or) (marks+1) are same
marks[0] (or) *(marks+0) are the same.

/* program to perform matrix multiplication */


#include <stdlib.h>
void main()
{
int a[10][10], b[10][10], c[10][10], r1,c1,r2,c2, i,j,k;

clrscr();
printf(“enter the order of matrix A”);

scanf(“%d%d”,&r1,&c1);

printf(“enter the order of matrix B”);


scanf(“%d%d”,&r2,&c2);
printf(“enter the elements of matrix A”);

for (i = 0; i< r1; i++)

for (j=0; j<c1; j++)

scanf(“%d”, &a[i][j]);

printf(“enter the elements of matrix B”);

for (i = 0; i< r2; i++)

for (j=0; j<c2; j++)

scanf(“%d”, &b[i][j]);

if(r1 != c2)
{
printf(“\n multiplication is not possible”);
exit(0);
}
else
{
for(i=0; i<r1; i++)
{
for (j=0; j<c2; j++)
{
c[i][j]=0;

for(k=0; k<c1; k++)

c[i][j] = c[i][j]+ a[i][k]* b[k][j];


}
}
}
printf(“the resultant matrix is\n”);
for(i=0; i<r1;i++)
{
for(j=0; j<c2;j++)
printf(“%d\t”, c[i][j]);

printf(“\n”);
}
}

STRINGS
A String in C is defined to be a sequence of characters terminated by null character ‘\0’. The null character
indicates the end of a string.
Declaration of Array of char type:
Syntax: char string_name[size];
Example: char str[20];
str is string name
20 is the size of string.
Example 2: char str[10]=”COMPUTER”;
C O M P U T E R \0

str str str str str str str str str


[0] [1] [2] [3] [4] [5] [6] [7] [8]

Initialization of arrays of char type:


Type 1: char str[6]={‘H’,’E’,’L’,’L’,’O’,’\0’};
Type 2: char str[6]=”HELLO”;
Write a program to read and write strings using scanf and printf
#include <stdio.h>
void main() Output:
{ Enter a string
char str[10]; mpcs student.
printf(“Enter a string”); You entered mpcs
scanf(“%s”, &str);
printf(“You entered %s”,str);
}
String Input/ Output Functions
1. Reading Strings
Strings can be read from user by using 3 ways
1. using scanf function
2. using gets() function
3. using getchar(), getch() and getche() functions
The main drawback of scanf() function is that it teminates as soon as it finds a blank space. So, we can use
gets() function which takes blank spaces .
getchar(), getch() and getche() functions read only single characters and has to call them repeatedly to read a
string.
2. Writing Strings
Strings can be displayed using three ways
1. using printf() function
2. using puts() function
3. using putchar() function repeatedly
Summary of functions to read and write a single character
Function Operation Usage

getchar() Used to read a character from keyboard and waits for ENTER char s =
or TAB or ESC key to be pressed getchar();

getch() Reads a character from keyboard and returns immediately and char s =
does not wait for ENTER key to be pressed. It does not display getch();
the character entered by user

getche() Reads a character from keyboard and returns immediately and char s =
does not wait for ENTER key to be pressed. It displays the getche();
character entered by user

putchar() Writes a character to screen putchar(s)

Write a program to read and write strings using puts() and gets()
void main()
{
char str[20];
puts("Enter a string");
gets(str);
puts(str);
}
String manipulation functions
The string library functions which are in the header file “string.h”
The most commonly performed operations are
1. Finding the length of the string – strlen()
2. Copying one string to another string – strcpy()
3. Comparing two string --- strcmp()
4. Concatenation of two strings --- strcat()
5. Reverse the given string-- strrev()
6. Convert the input string to lower case strlwr()
7. Convert the input string to upper case strupr()
1. Finding the length
strlen() is used to find the number of characters in a string excluding the null character
Usage: int length = strlen(string)
Write a program to find the length of a string
#include <string.h> Output:
void main() Enter a string
{ computers
char str[10]; You entered computers
int len; Length of the string is 9
printf(“enter a string”);
scanf(“%s”, &str);
len = strlen(str);
printf(“You entered %s”,str);
printf(“length of the string is %d”,len);
}
2. copying one string to another string
Usage: strcpy(string1, string2);
This function copies the string2 to string 1 including the null character. The contents if any in string1 will be
lost.
#include <string.h>
void main() Output:
{ Enter a string
char str1[50],str2[50]; mpcs
clrscr(); copied string in str1 is mpcs
printf("enter a string");
gets(str2);
strcpy(str1,str2);
printf(“copied string in str1 is %s”,str1);
}
3. strcmp() is used to compare two strings
Usage: int ret = strcmp( string1, string2)
This function return values as follows:
• returns < 0 if str1 is less than str2.
Output:
• returns > 0 if str2 is less than str1. Enter first string
mpcs
• returns = 0 if str1 is equal to str2. Enter second string
Write a program to compare two strings mecs
#include <string.h> the two strings are not equal
void main()
{
char str1[50],str2[50];
int ret;
clrscr();
printf("enter first string");
gets(str1);
printf("enter second string");
gets(str2);
ret = strcmp(str1,str2);
if (ret == 0)
printf(“the two strings are equal”);
else
printf(“the two strings are not equal”);
}
4. Concatenation of two strings
The strcat() function appends the string2 to the end of the string1. The null character in string1 is overwritten.
The process stops when null character of string2 is copied. String1 must be big enough to store the contents of
string1 and string2.
Usage: strcat(string1, string2)
Write a program to concatenate two strings
#include <string.h>
Output:
void main()
Enter first string
{
mpcs
char str1[50],str2[50];
Enter second string
clrscr();
First year
printf("enter first string");
String1 = mpcs First year
gets(str1);
printf("enter second string");
gets(str2);
strcat(str1,str2);
printf(“string1 =%s”,str1);
}
5. Reverse the input string
#include <string.h>
Output:
void main()
enter a string
{
mpcs
char str1[50],str2[50];
reverse = scpm
clrscr();
printf("enter a string ");
gets(str1);
printf(“reverse =%s”, strrev(str1));
}
6. Convert the input string into lower case
#include <string.h>
Output:
void main()
enter a string
{
MPCS
char str1[50],str2[50];
lowercase = mpcs
clrscr();
printf("enter a string in capital letter ");
gets(str1);
printf(“lowercase =%s”, strlwr(str1));
}
7. Convert the input string into uppercase
#include <string.h>
Output:
void main()
enter a string in lower case
{
mpcs
char str1[50],str2[50];
uppercase = MPCS
clrscr();
printf("enter a string in lower case ");
gets(str1);
printf(“upper case =%s”, strupr(str1));
}
ARRAYS OF STRINGS
An array of string is declared as char names[5][30];
First index indicates how many strings are needed and Second index indicates the length of every individual
string.
char names[3][30] = {“RAM”,”SHYAM”,”SAI”};
3 names and each name can consist of maximum of 30 characters .
Memory representation of 2D array

names[0] R A M \0

names[1] S H Y A M \0

names[2] S A I \0

Write a program to print names of n students of a class


void main()
{ Output:
char names[10][30]; Enter the number of students
int i, n; 2
clrscr(); Enter names of 2 students
puts(“Enter the number of students\n”); sita
scanf(“%d”, &n); gita
printf(“enter names of %d students”, n);
for ( i = 0; i<n;i++) sita
{ gita
scanf(“%s”,names[i]);
}
for ( i = 0; i<n;i++)
{
puts(names[i]);
}
}

UNIT – VI Pointers
Pointer Variables
When a variable is declared some amount of memory is allocated to hold the value of that variable. The size of
memory allocated depends on the datatype of the variable. Each memory location has an address.
pointer is a variable that stores the address of another variable.
Applications of pointers
1. pointers are used to pass arrays and strings as function arguments.
2. using pointers one can pass functions as arguments to another function
3. pointers are used to create complex data structures like trees, stack, queues etc..
4. pointers are used for dynamic memory allocation
Declaring and initializing Pointers

Addresses 10 10 10 10 104 105


0 1 2 3

6000 100

x ptr1
Example 1:
int x = 6000;
int *ptr1;
ptr1=&x;
ptr1 will store the starting address (here 100) and will read 2 bytes as it points to a integer variable when
dereferenced using *ptr1.

Addresses 10 10 10 10 11 111
6 7 8 9 0

100000.0 106

sal ptr2
Example2:
float sal = 100000.0;
float *ptr2;
ptr2=&sal;
ptr1 and ptr2 occupy same amount of memory. Memory enough to store the address of a memory location.
The datatype of pointer indicate that they contain the address of a variable of that datatype.
Indirection operator (or) Value at Address operator (*)
When * is used as unary operator after the pointer variable other than at the declaration of pointer variable, then
* is called indirection operator.
void main()
{
int x= 6000, *ptr;
ptr = &x;
printf(“%d”, *ptr);
}
The above program will print 6000 on the screen.
* operator deferences a pointer and will display the value present at the address stored in pointer.
printf (“%d”, *(&x) ; will also prints 6000 on the screen. Hence *ptr (or) x (or) *(&x) are same.
ptr (or) &x are same.
Write a program to declare and access pointer variable
void main()
{
int x = 6000, *ptr;
ptr = &x;
printf(“ value of x = %d”,x);
printf(“ value of x = %d”,*ptr);
printf(“ value of x = %d”,*(&x));
printf (“address of x = %u”, ptr);
printf (“address of x = %u”, &x);
}

Generic pointers
It is a pointer variable that has void as its data type. Generic pointer can be used to point to variables of any data
type.
Ex: void *ptr;
Pointers and arrays
Example: int marks[10], *ptr ;
ptr = marks;
The array name marks holds the starting address of the array i.e, &marks[0]
Write a program to print the elements of array using pointers
void main()
{
int marks[3] = { 1,2, 3}, *ptr,i=0 ;
ptr=&marks[0];
printf(“elements in an array are”);
while( i<3)
{
printf(“%d\t”, *ptr);
ptr++;
}

Write a program to pass string as arguments to functions using pointers


void print(char *);
void main()
{
char str[20]=”HELLO”; Output:
print(str); HELLO
}
void print( char *c)
{
while(*c != 0)
{
printf(“%c”, *c);
c++;
}
}

Understanding Computer memory


Memory allocated to a Program or application is divided into 4 segments.
1. Code -- contains instructions
2. Static/ Global memory --stores static and global variable that have program lifetime
3. Stack memory
4. Heap memory.
A fixed size Stack is allocated by the system and the stack is filled from bottom to top. Also the last element
added to stack is removed first (hence it is called LIFO data structure). All the variables declared within main()
are allocated space on stack. All the parameters passed to called function are also stored on stack. Stack is
faster, smaller and expensive than HEAP memory.
A fixed size HEAP is allocated by the system and is used when need arises in random fashion.
what is static memory and dynamic memory allocation?
1. Static memory allocation: The process of allocating memory to program at compile time is known as static
memory allocation. This memory cannot be changed during the execution of program. Example : stack and
global memory
when a program is executed, certain amout of memory from stack is taken and allocated for main() method.
This is called stack frame.
Similarly stack frame is created for each function called above the main()'s stack frame.

when a function is called, it is pushed onto the stack.


when control returns from function, it is popped from stack.
Whatever is on the top of the stack is executing.
At the time of program compilation itself, the amout of memory to be allocated for each function's stack frame
is decided by the compiler and do not change.

Hence it is called Static allocation.


2. Dynamic memory allocation: The process of allocating memory to the variables during program execution or
at run time is known as dynamic memory allocation. Example : heap memory.
If you want memory to be kept as long as you want, instead of getting cleared automatically when popped from
stack, we use dynamic memory.
In C, dynamic memory allocation is done using
1. malloc
2.calloc
3. realloc
Dynamic memory deallocation is done using free
1. malloc returns a void pointer that has address of first byte of block of memory allocated on heap , so we
typecast as shown below
ex: The below code allocates memory for 20 integers on heap

int *p;
p= (int *) malloc(20*sizeof(int));
2. free(p); is used to deallocate the memory.

3. calloc is same as malloc except

i. it takes 2 arguments. For ex: p=(int *)calloc(20, sizeof(int));


ii. it initializes all the memory allocated on heap to 'zero'

4. realloc is used to change the amout of memory previously allocated on heap


syntax:
void * realloc(void * ptr, size_t size)
ptr is pointer to existing block
size is the size of new block
size_t is data type that has only positive values For ex: unsigned integer.
Structures
A structure is a user defined data type. A structure stores related information. Structure is collection of variables
of DIFFERENT data types.
Declaring structures
A structure is declared using struct keyword followed by structure name.
All variables of structure are declared within structure and each variable is called member of the structure.
Memory is not allocated when the structure is declared. 100

101

102

103

104

105

106

107

108

109

110

111

112

113

Example:
struct student
{
int roll_no;
char name[10];
int marks;
}s1;

Structure initializations

Structures can be initialized in 3ways

1) 2) 3)
struct book struct book struct book b1,b2,b3;

{ { b1.title=”ANSI C”;

char title[20]; char title[20]; b1.author=”guru


swamy”;
char author[40]; char author[40];
b1.price=350;
int price; int price;

}b1 ={“ANSI }; b2.title=” C”;


C”,”swamy”,350}; struct book b1 ={“ANSI b2.author=”reema”;
C”,”swamy”,350};
b2.price=450;

Accessing the members of structure


A structure variable is accessed using a ‘.’ operator.

Write a program to print the details of 2 students such as rollno, name, course and fees.
#include <string.h>
void main()
{
struct student
{
int roll;
char name[40], course[10];
};
struct student s1={151301, “adi”,”IMPCS”};
struct student s2;
s2.roll=151302;
strcpy(s2.name,”naik”);
strcpy(s2.course,”IMPCS”);
printf(“rollno = %d \t name=%s \t course=%s \n”, s1.roll, s1.name, s1.course );
printf(“rollno = %d \t name=%s \t course=%s \n”, s2.roll, s2.name, s2.course );
}

typedef
By using typedef keyword an alternate name is given to existing data type.

When we precede a struct name with typedef keyword then the struct becomes a new data type.

write a program to create a user defined data type date


#include <string.h>
typedef struct date
{
int dd;
int mm;
int yy;
};
void main()
{
date d1 = {1,9,2015};
printf(“today’s date = %d - %d - %d”, d1.dd, d1.mm, d1.yy );
}
Now that we have added typedef keyword before structure name date, date becomes new data type. Therefore,
we can define variable of type date by writing just date d1,d2,d3;
Copying and comparing structures
We can assign a structure variable to another structure variable of same type.
Example: struct student s1={151301, “adi”,”IMPCS”,18000};
struct student s2;
s2=s1;
C does not allow comparing of two structure variable however; individual elements of one structure can be
compared with individual elements of another structure.
Nested Structures
A structure can be placed within another structure. That is, a structure may contain another structure as its
member. Such a structure is called a nested structure.
#include <stdio.h>
typedef struct date
{
int dd;
int mm;
int yy;
};
typedef struct student
{
char name[40];
date dob;
};

main()
{
student s1;
printf("enter name and date, month and year of birth of student\n");
scanf("%s %d %d %d", &s1.name, &s1.dob.dd, &s1.dob.mm, &s1.dob.yy);
printf("name =%s \t date of birth =%d - %d - %d", s1.name, s1.dob.dd, s1.dob.mm, s1.dob.yy);
}

Arrays of structures
Example: student st[30];
To assign values to ith student, you should write
st[i].name = “ xyz”;
st[i].dob.dd = 21;
st[i].dob.mm=12;
st[i].dob.yy=1991;

Self referential Structures contains a pointer to data that is of same type as that of the structure.
example:
struct node
{
int val;
struct node *next;
}
Here the structure node will contain 2 types of data- an integer val and next, which is pointer to a node.

Structures and Functions


A structure can be passed to a function in 3 ways
1. Passing individual members
2. Passing the entire structure
3. Passing the address of the structure.

Difference between structure and unions


Structure Union

It is collection of variables of different data It is collection of variables of different data


type type

Structure is declared using struct keyword Union is declared using union keyword

struct structure_name union name

{ {

datatype var1; datatype var1;

datatype var2; datatype var2;

}object; }object;

Each member within a structure is allocated A common memory of size equal to largest
unique memory. member size is allocated. Each member
struct book within union share the common memory.

{ union book

char title[20]; {

char author[40]; char title[20];

int price; char author[40];

}b1 ; int price;

Memory allocated for b1 = 64 bytes }b1 ;

Memory allocated for b1 = 40 bytes

20 bytes for title variable +

40 bytes for author variable+

2 bytes for price variable+ 2 bytes padding

Size of structure is >= sum of sizes of its Size of union is equal to its largest member
members size

All the members can be assigned values at a Only one member can be assigned value at a
time. time

All the members can be accessed at same Only one member can be accessed at a time
time

Values assigned to one member will not Values assigned to one member may cause
cause the change in other members. change in values of other members.

Enumerated Data types


Enumerated data types is a user defined type. Keyword enum is used to defined enumerated data type.
Enumerated data type consists of integral constants and each integral constant is given a name.
Example:
enum month {JAN =1 ,FEB=2,MAR=3,APR=4,MAY=5,JUN=6,JUL=7,AUG=8,SEP=9,OCT=10,
NOV=11,DEC=12};
A user defined data type month is created. It has 12 values as given in pair of braces.
enum month rmonth;
“rmonth” variable is declared of type “month” which can be initialized with any data value amongst 12 values”.

Files
File is a collection of records stored in secondary memory such as hard disk. Record is collection of fields and
each field can carry a value.
Stream is a logical interface. Stream can be attached to any device to communicate with that device. The device
can be logical file or physical keyboard.
There are 3 standard streams in C language
1. standard input (stdin)----------- stream from which the program receives data.
2. standard output (stdout) ------- stream to which the program writes the data.
3. standard error (std err) ---------- stream to which the program writes the error messages.
stdin, stdout and stderr are the logical names given to these streams.
By default Standard input is connected to keyboard. Standard output and Standard error are connected to
monitor.
Buffer: When a stream is linked to a disk file, a buffer is automatically created.
Buffer is block of memory used for temporary storage of data. Buffers are needed as the disk drives are block
oriented.
Types of Files
There are 2 types of files.
1. ASCII text files
2. Binary files.

1. ASCII text file is a stream of characters that can be sequentially processed by a computer. In a text file, each
line of data ends with a new line character (\n). Each file ends with a special character (EOF) marker

Example: Integer vaue 123 will be stored as a sequence of 3 characters. And so requires 3 bytes to store

int value will be represented as 2 bytes of memory internally, but externally the int value will be represented as
a string of characters. To convert internal representation into external, we use printf and fprintf functions.

To convert external representation to internal representation, scanf and fscanf functions are used.

2. Binary files may contains any type of data encoded in binary form. A binary file does not require any special
processing.
Binary files can be processed sequentially or randomly.
Integer vaue 123 will be stored in 2 bytes .

Using files in C
To use files in C, we must follow the below steps
1. Declare a FILE pointer variable
2. Open the file (fopen)
3. Process the file
4. Close the file.
Declaring a file pointer variable.
A file pointer variable that points to a structure FILE has to be declared as fopen functions return a FILE
pointer.

Syntax: FILE filepointer_variable;


Ex: FILE *fp;

Opening a file
a file must be opened before data can be read and write. fopen() function is used to open the file.
Syntax: filepointer_variable = fopen(“filepath”,”mode”);
ex: fp = fopen(“myfile.txt”, “r”);
File modes:
mode Description

"r" Opens a file for reading. The file must exist.

"w" Creates an empty file for writing. If a file with the same name already exists, its contents
are erased

"a" Appends data at the end of the file. The file is created if it does not exist.

"r+" Opens a file for reading and writing. The file must exist.

"w+" Creates an empty file for both reading and writing.

"a+" Opens a file for reading and appending.

note: the modes that can be used with binary files are rb,wb,ab, rb+,wb+,ab+

closing a file:
The C library function fclose closes the stream. All buffers are flushed.
syntax: fclose(filepointer_variable);
Example: fclose(fp);

Write a program to read student details from a file and display the details
#include <stdlib.h>
void main()
{
FILE *fp;
char name[40];
int roll;

fp = fopen("student.txt","r");
if( fp == NULL)
{
printf("file cannot be opened");
exit(0);
}
printf("enter rollno and name");
fscanf(fp,"%d%s", &roll,&name);
printf("\n Roll no = %d \t name = %s",roll, name);
fclose(fp);
}

Reading data from files


C provides the following set of functions to read data from a file.
Function name Description Example

fscanf() fscanf reads formatted


input from a stream.

fgets() fgets reads a line from the char str[60];


stream and stores it into
the string pointed to by str. if( fgets (str, 60, fp)!
It stops when either (n-1) =NULL )
characters are read, the
newline character is read, {
or the end-of-file is /* writing content to
reached, whichever comes stdout */
first.
puts(str);

fgetc() gets the next character do


from the stream and
advances the position {
indicator for the stream c = fgetc(fp);

if( feof(fp) )

break ;

printf("%c", c);

}while(1);

fread() fread function reads data char c[] = "this is c


from the given stream into program";
the array pointed to, by ptr.
char buffer[100];

fp = fopen("file.txt",
"w+");

/* Write data to the file


*/

fwrite(c, strlen(c) + 1, 1,
fp);

/* Seek to the beginning


of the file */
fseek(fp, SEEK_SET, 0);

/* Read and from file */

fread(buffer, strlen(c)+1,
1, fp);

writing data to files


1. fprintf() 2. fputs() 3.fputc() 4. fwrite()

You might also like