c notes for exam preparation

47
Start Read A, B Sum=A+B Print Sum Start 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. 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 Step2: Input the second number as B Step3: Set Sum = A + B Step4: Print Sum Step 5: End Flow chart is a graphical or symbolic representation of an algorithm. Flow chart to add two numbers and display the sum is as shown in the figure 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 True False Condit ion? Body of loop StatementX True Fals e Flow chart for while loop Flow chart for do-while loop Tru e Fal se StatementX Condit ion? Body of loop

Upload: sarvani-videla

Post on 15-Apr-2017

354 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: C notes for exam preparation

Start

Read A, B

Sum=A+B

Print Sum

Start

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.Once algorithm is written, it can be implemented in any high level language. Algorithm to add two numbersStep 1: Input the first number as AStep2: Input the second number as BStep3: Set Sum = A + BStep4: Print SumStep 5: EndFlow chart is a graphical or symbolic representation of an algorithm.Flow chart to add two numbers and display the sum is as shown in the figure

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. while2 Variables Variables are named locations in memory. sum3 Constants Constants are assigned to variables 894 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

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.

True

False

Condition?

Body of loop

StatementX

True

False

Flow chart for while loopFlow chart for do-while loop

True

False

StatementX

Condition?

Body of loop

Page 2: C notes for exam preparation

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 CConstants 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 defineEx: const float pi = 3.14; pi is a constant whose value cannot be changed

#define PI 3.14 Types of C constants:S.no Constant type Example Rules for constructing C constant1 Integer constants 53762, -478, Must have atleast one digit

It must not have a decimal point2 Real or Floating point

constants10.45, 0.5e2,14E-2 Must have atleast one digit

It must have a decimal point5 character constants ‘A’   ,   ‘B’,     ‘C’ Single character enclosed in single quotes6 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 Description1 printf() Prints the output on the screen2 scanf() Reads a character, string, numeric data from keyboard.3 gets() It reads line from keyboard4 getchar() It reads character from keyboard5 puts() It writes line to o/p screen6 putchar() It writes a character to screen7 fflush() flushes a file2. conio.h: provide console input/output functions. Some of the functions defined in conio.h are S.no Function Description1 clrscr() This function is used to clear the output screen.2 getch() It reads character from keyboard3 getche() It reads character from keyboard and echoes to o/p screen

Long Answer Questions1. 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.

Page 3: C notes for exam preparation

Basic data types and their size in bytes in a 16 bit computer is shown in the table below.Keyword used

Size in bytes

Range Use Example

character data type

char 1 -128 to 127 To store characters char gender = ‘m’;

Integer data type int 2 -32767 to 32768 To store integers int num=10;

Floating point data type

float 4 3.4E-38 to 3.4E+38

To store floating point numbers

float discount = 12.5;

Double data type double 8 1.7E-308 to 1.7E+308

To store big floating point numbers

double sal = 1234567.12345;

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 signed char

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

int signed intshort intsigned short int

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

unsigned intunsigned short int

2 0 to 65535 unsigned short int num = 12;

long intsigned long int

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

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.

Page 4: C notes for exam preparation

Example:

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

#include <stdio.h>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(){ int m=40,n=20; if (m == n) { printf("m and n are equal"); }

else {

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

output: Total amount to be paid = 5500

Output: m and n are not equal

Page 5: C notes for exam preparation

}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;

Page 6: C notes for exam preparation

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 memory2. Secondary memoryPrimary 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 bythe CPU and other parts by increasing surface area.

Page 7: C notes for exam preparation

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 sectionpre-processor directivesglobal declarationsmain(){ 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 FunctionsAny number of user defined functions can be written. All functions including main() are divided into 2 parts.1. declaration section2. statement sectiondeclaration 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:

Page 8: C notes for exam preparation

S.no Types of Operators              Description              1 Arithmetic operators These are used to perform mathematical calculations like addition,

subtraction, multiplication, division and modulus2 Assignment operators

(=)These are used to assign values to variables.

3 Relational operators These are used to compare the values of two variables4 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)

operatorsConditional operators return one value if condition is true and returns another value if condition is false.

7 Increment/decrement operators

These operators are used to either increase or decrease the value of the variable by one.

8 Special operators &, *, sizeof( )Arithmetic Operators in C:S.no Arithmetic Operators Operation Example1 + Addition A+B2 - Subtraction A-B3 * multiplication A*B4 / Division A/B5 % Modulus A%BAssignment operators in C:Operators Example  Explanation Simple assignment operator = sum = 10 10 is assigned to variable sumCompound assignment operators (+=, *=, /=, %=, etc..

+= sum += 10

This is same as sum = sum + 10

Relational operators in C:S.no Operators Example  Description1 > x > y x is greater than y2 < x < y x is less than y3 >= x >= y x is greater than or equal to y4 <= x <= y x is less than or equal to y5 == x == y x is equal to y6 != x != y x is not equal to yLogical 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 Description1 && logical AND (x>5)&&(y<5) It returns true when both conditions are true2 || logical OR (x>=10)||(y>=10) It returns true when at-least one of the condition is true3 ! logical NOT !((x>5)&&(y<5)) It reverses the state of the operand

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 operatorsx y  x|y x & y x ^ y Operator_symbol Operator_name0 0 0 0 0 & Bitwise_AND0 1 1 0 1 | Bitwise OR1 0 1 0 1 ~ Bitwise_NOT

Page 9: C notes for exam preparation

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 OperatorsSyntax: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 Description1 & 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; printf("Enter three numbers: "); scanf("%f %f %f", &a, &b, &c); if(a>b && a>c) printf("Largest number = %f", a); 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,

Output:Enter three numbers:345Largest number = 5

Page 10: C notes for exam preparation

1. for 2. while 3. do whileWhile loop: /* Program to print the natural numbers from 1 to 5 using while loop*/#include <stdio.h>void main(){

int i=1;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(){

int i=1;do{

printf(“%d\n”,i);i++;

} while(i < 5);

}

For loop: /* Program to print the natural numbers from 1 to 10 using for loop*/#include <stdio.h>void main(){

int i;for(i=1;i < 5;i++){

printf(“%d\n”,i);}

}

Output: 12345

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.

Syntax of do while loop is as follows:

do { statements; }while (condition);

The syntax of while loop is as follows:

while(condition){ statement(s);}

Syntax of for loop is as follows:for (exp1; exp2; expr3){ statements; }Where,exp1 – variable initialization( Example: i=0, j=2, k=3 )exp2 – condition checking( Example: i>5, j<3, k=3 )exp3 – increment/decrement( Example: ++i, j–, ++k )

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

Compilerconverts the c program into machine level language

Object code ex: factorial.obj

LinkerObject code of header files included

Ex: stdio.h

Executable ex: factorial.exe

Page 11: C notes for exam preparation
Page 12: C notes for exam preparation

main(){int x, y;y= f1(x);…….}

int f1(int z){……return z;}

FunctionsDefinition: Functions are self contained and independent block of statements.C allows a big program to be divided into segments known as functions.

Need for functions1. 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 FunctionsWhile using functions we use the following terminology1. If a function f() uses another function g().

f() is called calling function and g() is called called function

2. Function callWhen 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

Here main() is calling function and f1() is called function

3. Inputs given to function are called parameters / arguments. 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 prototypeBefore 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 definitionWhen a function is defined space is allocated for that function in memoryA 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.

f1(){…..…..}

Page 13: C notes for exam preparation

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 */void swap(int , int);void main(){ int a ,b; clrscr(); printf(“enter two numbers”); scanf(“%d%d”, &a,&b); printf(“values before swapping = %d \t%d”, a, b); swap(a,b); getch();}void swap ( int x, int y){ int temp; temp =x; x=y; y=temp; printf(“values after swapping = %d\t %d”, x, y);}

/* swapping using call by reference */void swap(int *, int *);void main(){ int a ,b; clrscr(); printf(“enter two numbers”); scanf(“%d%d”, &a,&b); printf(“values before swapping = %d \t %d”, a, b); swap(&a,&b); getch();}void swap ( int *x, int *y){ int temp; temp =*x; *x=*y; *y=temp; 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

Page 14: C notes for exam preparation

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 scope1. 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 ClassesThe 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.

Page 15: C notes for exam preparation

C supports 4 storage classes.

1. automatic

2. register

3. external

4. static

Comparison of storage classesFeature Storage class

auto extern register staticAccessibility Within function or block in

which it is declaredWithin all program files that are part of a program

Within function or block in which it is declared

Local: Within function or block in which it is declaredGlobal: Within the program in which it is declared

Storage Main memory Main memory CPU register Main memoryExistence Exists in memory as long as

the control is within the block or function in which it is declared. Once the control returns from function or block, it is removed from memory

Exists through out the execution of the program

Exists in memory as long as the control is within the block or function in which it is declared. Once the control returns from function or block, it is removed from memory

Local: Exists through out the execution of the programGlobal: Exists through out the execution of the program files

Default Value

Garbage Garbage Garbage zero

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 array3. 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 arraysAll Elements of array are stored in contiguous memory locations.

Memory location addresses 1000 1002 1004

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

Page 16: C notes for exam preparation

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 userEx: 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 arrays1. Traversal: acessing every element of array2. Insertion : inserting a new element 3. Deletion: deleting existing element4. Merging: merge 2 arrays5. Search : search for a value in an array6. 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 arrayvoid main(){

Find the sum of the elements of an arrayvoid main(){

int marks[5], i, sum;

Page 17: C notes for exam preparation

int marks[5], i;clrscr();printf(“Enter marks of 5 students”);for (i=0;i<5;i++){

scanf(“%d”,&marks[i]);printf(“\n marks = %d”, marks[i]);

} getch();}

clrscr();sum=0;printf(“Enter marks of 5 students”);for (i=0;i<5;i++){

scanf(“%d”,&marks[i]);sum = sum+ marks[i];

}printf(“sum = %d”, sum);

getch();}

Search an element in an array using linear searchvoid main(){

int a [10], i, n, s, flag = 0;printf(“Enter the number of elements”);

scanf(“%d”, &n); printf (“enter %d elements”,n); for (i=0;i<n;i++)

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

printf(“enter the search element”);scanf(“%d”, &s);

for (i=0;i<n;i++){

if ( s == a[i]) { flag = 1; break; }

}if( flag = = 1) printf(“Element found”);else printf(“Element not found”); getch();

}

Search an element in an array using binary searchvoid main(){

int a [10], i, n, s, left, right, mid, flag=0;printf(“Enter the number of elements”);

scanf(“%d”, &n); printf (“enter %d elements”,n);

for (i=0;i<n;i++){

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

printf(“enter the search element”);scanf(“%d”, &s);

left=0;right=n-1;mid = (left+right)/2;while (left < = right){

if ( s = = a[mid])flag =1;

else if ( s< a[mid])right = mid-1;

elseleft = mid+1;

mid = (left+right)/2;}

if( flag = = 1) printf(“Element found”);else printf(“Element not found”); getch();

}Program to sort the given elements using bubble sort.

#include <stdio.h>#include <conio.h>void main()

Program to read and print values of 2D array#include <stdio.h>#include <conio.h>void main(){

Page 18: C notes for exam preparation

{int a [10], i, n, j, t;printf(“Enter the number of elements”);

scanf(“%d”, &n);for (i=0;i<n;i++)

scanf(“%d”,&a[i]);for ( i=0; i< n; i++){

for ( j = i+1; j < = n; j++){

if( a[i] > a[j]){

t= a[i];a[i]=a[j];a[j]=t;

}}

} printf(“\n sorted array”);

for (i =0; i< n; i++)printf(“%5d”, a[i];

getch();}

int a[5][5],i,j,r,c;clrscr();printf(“enter the order of matrix”);scanf(“%d %d”, &r,&c);printf(“Enter %d elements”, r*c);for(i=0; i<0r;i++)

for(j=0; j<c;j++)scanf(“%d”, &a[i][j]);

for(i=0; i<r;i++){

for(j=0; j<c;j++)printf(“%3d”, a[i][j]);

printf(“\n”);}getch();

}

Two dimensional ArraysDeclaration:

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 array1. 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 elementsmarks[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 addresses

1004 1008 1010 1012 1014 1016

80 81 82 83 84 85marks[0][0] marks[0][1] marks[1][0] marks[1][1] marks[2][0] marks[2][1]

Page 19: C notes for exam preparation

One dimensional arrays

One dimensional arrays

Passing entire array

Passing data values

Passing addresses

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 belowPassing entire array to functionWhen 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:int soe(int *, int );void main(){

int marks[3] = {65,67,69};int sum;sum = soe(&marks[0], 3);printf(“sum of elements in array =%d”,sum);

}

int soe(int *b, int size){

int i, s=0;for ( i=0; i< size, i++) s=s+(*(b+i));

return s;}

Note: marks (or) &marks[0] (or) (marks + 0) are the same&marks[1] (or) (marks+1) are samemarks[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);

Page 20: C notes for exam preparation

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”);}

}

STRINGSA 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 name20 is the size of string.

Page 21: C notes for exam preparation

Example 2: char str[10]=”COMPUTER”;

C O M P U T E R \0

str[0]

str[1]

str[2]

str[3]

str[4]

str[5]

str[6]

str[7]

str[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(){

char str[10];printf(“Enter a string”);scanf(“%s”, &str);printf(“You entered %s”,str);

}String Input/ Output Functions1. Reading StringsStrings can be read from user by using 3 ways1. using scanf function2. using gets() function3. using getchar(), getch() and getche() functionsThe 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 StringsStrings can be displayed using three ways1. using printf() function2. using puts() function3. using putchar() function repeatedlySummary of functions to read and write a single character

Function Operation Usage

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

char s = getchar();

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

char s = getch();

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

char s = getche();

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

Output:Enter a string mpcs student.You entered mpcs

Page 22: C notes for exam preparation

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 functionsThe 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 lengthstrlen() 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>void main(){

char str[10];int len;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(){

char str1[50],str2[50]; clrscr(); 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:Enter first stringmpcsEnter second stringmecsthe two strings are not equal

Output:Enter a stringcomputersYou entered computersLength of the string is 9

Output:Enter a stringmpcscopied string in str1 is mpcs

Page 23: C notes for exam preparation

returns > 0 if str2 is less than str1.

returns = 0 if str1 is equal to str2.

Write a program to compare two strings#include <string.h>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 stringsThe 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>void main(){ char str1[50],str2[50]; clrscr(); printf("enter first string"); gets(str1); printf("enter second string"); gets(str2); strcat(str1,str2); printf(“string1 =%s”,str1); }5. Reverse the input string #include <string.h>void main(){ char str1[50],str2[50]; clrscr(); printf("enter a string "); gets(str1);

printf(“reverse =%s”, strrev(str1));}6. Convert the input string into lower case#include <string.h>void main()

Output:Enter first stringmpcsEnter second stringFirst yearString1 = mpcs First year

Output: enter a string mpcs reverse = scpm

Output: enter a string MPCSlowercase = mpcs

Page 24: C notes for exam preparation

{ char str1[50],str2[50]; 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>void main(){ char str1[50],str2[50]; clrscr(); printf("enter a string in lower case "); gets(str1);

printf(“upper case =%s”, strupr(str1));}ARRAYS OF STRINGSAn 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 classvoid main(){

char names[10][30];int i, n;clrscr();puts(“Enter the number of students\n”);scanf(“%d”, &n);printf(“enter names of %d students”, n);for ( i = 0; i<n;i++){

scanf(“%s”,names[i]);}for ( i = 0; i<n;i++){

puts(names[i]);}

}

UNIT – VI Pointers

Output:Enter the number of students2Enter names of 2 studentssitagita

sitagita

Output: enter a string in lower casempcsuppercase = MPCS

Page 25: C notes for exam preparation

Pointer VariablesWhen 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 pointers1. pointers are used to pass arrays and strings as function arguments.2. using pointers one can pass functions as arguments to another function3. pointers are used to create complex data structures like trees, stack, queues etc..4. pointers are used for dynamic memory allocationDeclaring and initializing PointersExample 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.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 variablevoid 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);

}

Addresses 100 101 102 103 104 105

6000 100

x ptr1

Addresses 106 107 108 109 110 111

100000.0 106

sal ptr2

Page 26: C notes for exam preparation

Generic pointersIt 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 arraysExample: 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 pointersvoid 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 pointersvoid print(char *);void main(){

char str[20]=”HELLO”;print(str);

}void print( char *c){

while(*c != 0){

printf(“%c”, *c);c++;

}}

Understanding Computer memoryMemory allocated to a Program or application is divided into 4 segments.1. Code -- contains instructions2. Static/ Global memory --stores static and global variable that have program lifetime3. Stack memory4. 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

Output:HELLO

Page 27: C notes for exam preparation

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. malloc2.calloc3. reallocDynamic memory deallocation is done using free1. malloc returns a void pointer that has address of first byte of block of memory allocated on heap , so we typecast as shown belowex: 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 heapsyntax:void * realloc(void * ptr, size_t size)ptr is pointer to existing blocksize is the size of new blocksize_t is data type that has only positive values For ex: unsigned integer.StructuresA structure is a user defined data type. A structure stores related information. Structure is collection of variables of DIFFERENT data types.Declaring structuresA 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. Example:

struct student {

100

101

102

103

104

105

106

107

108

109

110

111

112

113

Page 28: C notes for exam preparation

int roll_no; char name[10];

int marks; }s1;

Structure initializations

Structures can be initialized in 3ways

1)struct book{ char title[20];

char author[40];

int price;

}b1 ={“ANSI

C”,”swamy”,350};

2)struct book { char title[20];

char author[40];

int price;

};struct book b1 ={“ANSI C”,”swamy”,350};

3)struct book b1,b2,b3;b1.title=”ANSI C”;b1.author=”guru swamy”;b1.price=350;

b2.title=” C”;b2.author=”reema”;b2.price=450;

Accessing the members of structureA 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 );

Page 29: C notes for exam preparation

}

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{

Page 30: C notes for exam preparation

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 FunctionsA structure can be passed to a function in 3 ways1. Passing individual members2. Passing the entire structure3. Passing the address of the structure.

Difference between structure and unionsStructure Union

It is collection of variables of different data typeStructure is declared using struct keywordstruct structure_name{ datatype var1; datatype var2;

It is collection of variables of different data typeUnion is declared using union keywordunion name{ datatype var1; datatype var2;

Page 31: C notes for exam preparation

}object; }object;

Each member within a structure is allocated unique memory. struct book{ char title[20];

char author[40];

int price;

}b1 ;Memory allocated for b1 = 64 bytes

20 bytes for title variable +40 bytes for author variable+ 2 bytes for price variable+ 2 bytes padding

A common memory of size equal to largest member size is allocated. Each member within union share the common memory.union book{ char title[20];

char author[40];

int price;

}b1 ;Memory allocated for b1 = 40 bytes

Size of structure is >= sum of sizes of its members

Size of union is equal to its largest member size

All the members can be assigned values at a time.

Only one member can be assigned value at a time

All the members can be accessed at same time

Only one member can be accessed at a time

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

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

Enumerated Data typesEnumerated 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”.

FilesFile 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

Page 32: C notes for exam preparation

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 FilesThere are 2 types of files.1. ASCII text files2. 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 CTo use files in C, we must follow the below steps1. Declare a FILE pointer variable2. Open the file (fopen)3. Process the file4. 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 filea 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

Page 33: C notes for exam preparation

"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 filesC 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 stream and stores it into the string pointed to by str.

char str[60];if( fgets (str, 60, fp)!

Page 34: C notes for exam preparation

It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

=NULL ) { /* writing content to stdout */ puts(str); }

fgetc() gets the next character from the stream and advances the position indicator for the stream

do { c = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", c); }while(1);

fread() fread function reads data from the given stream into the array pointed to, by ptr.

char c[] = "this is c program";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 files1. fprintf() 2. fputs() 3.fputc() 4. fwrite()