B.Sc. Computer Study Material Guide
B.Sc. Computer Study Material Guide
I [Link].
II SEMESTER
PAPER – 2
SYLLABUS - 2*03CSC15
UNIT I
Introduction to Algorithms and Programming Languages: Algorithm – Key features of
Algorithms – Some more Algorithms – Flow Charts – Pseudo code – Programming
UNIT II
Decision Control and Looping Statements: Introduction to Decision Control Statements –
Conditional Branching Statements – Iterative Statements – Nested Loops – Break and
Continue Statement – Goto Statement
Functions: Introduction – using functions – Function declaration/ prototype – Function
definition – function call – return statement – Passing parameters – Scope of variables –
Storage Classes – Recursive functions – Type of recursion – Towers of Hanoi – Recursion vs
Iteration
UNIT III
Arrays: Introduction – Declaration of Arrays – Accessing elements of the Array – Storing
Values in Array – Calculating the length of the Array – Operations on Array – one
dimensional array for inter-function communication – Two dimensional Arrays –Operations
on Two Dimensional Arrays - Two Dimensional Arrays for inter-function communication –
Multidimensional Arrays – Sparse Matrices
Strings: Introduction –Suppressive Input – String Taxonomy – String Operations –
Miscellaneous String and Character functions
UNIT IV
Pointers: Understanding Computer Memory – Introduction to Pointers – declaring Pointer
Variables – Pointer Expressions and Pointer Arithmetic – Null Pointers – Generic Pointers -
Passing Arguments to Functions using Pointer – Pointer and Arrays – Passing Array to
Function – Difference between Array Name and Pointer – Pointers and Strings – Array of
pointers – Pointer and 2D Arrays – Pointer and 3D Arrays – Function Pointers – Array 0f
Function Pointer – Pointers to Pointers – Memory Allocation in C Programs – Memory
Usage – Dynamic Memory Allocation – Drawbacks of Pointers
Structure, Union, and Enumerated Data Types: Introduction – Nested Structures – Arrays
of Structures – Structures and Functions – Self referential Structures – Union – Arrays of
Unions Variables – Unions inside Structures – Enumerated Data Types
Triveni 3
UNIT V
Files: Introduction to Files – Using Files in C – Reading Data from Files – Writing Data from
INDEX
Unit
Heading PageNo
No
2 Introduction to C 11
4 Functions 34
5 Arrays 42
6 Strings 47
7 Pointers 52
9 Files 67
Lab manual 72
Files – Detecting the End-of-file – Error Handling during File Operations – Accepting
Command Line Arguments – Functions for Selecting a Record Randomly - Remove() –
Renaming a File – Creating a Temporary File
Triveni 4
Triveni 5
UNIT - I
[Link] to Algorithms and Programming Languages
While
do-while and
for loops
Example: Algorithm to print the DENNIS WORD 10 TIMES.
Step 1 : [Initialize] Set I=1, N=10
Step 2 : Repeat Step 3&4 while I<=N
Step 3 : Print “DENNIS”
Step 4 : I=I+1
Step 5 : End
Some More Algorithms
1. Algorithm for swapping two values
Step 1: Input first number as A
Step 2: Input second number as B
Step 3: Set temp=A
Step 4: Set A=B
Step 5: Set B=temp
Step 6: Print A, B
Step 7: End
2. Algorithm to find whether a number is even or off
Step 1: Input the first number as A
Step 2: if A%2=0
then print “EVEN”
else
print “ODD”
Step 3: End
2. What is a Flowchart and explain its significance with an example.
A Flow Charts: A diagrammatic representation of the algorithm is called as flow charts.
They are constructed using some special geometric symbols. After developing the
algorithm a flowchart is drawn. Flowchart is useful to understand the computer program.
Symbols:
No Flow Chart Symbol Symbol Name Symbol Meaning
Beginning or end of a program
1 Oval
Input or output instructions
2 Parallelogram
Used for a calculation process other
3 Rectangle than a decision.
4
Diamond Decision-making and branching
Steps for drawing flow charts: The steps involved in the drawing or flow charts:
a) START: Every Flow Chart should begin with start instruction.
b) INITIALISATION: All the counters or variables should be assigned some initial
value.
c) INPUT: Some variables are assigned to the input variables in this step through READ
or ACCEPT statements.
d) PROCESSING: The processing step may consist of following operations:
a) Mathematical computations.
b) Movement of data value from one variable to another.
c) Conditions testing or decision-making.
d) Iteration of operations (a) through (c)
e) OUTPUT: The final results after processing of the input data are to be printed
displayed.
f) TERMINATION: The processing required at the end is to be done in this stage.
g) STOP: Every flow chart its module is to be closed with one or more stop instruction.
Example flowcharts
1. Addition of two numbers
The for loop is used for iterating a sequence for a specific number of times. The
keywords are FOR and ENDFOR.
EX: FOR each student in the class
Add 10 as bonus marks
ENDFOR
Examples of pseudocodes
1. Write a pseducode for calculating the price of a product after adding the sales tax to its
original price.
Types of Programming Languages: There are two main types of computer programming
languages.
• low-level languages
• high-level languages.
1. Low Level Programming Languages: These languages are near to computer hardware
and far from human languages. Computer can understand these languages easily.
Following are two low-level languages:
• Machine Language
• Assembly Language
a. Machine Language
Triveni 10
Assembly language is a low-level language. In assembly language, symbols are used instead
of binary code. These symbols are easy to remember. For example Add instruction is used to
add two numbers.
Assembly language is also known as second generation language
Advantages:
a) Assembly language programs are executed with fast speed
b) Assembly language programming is easier to learn, understand and modify than machine
language
Disadvantages:
a) Assembly language programs are machine dependent
b) Assembly language programming requires deep knowledge of hardware
INTRODUCTION TO C
Data Structures:- There are variety of ways to store data in C which allows easy
access to data.
Operator richness:- C supports a wide range of operators to handle arithmetic and
logical calculations.
Disadvantages of C:-
Difficult to debug:- C gives a lot of freedom to the developer but it appears bit
complex for a new comer to find what is wrong with a program.
Loosely syntaxes: - C allows a lot of freedom in coding. You can put end of
statement symbols (;), blank lines, white spaces anywhere you want in the
program. There is no fixed place to start or end a line. This can give rise to code
that is difficult to understand by reading.
Uses:
C language is primarily used for system programming. The portability, efficiency, the
ability to access specific hardware addresses and low runtime demand on system
resources makes it a good choice for implementing operating systems.
Compilers, libraries, and interpreters of other programming languages are often
implemented in C.
For portability and convenience reasons, C is sometimes used as an intermediate
language by implementations of other languages.
C is widely used to implement end-user applications.
5. Flexibility: (Key words or reserve words) ANSIC has 32 reserve words. ‘C’ language has
right number of reverse words which allows the programmers to have complete control on the
language. ‘C’ is also called as programmer’s language since it allows programmers to induce
creativeness into the programmers.
Function declaration section: Used to declare functions of program from which we get
required output.
Function definition section: Used to define functions which are to be called from main().
#include<stdio.h>
void main( )
{
clrscr( );
printf(“Welcome to b sc students”);
getch( );
}
Triveni 15
1. Creating a program :
An editor like notepad or WordPad is used to create a C program. This file contains a
source code which consists of executable code. The file should be saved as '*.c'
extension only.
2. Compiling the program :
The next step is to compile the program. The code is compiled by using compiler.
Compiler converts executable code to binary code i.e. object code.
3. Linking a program to library :
The object code of a program is linked with libraries that are needed for execution of
a program. The linker is used to link the program with libraries. It creates a file with
'*.exe' extension.
4. Execution of program :
The final executable file is then run by dos command prompt or by any other
software.
Double Precision real (or) Double (or) Long float data type:
It is a very large floating value.
Its range is 1.7E – 308 to 1.7E +308.
There are long double and long float are also available.
It occupies 8bytes of memory.
The format string specifier is %lf.
2. Structured (or) Derived data type: Derived data types are derived from the primary
data types by adding additional relationship with the elements of the primary data
types. These are used to represent a single or multiple values. These are also called as
structured or secondary data types. These are divided into 3 categories:
o Arrays and Strings
o Structures
o Unions
3. Enumerated (or) User Defined data type : This is also used for type definition i.e. it
allows the users to define a variable or an identifier, which is used to represent
existing data types. In other way it allows us to define new data types. These are
defined as below:
Syntax: enum identifier {v1, v2, v3,….., vn};
(or)
enum identifier {v1, v2, v3,…., vn} variable;
Example: enum month {Jan, Feb, Mar,…, Dec};
(or)
enum year {1999, 2000, 2001,…., 2005}y;
There is another user defined data type typedef. It is also used to represent the
existing data type and it can be used in place of the old data type anywhere in a C
program. It is defined as:
Syntax: typedef data type identifier;
Example: typedef int pay;
typedef float salary;
Here pay tells us the link with int and salary with the float and these can be
used for the declaration of the variable as:
pay p1, p2;
salary s1, s2, s3;
4. Void (or) Empty Data type: It is used in the user defined function or sub programs.
It is used when a function has not any argument and the function does not return a
value.
Syntax: void function name ( int, int ); void function name ( void );
Triveni 18
1. Numeric constant:- These constants have the numeric value of the combination of
sequence of digits i.e., from 0 – 9 as alone digit or combination of 0 – 9 with or with out
decimal point/ precision value having positive or negative sign. The numeric constant is
of two types:
1. Integer numeric constant: these constants have no decimal or precision point.
These constants range between 0 – 9 and have either + ve, or – ve sign. These are
again divided into three types:
Decimal integer numeric constant: These constants have no decimal or precision
point. These constants range between 0 – 9, and have either + ve or – ve sign.
Ex: 123, -239, 0, 8, -9, + 4, etc
Octal integer numeric constant: These constants consists of combination of digits
from 0 – 7 with positive or negative sign. It has leading with O or o (upper or
lower case). It will lead with either ‘O’ or ‘o’ means Octal or octal.
Ex: O37, O5, - o455, etc
Hexa decimal integer numeric constant: These have Hexa decimal data. These
constants will be preceded by ox, ox, ox, x, x. The combination of values are 0 – 9
and a – f ( a – f ) or alone. The alphabets a – f/ a – f represents the numeric values
10 – 15.
Ex: ox32, ox92, oxdef, etc
3. Character constant (Non Numeric Constant ):- These constants have a either a single
character or a group of characters or a character with a backslash. They are used for
special purpose. These constants are again divided into three types:
Single character constant: these constants have a single character within a single
quote (‘). Ex: ‘a’, ‘m’, ‘3’, ‘+’ , etc
String character constant: These constants have a string value enclosed in double
quotes (“). A string is the collection or combination of characters.
Ex: “hello”, “computers”, “2001 – 2002 “, “2003”, etc
Triveni 19
Backslash character constant: These constants are used for special purpose in the
programming languages. They are used to arrange the output in an order. They are
also used in the statements like printf, scanf, etc. The backslash characters are also
known as “Escape Sequence” characters. The following are the various escape
sequences used in c + +.
Constants Purpose
‘ \ a ‘ or “ \a “ Produces a beep sound when executed
‘ \ b ‘ or “ \b “ Backspace
‘ \ n ‘ or “ \n “ New line
‘ \ t ‘ or “ \t “ Horizontal tab
‘ \ v ‘ or “ \v ” Vertical tab
‘ \ r ‘ or “ \r “ Carriage return
‘ \ ? ‘ or “ \? “ Displays question tag
‘ \ \ ‘ or “ \\ “ Displays backslash
‘ \ “ ‘ or “ \ “ “ Displays double quotes and etc.
8. What is a variable? What are the rules that are to be followed during variable
declaration?
It is a data name which is used to store data and may change during program
execution. It is opposite to constant. Variable name is a name given to memory cells location
of a computer where data is stored.
The following is the syntax for the declaration of variable:
Syntax: data type variable name;
Example: int a; (or) float b;
Variables of different data type must be declared in different statements. But variables of
same data type can be declared in a single statement, separated by comma.
Syntax: data type variable name1, variable name 2,………, variable name n;
Example: int a, b, c;
Assigning values to variables: values to variables can be assigned in two ways:
Assigning values at the time of declaration
Assigning values after declaration
Assigning values at the time of declaration:
We can assign value to the variable at the time of declaring variables. These values
act like default values of the variables, when the variable is accessed.
Syntax: data type variable name = assigning value;
Example: int a = 5;
Assigning values after the declaration:
We can assign value to the variable after the declaration of the variable. Accepting values
from the user using input statements or assigning a value to the variable after the
declaration statement are known as assigning values after declaration.
Syntax: data type variable name;
Variable name = assigning value;
Example: int a;
int a = 5;
or
int a;
printf( “Enter a value into a “);
scanf(“%d”,&a);
Triveni 20
Operato Meaning
r
, Comma
&, * Pointer Operators
. Member selection
#, ## Pre processor
size of( ) :
The size of( ) operator returns the size of operand in bytes. The size of operator
always preceeds its operand in bytes. The operand may be a variable or a data type.
Ex: size of (int);
double d;
size of (d);
Triveni 23
The size of( ) operator is normally used to determine the length of arrays and structures, when
their sizes are not known to the programmer. These also used to allocate the memory space
dynamically to variables during the execution of program.
10. What is Operator Precedence and Explain with an examples (or) Hierarchy of
operations?
The individual constant, variables array elements and functions can be joined by
operation to form expression. These operators in ‘C’ language as precedence associated with
in. This precedence is used to determine, how an expression, involving more than one
operator is evaluated. The operators having higher level of precedence are evaluated first.
The operator of the same precedence are evaluated either from left to right (or) right to left,
depending on the associative property of an operator. The following table provides a
complete list of operators their precedence levels and their rules of association.
1. getchar(): The simplest of all input operations is reading a single character from
input unit (keyboard)
Syntax: char variable name;
Variable name=getchar();
Example: char ch;
ch=getchar();
5. scanf(): This is formatted input function. The scanf input statement is used for reading
mixed data type. It allows to read integer, float, character, hexadecimal, octal, decimal
data by using its format specifier.
Syntax: scanf (“control string”, arg1,arg2,………,argn);
(or)
scanf (“control string”,&v1,&v2,…….&vn);
Here arg1,arg2,………,argn are the arguments for reading and v1,v2,…….vn are all
variables.
Program:void main()
{
int a,b;
printf(“\n Enter a,b”);
scanf(“%d%d”,&a,&b);
printf(“\n addition = %d”, a+b);
}
Output functions:
These functions are used to output (or) print data from the computer onto he
standard output device (monitor or printer)
There are several output functions:
1. putchar()
2. putch() unformatted output functions
3. puts()
4. printf() Formatted output function
1. putchar(): This function displays a single character on the screen.
Syntax: putchar(v);
Where v is the variable of character type in which a single character data is
stored.
Program: void main()
{
char a;
printf(“Enter any character”);
a=getchar();
putchar(a);
}
2. putch(): This function is similar to putchar() which displays a single character, the
instant it is typed without waiting the enter key to be pressed. It displays the character on
the screen, which the user has typed.
Syntax: putch(variable);
Program: void main()
{
char a;
printf(“Enter any character”);
a=getch();
putchar(a);
}
3. puts(): This function is used to display a string at a time, in the standard output device
followed by a new character.
Syntax: puts(argument);
Program: void main()
{
Triveni 26
char triveni[20];
gets(triveni);
puts(triveni);
}
Output: Triveni
4. printf(): The printf() statement is used to display a text message or a value stored in
the variable.
Syntax: printf(“control string”,v1,v2,…….vn);
(or)
printf(“Message line or Text line”);
UNIT – II
[Link] CONTROL AND LOOPING STATEMENTS
Syntax:
if (condition)
{
True statement block;
}
Statement – x;
b. If – else Statement: This statement also has a single condition with two different
blocks. One is true block and another one is false block.
Syntax: Flow – Chart:
if (condition)
{
True statement block;
}
else
{
False statement block;
}
Statement – x;
Triveni 28
Flow – Chart:
else if (condition 2)
statement 2;
else if(condition 3)
statement 3;
else if(condition n)
statement n;
else
statement -x; "
Flow – Chart:
if(b>c)
printf("\nB is biggest:%d",b);
else
printf("\nC is biggest:%d",c);
getch();
}
3. Loop / repetitive / Iterative Control Statements: The repetition is done until condition
becomes true. A loop declaration and execution can be done in following ways.
Check condition to start a loop
Initialize loop with declaring a variable.
Executing statements inside loop.
Increment or decrement of value of a variable.
Types of looping statements:
Basically, the type of looping statements depends on the condition checking mode. Condition
checking can be made in two ways as: Before loop and after loop. So, there are 2(two) types
of looping statements.
Entry controlled loop
Exit controlled loop
1. Entry controlled loop:
In such type of loop, the test condition is checked first before the loop is executed. Some
common examples of these looping statements are:
while loop
for loop
2. Exit controlled loop:
In such type of loop, the loop is executed first. Then condition is checked after block of
statements are executed. The loop executed atleast one time compulsorily.
Some common example of this looping statement is:
do-while loop
i) while Loop: This is an entry controlled looping statement. It is used to repeat a block of
statements until condition becomes true.
Syntax: Initialization
initialization
while(condition)
{
statements;
increment/decrement; Condition F
}
Demo of While loop Program:
#include<stdio.h>
void main()
{ Body of theT Loop
int i=1;
clrscr();
while(i<=3) Increment/Decrement
{
printf("\nRama");
i++;
}
getch(); Next statement
}
Triveni 31
Output:
Rama
Rama
Rama
In above syntax, the condition is checked first. If it is true, then the program control flow
goes inside the loop and executes the block of statements associated with it. At the end of
loop increment or decrement is done to change in variable value. This process continues until
test condition satisfies.
ii) do- while: This is an exit controlled looping statement. Sometimes, there is need to
execute a block of statements first then to check condition. At that time such type of a loop is
used. In this, block of statements are executed first and then condition is checked.
Syntax:
do Initialization
{
statements;
(increment/decrement); Body of the Loop
}while(condition);
Example: Demo of Do-While loop.
#include<stdio.h> Increment/Decrement
void main()
{
int i=1;
clrscr();
do
{ Condition F
printf("\nRama");
i++;
}while(i<3);
getch(); T
}
Output:
Rama Next statement
Rama
Rama
In above syntax, the first the block of statements are executed. At the end of loop, while
statement is executed. If the resultant condition is true then program control goes to evaluate
the body of a loop once again. This process continues till condition becomes true. When it
becomes false, then the loop terminates.
iii) for loop: This is an entry controlled looping [Link] this loop structure, more than
one variable can be initilized. One of the most important feature of this loop is that the three
actions can be taken at a time like variable initilisation, condition checking and
increment/decrement. The for loop can be more concise and flexible than that of while and
do-while loops.
Syntax:
for(initialisation; test-condition; incre/decre)
{
statements;
}
Triveni 32
The default statement is not used and there is no match is found the control
transfer to the next statement of the program and there is no output.
Example: Demo of Switch control Statement.
#include<stdio.h>
void main()
{
int day_no;
clrscr();
printf("\t\tEnter Day Number:\t");
scanf("%d", &day_no);
switch(day_no)
{
case 1: printf("\n\t\tSunday");
break;
case 2: printf("\n\t\tMonday");
break;
case 3: printf("\n\t\tTuesday");
break;
case 4: printf("\n\t\tWednesday");
break;
case 5: printf("\n\t\tThursday");
break;
case 6: printf("\n\t\tFriday");
break;
case 7: printf("\n\t\tSaturday");
break;
default: printf("\n\t\tInvalid Day_Number");
}
getch();
}
Output:
Enter Day Number: 6
Friday
5. Jump Control Statements: These statements are used to transfer the control from one
position to desired position that’s why these are also known as conditional transfer control
statements.
a) Break Statement: Sometimes, it is necessary to exit immediately from a loop as soon as
the condition is satisfied. When break statement is used inside a loop, then it can cause
to terminate from a loop. The statements after break statement are skipped.
Syntax : Figure :
break;
Example:
#include<stdio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
Triveni 34
{
if(i==5)
break;
printf(“ %d”,i);
}
getch();
}
OUTPUT – 1:
1234
Example:
#include<stdio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5)
continue;
printf(" %d”, i);
}
getch();
}
Output:
1 2 3 4 6 7 8 9 10
c) goto: It is a well known as 'jumping statement.' It is primarily used to transfer the control
of execution to any place in a program. It is useful to provide branching within a loop. When
the loops are deeply nested at that if an error occurs then it is difficult to get exited from such
loops. Simple break statement cannot work here properly. In this
situations, goto statement is used.
Syntax :
goto label;
label creation
labelname:
Ex: err:
Figure :
Triveni 35
[Link]
void display( )
{
printf(“Rama”); called function
}
Argument: In order to perform specific tasks we have to send some information to the called
function in the form of an argument. There are different types of arguments known as
1. Actual Argument 2. Formal Argument
1. Actual Argument: Argument which is at calling function level it may be either
constant, variable, or expression.
2. Formal Argument: It is an argument which is at called function level. It must be a
variable.
void main( )
{
int x=5, y=6;
add(x,y); Actual Arguments
}
Triveni 36
Return Statement: It is used to return a value from called function to the calling
function. It is enable to return more than single value.
Eg: return(5);
return(x);
return(x+5);
Prototype of a function: It tells the compiler the characteristics of function. i.e., return
type, [Link] arguments and their types.
Eg: void add(int,int);
void display( );
long fact(int);
Rules for constructing user defined functions:
1. A function must be followed by a pair of parenthesis.
2. Arguments of a function must be enclosed with in a pair of parenthesis.
3. If a function name followed by a block of code i.e called function definition.
4. If a function name followed by a semicolon than it is invoked from other function
5. Prototype of called function should be declared from it gets called.
6. A Function can be called from any other function any [Link] times.
7. Even main function can be called from any other function
8. Main function may be defined any where of the program but execution is started with
main only.
9. [Link] actual arguments must be equal to [Link] formal arguments, in same order with
same data type.
10. A function can be called from itself. such a function is called recursive function and
such a process is known as recursion.
11. A function should not be defined with in the another function definition,
12. Keywords and system defined function names must not be used for user defined
functions.
13. A function can be called from any part of C program i.e from decision control
statement, loop control statements.
14. A function name can be used as argument to the another function calling
15. A function can be called from the other function by using the following methods.
call by value call by reference
16. The value can be returned from called function to the calling function by using return
statements.
17. A function can be ported into [Link] program by including the function name to other
program.
Uses of Functions:
1. reusability
2. reducing the return dent code
3. modularity
4. portability
5. Debugging time.
Advantages :
It is easy to use.
Debugging is more suitable for programs.
Triveni 37
2. Call by Reference: In this mechanism the address of the actual arguments are copied
on to the formal arguments, though they may be referred by different variable names. The
content of the variables that are altered within the function block are returned to the calling
portion of a program in the altered form it self, as the formal and the actual arguments are
referencing the dame memory location (or) address. This is technically known as call by
reference (or) call by address.
Example: A program to swap the contents of two variables using call by address.
#include<stdio.h>
Triveni 38
printf("\n\n\t %d",i);
getch();
}
Output :
20
10
2. Register variables:
Keyword : register
Storage Location : CPU Register
Initial Value : Garbage
Life : Local to the block in which variable is declared.
Scope : Local to the block.
Syntax :
register [data_type] [variable_name];
Example :
register int a;
Program :
#include <stdio.h>
#include <conio.h>
void main()
{
register int i=10;
clrscr();
{
register int i=20;
printf("\n\t %d",i);
} Output :
printf("\n\n\t %d",i); 20
getch(); 10
}
3. External Storage Class :
Keyword : extern
Storage Location : Main memory
Initial Value : Zero
Life : Until the program ends.
Scope : Global to the program.
Syntax :
extern [data_type] [variable_name];
Example :
extern int a;
The variable access time is very fast as compared to other storage classes. But few registers
are available for user programs.
The variables of this class can be referred to as 'global or external variables.' They are
declared outside the functions and can be invoked at anywhere in a program.
Program :
#include <stdio.h>
#include <conio.h>
extern int i=10;
void main()
{
Triveni 40
int i=20;
void show(void);
clrscr();
printf("\n\t %d",i);
show();
getch();
}
void show(void) Output :
{ 20
printf("\n\n\t %d",i); 10
}
4. Static Storage Class :
Keyword : static
Storage Location : Main memory
Initial Value : Zero and can be initialize once only.
Life : depends on function calls and the whole application or program.
Scope : Local to the block.
Syntax :
static [data_type] [variable_name];
Example :
static int a;
There are two types of static variables as :
a) Local Static Variable b) Global Static Variable
Static storage class can be used only if we want the value of a variable to persist between
different function calls.
Program :
// Program to demonstrate static storage class.
#include <stdio.h>
#include <conio.h>
void main()
{
int i;
void incre(void);
clrscr();
for (i=0; i<3; i++)
incre();
getch();
}
void incre(void)
{
int avar=1;
static int svar=1;
avar++;
svar++;
printf("\n\n Automatic variable value : %d",avar);
printf("\t Static variable value : %d",svar);
}
Output :
Automatic variable value : 2 Static variable value : 2
Automatic variable value : 2 Static variable value : 3
Triveni 41
1. Direct Recursion: A function is said to be directly recursive if it explicitly calls itself. For
example, consider the function given below.
int Func( int n)
{
if(n==0)
retrun n;
return (Func(n-1));
}
2. Indirect Recursion: A function is said to be indirectly recursive if it contains a call to
another function which ultimately calls it. Look at the functions given below. These two
functions are indirectly recursive as they both call each other.
int Func1(int n) int Func2(int x)
{ {
if(n==0) return Func1(x-1);
return n; }
return Func2(n);
}
3. Tail Recursion:
•A recursive function is said to be tail recursive if no operations are pending to be
performed when the recursive function returns to its caller.
•That is, when the called function returns, the returned value is immediately returned from
the calling function.
•Tail recursive functions are highly desirable because they are much more efficient to use as
in their case, the amount of information that has to be stored on the system stack is
independent of the number of recursive calls.
int Fact(n) int Fact1(int n, int res)
{ {
return Fact1(n, 1); if (n==1)
} return res;
return Fact1(n-1, n*res);
}
4. Linear and Tree Recursion:
•A recursive function is said to be linearly recursive when no pending operation involves
another recursive call to the function. For example, the factorial function is linearly
recursive as the pending operation involves only multiplication to be performed and does
not involve another call to Fact.
•A recursive function is said to be tree recursive (or non-linearly recursive) if the pending
operation makes another recursive call to the function. For example, the Fibonacci
function Fib in which the pending operations recursively calls the Fib function.
Triveni 43
UNIT - III
[Link]
Initialization: An array can be initialized by placing the elements with in a pair of brasses
and separated by camma(,) operated.
int a[5]={12,13,14,15,16};
int a[3][3]={{12,13,14},{23,34,45},{67,78,89}};
or
{12,13,14,23,24,25,67,78,89};
Accessing : T.D.A elements can be accessed by using two subscript variables. The value of
first one is valid from 0 to [Link] rows minus one and the value second one should be valid
from 0 to [Link] columns minus one.
Reading:
int i,j,r,c,a[100];
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”,&a[i][j]); //Here a[i][j] are two subscripted variables
}
Writing:
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(“ %d”,a[i][j]);
}
printf(“\n”);
}
3. Multi – Dimensional Array
Arrays can have more than one dimension is called multi dimensional array.
Syntax: storage class data type array name [expression1] [expression2] . . . .
[Expression n];
1. Where the storage class refers to the scope of the array variable such as external,
static, automatic (or) register.
2. Where the data type refers to the nature of the data elements in the array such as
character type, integer type (or) floating point etc.
3. Where the array name is the name of the multidimensional array. Expression 1,
expression 2, expression n refers to the maximum of the each array locations.
Examples:
int value [50][10][5];
char line [10] [80];
The First one is a three dimensional integer array whose maximum size is 2500
elements.
=================================================================
2. What are the operations that can be performed on Arrays?
A. There are number of operations that can be performed on arrays. These operations include:
1. Traversal: Traversing means accessing each and every element of the array.
Triveni 45
Linear search:
5. Merging: Merging means copying the content of one array to another array or copying the
contents of first array to third array, and then copy the contents of second array to third array.
6. Sorting: Sorting means arranging the elements of the array in some relevant order which
may either be ascending or descending. There are two types of sorting: Internal, Sorting.
3. Explain Sparse Matrices.
Sparse matrix is a matrix that has many elements with a value zero.
In order to efficiently utilize the memory, specialized algorithms and data structures
that take advantage of the sparse structure of the matrix should be used. Otherwise,
execution will slow down and the matrix will consume large amounts of memory.
Triveni 47
There are two types of sparse matrices. In the first type of sparse matrix, all elements
above the main diagonal have a value zero. This type of sparse matrix is also called a
(lower) triagonal matrix. In a lower triangular matrix, Ai,j = 0 where i<j.
An nXn lower triangular matrix A has one non zero element in the first row, two non
zero element in the second row and likewise, n non zero elements in the nth row.
In the second variant of a sparse matrix, elements with a non-zero value can appear
only on the diagonal or immediately above or below the diagonal. This type of matrix
is also called a tridiagonal matrix.
In a tridiagonal matrix, Ai,j = 0 where | i – j| > 1. Therefore, if elements are present on
the main diagonal the, it contains non-zero elements for i=j. In all there will be n
elements
diagonal below the main diagonal, it contains non zero elements for i=j+1. In all there
will be n-1 elements
diagonal above the main diagonal, it contains non zero elements for i=j-1. In all there
will be n-1 elements
1
1 2
9 3 1
4 2
2
5
1 9
6 7
Triveni 48
[Link]
1. What is character array (String)? Explain how to create and initialise the character
array.
• A string is a null-terminated character array. This means that after the last character, a
null character (‘\0’) is stored to signify the end of the character array.
• The general form of declaring a string is
char str[size];
• For example if we write,
char str[] = “HELLO”;
We are declaring a character array with 5 characters namely, H, E, L, L and O.
Besides, a null character (‘\0’) is stored at the end of the string. So, the internal
representation of the string becomes- HELLO’\0’. Note that to store a string of length 5,
we need 5 + 1 locations (1 extra for the null character).
The name of the character array (or the string) is a pointer to the beginning of the
string.
Reading of a string:-
If we declare a string by writing
char str[100];
Then str can be read from the user by using three ways
use scanf function
using gets() function
using getchar()function repeatedly
• The string can be read using scanf() by writing
scanf(“%s”, str);
• The string can be read by writing
gets(str);
gets() takes the starting address of the string which will hold the input. The string
inputted using gets() is automatically terminated with a null character.
Triveni 49
Writting of a string:-
The string can be displayed on screen using three ways
• use printf() function
• using puts() function
• using putchar()function repeatedly
The string can be displayed using printf() by writing
printf(“%s”, str);
The string can be displayed by writing
puts(str);
2. Explain suppressing input.
• scanf() can be used to read a field without assigning it to any variable. This is done
by preceding that field's format code with a *. For example, given:
scanf("%d*c%d", &hr, &min);
• The time can be read as 9:05 as a pair. Here the colon would be read but not assigned
to anything.
Using a Scanset
• The ANSI standard added the new scanset feature to the C language. A scanset is used
to define a set of characters which may be read and assigned to the corresponding
string. A scanset is defined by placing the characters inside square brackets prefixed
with a %
int main()
{
char str[10];
printf("\n Enter string: " );
scanf("%[aeiou]", str );
printf( "The string is : %s", str);
return 0;
}
• The code will stop accepting character as soon as the user will enter a character that is
not a vowel.
• However, if the first character in the set is a ^ (caret symbol), then scanf() will accept
any character that is not defined by the scanset. For example, if you write
scanf("%[^aeiou]", str );
The sscanf() function: This function reads data from str and stores them according to the
parameter format into the specific location. Consider the following:
sscanf(str, “%d”, &num);
a) First parameter str contains the data to be converted.
b) Second parameter %d determines how the string is converted.
c) Third parameter specifies memory location to place the result of the conversion.
Fixed length String: When storing a string in fixed length format, we need to specify an
approximate size for the string variable.
Variable Length String: In variable length format, the string expanded or condensed to
accommodate the elements in it. This can be done in two ways:
1. Length controlled string: In this format, we have to specify the count, this count is
then used by the string manipulation functions.
2. Delimited string: In this the string is ended with some delimiter. The NULL character
is most commonly used delimiter in the C language.
4. Explain string operations.
There are different string operations that are performed on character arrays.
1. Length: The number of characters in the string constitutes the length of the string. For
example, LENGTH(“C PROGRAMMING IS FUN”) will return 20. Note that even blank
spaces are counted as characters in the string. LENGTH(‘0’) = 0 and LENGTH(‘’) = 0
because both the strings does not contain any character.
Step 1: [INITIALIZE] SET I = 0
Step 2: Repeat Step 3 while STR[I] != '\0'
Step 3: SET I = I + 1
[END OF LOOP]
Step 4: SET LENGTH = I
Step 5: END
2. Converting to upper case: In memory the ASCII code of a character is stored instead of
its real value. The ASCII code for A-Z varies from 65 to 91 and the ASCII code for a-z
ranges from 97 to 123. So if we have to convert a lower case character into upper case, then
we just need to subtract 32 from the ASCII value of the character.
3. Converting to upper case: In memory the ASCII code of a character is stored instead of
its real value. The ASCII code for A-Z varies from 65 to 91 and the ASCII code for a-z
ranges from 97 to 123. So if we have to convert a lower case character into upper case, then
we just need to add 32 from the ASCII value of the character.
Triveni 51
4. Concatenating two strings: If S1 and S2 are two strings, then concatenation operation produces a
string which contains characters of S1 followed by the characters of S2.
5. Reversing a String: If S1= “HELLO”, then reverse of S1 = “OLLEH”. To reverse a string we just
need to swap the first character with the last, second character with the second last character, so on
and so forth.
Step1: [Initialize] SET I=0, J= Length(STR)
Step 2: Repeat Step 3 and 4 while I< Length(STR)
Step 3: SWAP( STR(I), STR(J))
Step 4: SET I = I + 1, J = J – 1
[END OF LOOP]
Step 5: EXIT
2. strcmp():The purpose of this function is to compare two strings. If two strings are equal then it
returns 0, if string1 is larger than string2 then it returns –ve value, if string2 is larger than
string2 then it returns +ve value.
Syntax: strcmp(string1, string2); Example: strcmp(“HELLO”, “HAI”);
3. strcpy():The purpose of this function is to copy one string to another.
Syntax: strcpy(string1, string2); Example: char name[30]; strcpy(name, “Rama”);
4. strlen(): This function count the number of characters in a string i.e., to find the length of the
string.
Syntax: n = strlen(string1); Example: n = strlen(“Rama”);
5. strrev(): The purpose of this function is to reverse a string. Here the first character becomes the
last and the last character becomes the first character.
Syntax: strrev(string); Example: strrev(“Rama”);
6. strlwr(): This function converts the string into lowercase.
Syntax: strlwr(string); Example: strlwr(“Rama”);
7. strupr(): This function converts the string into lowercase.
Syntax: strupr(string); Example: strupr(“Rama”);
AIM: Write a c program to demonstrate the string functions
#include<stdio.h>
void main( )
{
char s1[10]={“triveni”};
char s2[10]={“college”};
char s3;
clrscr( );
printf(“\nstring length:%d”,strlen(“Triveni”));
printf(“\nstring upper:”%s”,strupr(“triveni”));
printf(“\nstring lower:%s”,strlwr(“TRIVENI”));
printf(“\nstring reverse:%s”,strrev(“triveni”);
printf(“\nstring concat:%s”,strcat(s1,s2));
strcpy(s3,”dennis”)
printf(“\nstring copy:%s”,s3);
printf(“\nstring compare:%d”,strcmp(s1,s2));
getch()
}
TRIVENI 54
UNIT - IV
[Link]
Pointer to Pointer: It is a variable which can store the address of another pointer variable.
Declaration: datatype **variable name;
Example: Program to access array elements using pointers
#include<stdio.h>
main()
{
int a[]={10,20,30,40,50};
int i,*p;
clrscr();
p=&a[0];
printf("\nArray elements:");
for(i=0; i<5; i++)
{
printf("%d\t",*p);
p++;
}
getch();
}
OUTPUT: Array elements: 10 20 30 40 50
3. Write short notes on Pointer Arithmetic?
TRIVENI 55
Pointer Arithmetic: As a pointer holds the memory address of a variable; some arithmetic
operations can be performed with pointers. C supports four arithmetic operators that can be used
with pointer, such as
Addition +
Subtraction -
Incrementation ++
Decrementation - -
Pointers are variables. They are not integers, but they can be displayed as unsigned integers.
The conversion specifier for a pointer is added and subtracted.
Examples:
Increment operator on pointer variable:
if x is pointer variable
1. int *x;
x++;
The value x incremented by 2, since integer type requires 2 bytes long.
2. float *x;
x++;
The value of x incremented by 4, since floating type requires 4 bytes long.
3. char *x;
x++;
The value of x incremented by 1, since character requires 1 byte long.
Every time a pointer is incremented it points to the immediately next location of its base type.
Decrement operator on a pointer variable:
int *x;
x--;
Each time a pointer is decremented, it points to the location of the previous element.
A number can be added to pointer:
int i, *j;
i=5;
j=&i;
j=j+i;
A number can be subtracted from a pointer:
int i=5;
int *j;
j=&i;
j=j-2;
Subtraction of one pointer from another is possible:
This is possible when both variables point to elements of the same array. The resulting value
indicates the number of bytes separating the corresponding array elements.
main( )
{
int a[ ] = {10, 20, 30};
int *i, *j;
i=&a[0];
j=&a[2];
printf(“%d”,j-1);
}
j-1 would print a value 3 and not 6 i.e. the j & i are pointing to locations which are 3 integers
a part.
(i) Null Pointer: A null pointer which is a special pointer value that is known not to point anywhere.
This means that a NULL pointer does not point to any valid memory address. To declare a null
pointer you may use the predefined constant NULL,
int *ptr = NULL;
We can always check whether a given pointer variable stores address of some variable or
contains a null by writing,
if ( ptr == NULL)
{ Statement block;
}
Null pointers are used in situations if one of the pointers in the program points somewhere
some of the time but not all of the time. In such situations it is always better to set it to a null pointer
when it doesn't point anywhere valid, and to test to see if it's a null pointer before using it.
(ii) Generic Pointer: A generic pointer is pointer variable that has void as its data type. The generic
pointer, can be pointed at variables of any data type. It is declared by writing:
void *ptr;
We need to cast a void pointer to another kind of pointer before using it. Generic pointers are used
when a pointer has to point to data of different types at different times. For ex,
#include<stdio.h>
void main()
{ int x=10;
char ch = ‘A’;
void *gp;
gp = &x; printf("\n Generic pointer points to the integer value = %d", *(int*)gp);
gp = &ch; printf("\n Generic pointer now points to the character %c", *(char*)gp);
}
OUTPUT:
Generic pointer points to the integer value = 10
Generic pointer now points to the character = A
5. Explain (i) Pointer and Arrays (ii) Passing arrays to functions (iii) Difference between Array
Name and Pointer.
A. i. Pointers and Arrays: The concept of arrays is very much related to the pointers. Array
occupies consecutive memory locations.
Array notation is a form of pointer notation. The address of the first element of the array is called
base address. The name of the array is actually a pointer that points to the first element of the array.
Let us use a pointer variable as:
int *ptr;
ptr=&arr[0];
Example:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = &arr[0];
ptr++;
printf(“\n The value of the second element of the array is %d”, *ptr);
(ii) Passing arrays to functions: An array can be passed to a function using pointers. The function
that expects an array can declare the formal parameters in the following two ways:
TRIVENI 57
Func(int arr[]);
OR
Func(int *arr);
When we pass the name of the array to function, the address of the 0 th element of the array copied to
the local pointer variable in the function. We can access all the elements of the array using array
name and index. The declaration should be as:
Func(int arr[, int n);
OR
Func(int *arr, int n);
(iii) Difference between Array Name and Pointer:
1. When memory is allocated for array, its base address cannot be changed during program
execution, means array name is an address constant. However pointer variable may change.
2. Array cannot be assigned to another array. However one pointer variable is assigned to another.
3. For pointer, the address operator returns the address of the operand. For arrays, array name (arr)
and address of the array (&arr) gives the same value.
4. For arrays, sizeof operator returns the number of bytes allocated. For pointers, the sizeof operator
returns the number of bytes used for the pointers.
6. Explain (i) Array of pointers (ii) Pointer and 2D Arrays (iii) Pointer and 3D Arrays.
(i) Array of pointers: An array of pointers can be declared as int *ptr[10]
The above statement declares an array of 10 pointers where each of the pointer points to an
integer variable. For example, look at the code given below.
int *ptr[10];
int p=1, q=2, r=3, s=4, t=5;
ptr[0]=&p;
ptr[1]=&q;
ptr[2]=&r;
ptr[3]=&s;
ptr[4]=&t
Can you tell what will be the output of the following statement?
printf(“\n %d”, *ptr[3]);
Yes, the output will be 4 because ptr[3] stores the address of integer variable s and *ptr[3]
will therefore print the value of s that is 4.
(ii) Pointer and 2D Arrays: Individual elements of the array mat can be accessed using either:
mat[i][j] or *(*(mat + i) + j) or*(mat[i]+j);
• Pointer to an one dimensional array can be declared as,
int arr[]={1,2,3,4,5};
int *parr;
parr=arr;
• Similarly, pointer to a two dimensional array can be declared as,
int arr[2][2]={{1,2},{3,4}};
int (*parr)[2];
parr=arr;
• Look at the code given below which illustrates the use of a pointer to a two dimensional
array.
#include<stdio.h>
main()
{ int arr[2][2]={{1,2}.{3,4}};
int i, (*parr)[2];
parr=arr;
for(i=0;i<2;i++)
{ for(j=0;j<2;j++)
TRIVENI 58
b) Calloc( ): It is used to allocate a required bytes of memory for a variable and returns the base
address. In this case initially the locations are filled up with zero’s.
Syntax: pointer=(data type *)calloc(sizeof(data type),[Link] elements);
Eg: a=(int *)calloc(sizeof(int),10);
c) realloc( ): It is used to reallocate the allocated memory. But the contents of old memory locations
will be lost.
Syntax: pointer=(data type *)realloc(sizeof(data type)*[Link] elements);
Eg: a=(int *)realloc(sizeof(int)*10);
Drawbacks of pointers in c:
Un-initialized pointers might cause segmentation fault.
Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to
memory leak.
Pointers are slower than normal variables.
If pointers are updated with incorrect values, it might lead to memory corruption.
Basically, pointer bugs are difficult to debug. Its programmer’s responsibility to use pointers
effectively and correctly.
TRIVENI 62
1. What is a structure and explain the rules for declaration, initialization and accessing
structure?
Structures: It may be defined as a secondary data type which can store collection of dissimilar data
elements. In order to define structure we have to use the special keyword “struct”.
Syntax:
struct structurename
{
datatype varialbename;
datatype varialbename;
datatype varialbename;
datatype varialbename;
}structurevariable;
Definition:
struct employee
{
int eno;
char name[20]; 26 bytes elements/members of structure
float sal;
};
struct employee e1,e2; each structure variables it occupies 26 bytes of memory.
Initialization of Structure: Structure can be initialized by placing the elements with in a pair of
braces and separated by cama operator.
struct employee e={101,”SriRama”,3500.00};
or
[Link],[Link],[Link];
Accessibility of structure elements: Structure elements can be accessed with the help of dot or
arrow operators. On the left side of dot operator there must be a structure variable but on the right
hand side structure element should be there. On the left hand side of arrow operator there should be
pointer to structure but on right hand side structure element must be there.
Eg: [Link],[Link],[Link];
Eg: eeno,ename,esal;
Example:
Using Structure
struct student
{
int rollnum;
char name[100];
int m1,m2,m3,sum;
float avg;
};
struct student s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Rollnum:");
scanf("%d",&[Link]);
TRIVENI 63
2. Explain (i) Nested Structures (ii) Array of Structures (iii) Structures and Functions
(iv) Self referential Structures.
(i) Nested Structures: If the structure is defined within another structure such a concept is known as
nested structures. The elements of nested structures can be accessed with the help of two or more dot
or arrow operators.
Example:
struct student
{
int rno;
char name[30];
char course[10];
struct marks
{
int m1,m2,m3,sum;
float avg;
}g;
}s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Student Details:");
printf("\nEnter Student RollNum:");
scanf("%d",&[Link]);
printf("\nEnter Student Name:");
scanf("%s",&[Link]);
printf("\nEnter Student Course:");
scanf("%s",&[Link]);
printf("\nEnter Subject1:");
scanf("%d",&s.g.m1);
printf("\nEnter Subject2:");
scanf("%d",&s.g.m2);
printf("\nEnter Subject3:");
scanf("%d",&s.g.m3);
[Link]=s.g.m1+s.g.m2+s.g.m3;
[Link]=[Link]/3;
printf("\nStudent Rollnum:%d",[Link]);
printf("\nStudent Name:%s",[Link]);
printf("\nStudent Course:%s",[Link]);
printf("\nMarks1:%d",s.g.m1);
TRIVENI 64
printf("\nMarks2:%d",s.g.m2);
printf("\nMarks3:%d",s.g.m3);
printf("\nTotal Marks of Student:%d",[Link]);
printf("\nAverage Marks of Student:%f",[Link]);
getch();
}
(ii) Array of Structure: It may be defined as collection of similar structure stored in the adjacent
memory locations.
Example:
#include<stdio.h>
struct std
{
int rno;
char name[30];
};
void main()
{
struct std s[100];
int i,n;
clrscr();
printf("Enter [Link] Students:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter RollNum:");
scanf("%d",&s[i].rno);
fflush(stdin);
printf("\nEnter Name:");
gets(s[i].name);
fflush(stdin);
}
printf("\nThe Details are:\n");
for(i=1;i<=n;i++)
{
printf("\nRno:%d\nName:%s",s[i].rno,s[i].name);
}
getch();
}
(iii) Structure using functions: Struct variables can also be passed to a function. We may either
pass individual structure elements or the entire structure variables at one go.
#include<stdio.h>
struct book
{
int bno;
char bname[20];
};
void main()
{
struct book b={101,"JAVA"};
void disp();
clrscr();
TRIVENI 65
disp(b);
getch();
}
void disp(struct book b)
{
printf("\nBook no:%d",[Link]);
printf("\nBook name:%s",[Link]);
}
(iv) Passing Structures through Pointers: C allows to crerate a pointer to a structure. Like in other
cases, a pointer to a structure is never itself a structure, but merely a variable that holds the address
of a structure. The syntax to declare a pointer to a structure can be given as
struct struct_name
{
data_type member_name1;
data_type member_name2;
.....................................
}*ptr; OR
struct struct_name *ptr;
For our student structure we can declare a pointer variable by writing
struct student *ptr_stud, stud;
Example:
struct student
{
int rollnum;
char name[100];
int m1,m2,m3,sum;
float avg;
};
struct student s,*p;
#include<stdio.h>
void main()
{
p=&s;
clrscr();
printf("Enter Rollnum:");
scanf("%d",&p->rollnum);
printf("\nEnter Student Name:");
scanf("%s",&p->name);
printf("\nEnter 3 Subjects Marks:");
scanf("%d%d%d",&p->m1,&p->m2,&p->m3);
p->sum=p->m1+p->m2+p->m3;
p->avg=p->sum/3;
printf(“\nStudent Details are:”);
printf("\n\tRollNum:%d,\n\tName:%s,\n\tM1:%d,\n\tM2:%d,\n\tM3:%d,\n\tTotal:%d,\n\tAverage:
%f",p->rollnum,p->name,p->m1,p->m2,p->m3,p->sum,p->avg);
getch();
}
3. Write short notes on Unions?
A. Union is user defined data type used to stored data under unique variable name at single memory
[Link] is similar to that of structure. Syntax of union is similar to structure. But the major
difference between structure and union is 'storage.' In structures, each member has its own
TRIVENI 66
storage location, whereas all the members of union use the same location. Union contains many
members of different types, it can handle only one member at a time.
To declare union data type, 'union' keyword is used.
Union holds value for one data type which requires larger storage among their members.
Syntax:
union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;
Example:
union techno
{
int comp_id;
char nm;
float sal;
}tch;
In above example, it declares tch variable of type union. The union contains three members as data
type of int, char, float. We can use only one of them at a time.
* Memory Allocation :
Example:
Write a C program to demonstrate the unions.
#include<stdio.h>
union student
{
int rno;
char name[20];
float fees;
}s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Std Details:");
scanf("%d%s%f",&[Link],&[Link],&[Link]);
printf("\nThe Std Detials are:");
printf("\nRollNum:%d\nName:%s\nFees:%f",[Link],[Link],[Link]);
getch();
}
TRIVENI 67
clrscr();
if(r1==r2)
printf("\nBoth are equal");
else
printf("\nBoth are not equal");
getch();
}
Output:
Both are not equal
Structure Union
[Link] keyword struct is used to define a 1. The keyword union is used to define a
structure union.
2. When a variable is associated with a 2. When a variable is associated with a union,
structure, the compiler allocates the memory the compiler allocates the memory by
for each member. The size of structure is considering the size of the largest memory. So,
greater than or equal to the sum of sizes of its size of union is equal to the size of largest
members. The smaller members may end with member.
unused slack bytes.
3. Each member within a structure is assigned 3. Memory allocated is shared by individual
unique storage area of location. members of union.
4. The address of each member will be in 4. The address is same for all the members of a
ascending order This indicates that memory for union. This indicates that every member begins
each member will start at different offset at the same offset value.
values.
5 Altering the value of a member will not 5. Altering the value of any of the member will
affect other members of the structure. alter other member values.
6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.
7. Several members of a structure can initialize 7. Only the first member of a union can be
at once. initialized.
TRIVENI 69
UNIT - V
[Link]
1. Unformatted Disk I/O functions: These functions are used to access either character or string
type of information on secondary storage devices.
fgetc( ): It gets a character from a specific file.
Syntax: variable=fgetc(file ponter);
fputc( ): It prints a character into a specific file.
Syntax: fputc(character, file pointer);
fgets( ): It gets a string from a specific file.
Syntax: fgets(string name, max size, file pointer);
fputs( ): It prints a string into a specific file.
Syntax: fputs(string, file pointer);
2. Formatted Disk I/O functions: These functions are used to access any type of information from
or to the secondary storage devices.
fscanf( ): It is used to read any type of information from a specific file.
Syntax: fscanf(file pointer, ”format string specifies”, list of variables);
fprintf( ): It is used to print any type of information in required format into a specific file.
Syntax: fprintf(file pointer, ”format string specifies”, list of operands);
II. Record I/O functions: These functions are used to access an entire record from or to
a specific file.
fwrite( ): It prints an entire record into a specific file.
Syntax: fwrite(address of record, sizeof(record), [Link] records, file pointer);
fread( ): It gets an entire record from specific file.
Syntax: fread(address of record, sizeof(record), [Link] records, file pointer);
III. Other functions in files:
fopen( ): to open a file in specific mode.
Syntax: file pointer=fopen(“Filename”,mode);
Here mode may be one of the following:
Mode Description
r Opens an existing text file for reading purpose.
w Opens a text file for writing, if it does not exist then a new file is created. Here your
program will start writing content from the beginning of the file.
a Opens a text file for writing in appending mode, if it does not exist then a new file is
created. Here your program will start appending content in the existing file content.
r+ Opens a text file for reading and writing both.
w+ Opens a text file for reading and writing both. It first truncate the file to zero length if it
exists otherwise create the file if it does not exist.
a+ Opens a text file for reading and writing both. It creates the file if it does not exist. The
reading will start from the beginning but writing can only be appended.
TRIVENI 70
Write a C program to count numbers of (i) Words (ii) Lines (iii) Special characters in a given
text.
#include<stdio.h>
void main( )
{
FILE *fp;
char ch;
int noc=0, now=1, nol=0, nos=0;
clrscr( );
fp=fopen("[Link]","r");
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
noc++;
if(ch==' ')
{
now++;
nos++;
}
if(ch=='\n')
nol++;
}
fclose(fp);
printf("\nNumber of characters:%d",noc);
printf("\nNumber of words:%d",now);
printf("\nNumber of lines:%d",nol);
printf("\nNumber of spaces:%d",nos);
getch( );
}
OUTPUT:
TRIVENI 71
Number of characters:232
Number of words:27
Number of lines:20
Number of spaces:26
2) perror():
• perror() stands for print error. The perror() function is used to handle errors in C programs.
When called, perror() displays a message on stderr describing the most recent error that
occurred during a library function call or system call. The prototype of perror() can be given
as
void perror(char *msg);
• The perror() takes one argument msg which points to an optional user-defined message. This
message is printed first, followed by a colon and the implementation-defined message that
describes the most recent error.
• If a call to perror() is made when no error has actually occurred, then a “No error” will be
displayed. The most important thing to remember is that a call to perror() does nothing to
deal with the error condition.
• On successful operation, fseek() returns zero and in case of failure, it returns a non-zero
value. For example, if you try to perform a seek operation on a file that is not opened in
binary mode then a non-zero value will be returned.
fseek() can be used to move the file pointer beyond a file, but not before the beginning.
2) rewind():
• rewind() is used to adjust the position of file pointer so that the next I/O operation will take
place at the beginning of the file. It’s prototype can be given as
void rewind( FILE *f );
• rewind() is equivalent to calling fseek() with following parameters: fseek(f,0L,SEEK_SET);
3) fgetpos():
• The fgetpos() is used to determine the current position of the stream. It’s prototype can be
given as
int fgetpos(FILE *stream, fpos_t *pos);
• Here, stream is the file whose current file pointer position has to be determined. pos is used to
point to the location where fgetpos() can store the position information. The pos variable is of
type fops_t which is defined in stdio.h and is basically an object that can hold every possible
position in a FILE.
• On success, fgetpos() returns zero and in case of error a non-zero value is returned. Note that
the value of pos obtained through fgetpos() can be used by the fsetpos() to return to this same
position.
4) fsetpos():
• The fsetpos() is used to move the file position indicator of a stream to the location indicated
by the information obtained in "pos" by making a call to the fgetpos(). Its prototype is
int fsetpos( FILE *stream, const fops_t pos);
• Here, stream points to the file whose file pointer indicator has to be re-positioned. pos points
to positioning information as returned by "fgetpos".
• On success, fsetpos() returns a zero and clears the end-of-file indicator. In case of failure it
returns a non-zero value
5) ftell():
• The ftell function is used to know the current position of file pointer. It is at this position at
which the next I/O will be performed. The syntax of the ftell() defined in stdio.h can be given
as: long ftell (FILE *stream);
• On successful, ftell() function returns the current file position (in bytes) for stream. However,
in case of error, ftell() returns -1.
• When using ftell(), error can occur either because of two reasons:
1. First, using ftell() with a device that cannot store data (for example, keyboard)
2. Second, when the position is larger than that can be represented in a long integer.
6) remove():
• The remove() as the name suggests is used to erase a file. The prototype of remove() as given
in stdio.h can be given as,
int remove(const char *filename);
• The remove() will erase the file specified by filename. On success, the function will return
zero and in case of error, it will return a non-zero value.
• On success, rename() returns zero. In case of error, it will return a non-zero value will set the
errno to indicate the error.
(ii) Creating temporary File:
• The tmpfile() function is used to create a temporary file. The tmpfile() opens the
corresponding stream with access parameters set as “w+”. The file created with tmpfile() will
be automatically deleted when all references to the file are closed. That is, the file created
will be automatically closed and erased when the program has been completely executed.
• The prototype of tmpfile() as given is stdio.h header file is,
FILE* tmpfile(void);
• On success, tmpfile() will return a pointer to the stream of the file that is created. In case of
error, the function will return a null pointer [and set errno to indicate the error.
TRIVENI 74
LAB MANUAL
[Link] program
Program:
#include<stdio.h>
void main()
{
int a,b;
clrscr();
printf("Enter Two Values:");
scanf("%d%d",&a,&b);
printf("\nBefore Swapping %d and %d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nAfter Swapping %d and %d",a,b);
getch();
}
Output:
2. QUADRATIC EQUATION
Aim: Write a c program to print roots of a quadratic equation.
Program:
#include<stdio.h>
#include<math.h>
void main()
{
float a,b,c,desc,root1,root2;
clrscr();
printf("\n\t\tEnter values for a,b and c:\n");
scanf("%f%f%f",&a,&b,&c);
desc=(b*b)-(4*a*c);
if(desc<0)
printf("\n\n\t\tRoots are Imaginary");
else if(desc>0)
{
printf("\n\n\t\tRoots are Real");
root1=(-b+sqrt(desc))/(2.0*a);
root2=(-b-sqrt(desc))/(2.0*a);
printf("\n\n\t\t\tRoot-1=%5.2f\n\n\t\t\tRoot- =%5.2f",root1,root2);
}
else
{
printf("\n\n\t\tRoots are Equal");
root1=(-b+sqrt(desc))/(2.0*a);
root2=(-b-sqrt(desc))/(2.0*a);
printf("\n\n\t\t\tRoot-1=%5.2f\n\n\t\t\tRoot-2=%5.2f", root1,root2);
}
getch();
}
Output:
3. REVERSE OF A NUMBER
Aim: Write a program to calculate reverse of a given number.
Program:
#include<stdio.h>
void main()
{
int d;
long n,rev=0;
clrscr();
printf("Enter N Value:");
scanf("%ld",&n);
while(n>0)
{
d=n%10;
rev=(rev*10)+d;
n=n/10;
}
printf("\nReverse of a given Num:%ld",rev);
getch();
}
Output:
Enter N Value:123
Reverse of a given Num:321
TRIVENI 78
4. PALINDROME OR NOT
Aim: Write a program to check whether the given number is palindrome or not.
Program:
#include<stdio.h>
#include<stdio.h>
void main()
{
long n, rev=0,t;
int d;
clrscr();
printf("Enter a no:");
scanf("%ld",&n);
t=n;
while(n>0)
{
d=n%10;
rev=(rev*10)+d;
n=n/10;
}
if(t==rev)
printf("\nIt is palindrome");
else
printf("\nIt is not palindrome");
getch();
}
Output:
Enter a number:121
It is not palindrome:121
TRIVENI 79
5. PRIME OR NOT
Aim: Write a c program to check whether the given num is prime or not.
Program:
#include<stdio.h>
void main()
{
int n, i, check=1;
clrscr();
printf("Enter a Number:");
scanf("%d",&n);
for(i=2; i<n; i++)
if(n%i == 0)
{
check=0;
break;
}
if(check==1)
printf("\nThe given no is prime");
else
printf("\nThe given no is not prime");
getch();
}
Output – 1:
Enter a number: 5
The given no is prime
Output – 2:
Enter a number: 9
The given no is not prime
TRIVENI 80
6. PASCAL TRIANGLE
Aim: Write a program to calculate Pascal Triangle.
1
1 1
1 2 1
1 3 3 1
1 4 5 4 1
Program:
#include<stdio.h>
void main()
{
int i,j,k=1;
clrscr();
for(i=0;i<5;i++)
{
for(j=0;j<40-i;j++)
printf(" ");
for(j=0;j<=i;j++)
{
if(j==0)
{
k=1;
}
else
{
k=(i*k-j*k+k)/j;
}
printf(" %d",k);
}
printf("\n");
}
getch();
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 5 4 1
TRIVENI 81
7. PERFECT OR NOT
Aim: Write a program to check whether the given no is perfect or not.
Program:
#include<stdio.h>
void main()
{
int n, s=0, i;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
for(i=1; i<n; i++)
if(n%i == 0)
s+=i;
if(n==s)
printf("\nThe given no is perfect:%d",s);
else
printf("\nThe given no is not perfect:%d",s);
getch();
}
Output – 1:
Enter a number:6
The given no is perfect:6
Output – 2:
Enter a number:9
The given no is not perfect:4
TRIVENI 82
9. ARMSTRONG OR NOT
Aim: Write a c program to check whether the given no is Armstrong or not.
Program:
#include<stdio.h>
void main()
{
long n, sd=0, d, t;
clrscr();
printf("Enter a number:");
scanf("%ld",&n);
t=n;
while(n>0)
{
d=n%10;
sd=sd+(d*d*d);
n=n/10;
}
if(t==sd)
printf("\nThe given no is Armstrong:%ld",sd);
else
printf("\nThe given no is not Armstrong:%ld",sd);
getch();
}
Output – 1:
Enter a number:153
The given no is Armstrong:153
Output – 2:
Enter a number:125
The given no is not Armstrong:134
TRIVENI 83
9. SUM OF DIGITS
Aim: Write a program to print sum of digits of the given number.
Program:
#include<stdio.h>
void main()
{
long n;
int sd=0, d;
clrscr();
printf("Enter a number:");
scanf("%ld",&n);
while(n>0)
{
d=n%10;
sd+=d;
n=n/10;
}
printf("\nSum of digits:%d",sd);
getch();
}
Output – 1:
Enter a number:123
Sum of digits:6
Output – 2:
Enter a number:456
Sum of digits:15
TRIVENI 84
Program:
#include<stdio.h>
void main()
{
int a[100],i,j,n,t;
clrscr();
printf("Enter N Array Size:");
scanf("%d",&n);
printf("Enter Array Elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nBefore Sorting Array Elements:\n");
for(i=0;i<n;i++)
{
printf(" %d",a[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
printf("\nAfter Sorting Array Elements:\n");
for(i=0;i<n;i++)
{
printf(" %d",a[i]);
}
getch();
}
Output:
Enter N Array Size:5
Enter Array Elements:89 12 34 21 85
Before Sorting Array Elements:
89 12 34 21 85
After Sorting Array Elements: 12 21 34 85 89
TRIVENI 85
Program:
#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],d[10][10],i,j,r1,c1,r2,c2;
clrscr();
printf("Enter R1*C1 Matrix Size:");
scanf("%d%d",&r1,&c1);
printf("Enter R2*C2 Matrix Size:");
scanf("%d%d",&r2,&c2);
if(r1!=r2||c1!=c2)
{
printf("\nMatrix Add & Sub is not possible");
exit(0);
}
printf("\nEnter R1*C1 Matrix Elements:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter R2*C2 Matrix Elements:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
//Addition
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
//Subtraction
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
d[i][j]=a[i][j]-b[i][j];
}
}
TRIVENI 86
Output:
Program:
#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,r1,c1,r2,c2,k;
clrscr();
printf("Enter R1*C1 Matrix Size:");
scanf("%d%d",&r1,&c1);
printf("Enter R2*C2 Matrix Size:");
scanf("%d%d",&r2,&c2);
if(r1!=c2)
{
printf("\nMatrix Mul is not possible");
exit(0);
}
printf("\nEnter R1*C1 Matrix Elements:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nEnter R2*C2 Matrix Elements:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);
}
}
// Calculate Matrix Multiplication
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]+=a[i][k]*b[k][j];
}
}
printf("\nMultiplication of Two Matrix:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf(" %d",c[i][j]);
}
TRIVENI 88
printf("\n");
}
getch();
}
Output:
Program:
#include<stdio.h>
void main()
{
int a[10][10],i,j,r1,c1;
clrscr();
printf("Enter R1*C1 Matrix Size:");
scanf("%d%d",&r1,&c1);
printf("\nEnter R1*C1 Matrix Elements:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\nThe Matrix Elements:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}
printf("\nTranspose of a Matrix:\n");
for(i=0;i<c1;i++)
{
for(j=0;j<r1;j++)
{
printf(" %d",a[j][i]);
}
printf("\n");
}
getch();
}
Output:
Transpose of a Matrix:
13
24
TRIVENI 90
Program:
Output:
Output:
Addition:25
iii. Function with argument without return value
#include<stdio.h>
void sum(int a, int b)
{
printf("\nAddition:%d",a+b);
}
void main()
{
int a,b;
clrscr();
printf("Enter Two Values:");
scanf("%d%d",&a,&b);
sum(a,b);
getch();
}
Output:
Output:
Enter Two Values:12 13
Addition:25
TRIVENI 92
b. Call by reference
void swap(int *a,int *b)
{
int t;
printf("\nBefore Swapping %d and %d",*a,*b);
t=*a;
*a=*b;
*b=t;
printf("\nAfter Swapping %d and %d",*a,*b);
}
void main()
{
int x,y;
clrscr();
printf("Enter Two Values:");
scanf("%d%d",&x,&y);
swap(&x,&y);
getch();
}
Output:
Enter Two Values:12 23
Before Swapping 12 and 23
After Swapping 23 and 12
TRIVENI 93
Program:
#include<stdio.h>
void main()
{
long fact(int);
int n;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
printf("\nFactorial of a given number:%ld",fact(n));
getch();
}
long fact(int n)
{
if(n<=1)
return(1);
else
return(n*fact(n-1));
}
Output – 1:
Enter a number:5
Factorial of a given number:120
Output – 2:
Enter a number:6
Factorial of a given number:720
TRIVENI 94
17. STRINGS
AIM
Write a c program to demonstrate the string functions
SOURCE CODE
#include<stdio.h>
void main( )
{
char s1[10]={“triveni”};
char s2[10]={“college”};
char s3;
clrscr( );
printf(“\nstring length:%d”,strlen(“Triveni”));
printf(“\nstring upper:”%s”,strupr(“triveni”));
printf(“\nstring lower:%s”,strlwr(“TRIVENI”));
printf(“\nstring reverse:%s”,strrev(“triveni”);
printf(“\nstring concat:%s”,strcat(s1,s2));
strcpy(s3,”dennis”)
printf(“\nstring copy:%s”,s3);
printf(“\nstring compare:%d”,strcmp(s1,s2));
getch()
}
TRIVENI 95
Program:
#include<stdio.h>
void main()
{
char s[10];
int i,len=0,check=1,j;
clrscr();
puts("Enter a string:");
gets(s);
for(i=0; s[i]!='\0'; i++)
len++;
for(i=0, j=len-1; i<(len/2); i++, j--)
if(s[i]!=s[j])
{
check=0;
break;
}
if(check==1)
puts("It is a string palindrome");
else
puts("It is not a string palindrome");
getch();
}
Output – 1:
Output – 2:
19. STRUCTURES
Aim: Write a program by using structures.
Program:
a. Using Structure
struct student
{
int rollnum;
char name[100];
int m1,m2,m3,sum;
float avg;
};
struct student s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Rollnum:");
scanf("%d",&[Link]);
printf("\nEnter Student Name:");
scanf("%s",&[Link]);
printf("\nEnter 3 Subjects Marks:");
scanf("%d%d%d",&s.m1,&s.m2,&s.m3);
[Link]=s.m1+s.m2+s.m3;
[Link]=[Link]/3;
printf(“\nStudent Details are:”);
printf("\n\tRollNum:%d,\n\tName:%s,\n\tM1:%d,\n\tM2:%d,\n\tM3:%d,\n\tTotal:%d,\n\tAverage:
%f",[Link],[Link],s.m1,s.m2,s.m3,[Link],[Link]);
getch();
}
Output:
Enter Rollnum:1001
Enter Student Name:Rama
Enter 3 Subjects Marks:56 78 89
Student Details are:
RollNum:1001,
Name:Rama,
M1:56,
M2:78,
M3:89,
Total:223,
Average:74.000000
}g;
}s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Student Details:");
printf("\nEnter Student RollNum:");
scanf("%d",&[Link]);
printf("\nEnter Student Name:");
scanf("%s",&[Link]);
printf("\nEnter Student Course:");
scanf("%s",&[Link]);
printf("\nEnter Subject1:");
scanf("%d",&s.g.m1);
printf("\nEnter Subject2:");
scanf("%d",&s.g.m2);
printf("\nEnter Subject3:");
scanf("%d",&s.g.m3);
[Link]=s.g.m1+s.g.m2+s.g.m3;
[Link]=[Link]/3;
printf("\nStudent Rollnum:%d",[Link]);
printf("\nStudent Name:%s",[Link]);
printf("\nStudent Course:%s",[Link]);
printf("\nMarks1:%d",s.g.m1);
printf("\nMarks2:%d",s.g.m2);
printf("\nMarks3:%d",s.g.m3);
printf("\nTotal Marks of Student:%d",[Link]);
printf("\nAverage Marks of Student:%f",[Link]);
getch();
}
Output:
Enter Student Details:
Enter Student RollNum:1001
Enter Student Name: Ramya
Enter Student Course: Bsc
Enter Subject1:78
Enter Subject2:89
Enter Subject3:91
Student Rollnum:1001
Student Name:Ramya
Student Course:Bsc
Marks1:78
Marks2:89
Marks3:91
Total Marks of Student:258
Average Marks of Student:86.000000
char name[100];
int m1,m2,m3,sum;
float avg;
};
struct student s,*p;
#include<stdio.h>
void main()
{
p=&s;
clrscr();
printf("Enter Rollnum:");
scanf("%d",&p->rollnum);
printf("\nEnter Student Name:");
scanf("%s",&p->name);
printf("\nEnter 3 Subjects Marks:");
scanf("%d%d%d",&p->m1,&p->m2,&p->m3);
p->sum=p->m1+p->m2+p->m3;
p->avg=p->sum/3;
printf(“\nStudent Details are:”);
printf("\n\tRollNum:%d,\n\tName:%s,\n\tM1:%d,\n\tM2:%d,\n\tM3:%d,\n\tTotal:%d,\n\tAverage:
%f",p->rollnum,p->name,p->m1,p->m2,p->m3,p->sum,p->avg);
getch();
}
Output:
Enter Rollnum:1001
Enter Student Name:Sathyaveni
Enter 3 Subjects Marks:89 78 91
Student Details are:
RollNum:1001,
Name:Sathyaveni,
M1:89,
M2:78,
M3:91,
Total:258,
Average:86.000000
printf("\nEnter RollNum:");
scanf("%d",&s[i].rno);
fflush(stdin);
printf("\nEnter Name:");
gets(s[i].name);
fflush(stdin);
}
printf("\nThe Details are:\n");
for(i=1;i<=n;i++)
{
printf("\nRno:%d\nName:%s",s[i].rno,s[i].name);
}
getch();
}
Output:
Enter [Link] Students:3
Enter RollNum:1001
Enter Name:Anupama
Enter RollNum:1002
Enter Name:Harika
Enter RollNum:1003
Enter Name:Divya
The Details are:
Rno:1001
Name:Anupama
Rno:1002
Name:Harika
Rno:1003
Name:Divya
e. Structures using Functions
#include<stdio.h>
struct book
{
int bno;
char bname[20];
};
void main()
{
struct book b={101,"JAVA"};
void disp();
clrscr();
disp(b);
getch();
}
void disp(struct book b)
{
printf("\nBook no:%d",[Link]);
printf("\nBook name:%s",[Link]);
}
Output:
Book no:101
Book name:JAVA
TRIVENI 100
20. UNIONS
Aim: Write a Program to demonstrate the unions.
Program:
union student
{
int rno;
char name[20];
float fees;
}s;
#include<stdio.h>
void main()
{
clrscr();
printf("Enter Std Details:");
scanf("%d%s%f",&[Link],&[Link],&[Link]);
printf("\nThe Std Detials are:");
printf("\nRollNum:%d\nName:%s\nFees:%f",[Link],[Link],[Link]);
getch();
}
Output:
21. FILES
Aim: Program to count numbers of (i)words (ii)lines (iii)special characters in a given text.
Program:
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int noc=0, now=1, nol=0, nos=0;
clrscr();
fp=fopen("p1.c","r");
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
break;
noc++;
if(ch==' ')
{
now++;
nos++;
}
if(ch=='\n')
nol++;
}
fclose(fp);
printf("\nNumber of characters:%d",noc);
printf("\nNumber of words:%d",now);
printf("\nNumber of lines:%d",nol);
printf("\nNumber of spaces:%d",nos);
getch();
}
Output:
Number of characters:232
Number of words:27
Number of lines:20
Number of spaces:26
TRIVENI 102
Program:
#include<stdio.h>
void main()
{
FILE *f1;
char s[80];
clrscr();
printf("\nOpening a File in Writing Mode:\n");
printf("Enter the data into file (Press Ctrl+z at last)");
f1=fopen("[Link]","w");
while(strlen(gets(s))>0)
{
fputs(s,f1);
fputs("\n",f1);
}
fclose(f1);
printf("\nOpening a file in Reading Mode\n");
f1=fopen("[Link]","r");
while(fgets(s,79,f1)!=NULL)
printf("%s",s);
fclose(f1);
getch();
}
Output:
23. ENUMS
Aim: Write a Program to demonstrate the enums.
Program:
#include<stdio.h>
enum rest
{
idly=10,
dosa=15,
voda=20
};
enum rest r1, r2;
main()
{
r1=idly;
r2=dosa;
clrscr();
if(r1==r2)
printf("\nBoth are equal");
else
printf("\nBoth are not equal");
getch();
}
Output:
Program:
#include<stdio.h>
void main()
{
int a[]={10,20,30,40,50};
int i,*p;
clrscr();
p=&a[0];
printf("\nArray elements:");
for(i=0; i<5; i++)
{
printf("%d\t",*p);
p++;
}
getch();
}
Output:
Array elements: 10 20 30 40 50
TRIVENI 105
Program:
#include<stdio.h>
void main()
{
int *p,n,i,sum=0;
clrscr();
printf("Enter [Link] Students:");
scanf("%d",&n);
p=(int *)malloc(n*sizeof (n));
printf("\nEnter marks:\n");
for(i=0;i<n;i++)
{
scanf("%d",(p+i));
sum+=*(p+i);
}
printf("\nThe No Of Students Are :%d",n);
printf("\nThe Grand Total Of All Student Marks Are:%d",sum);
getch();
}
Output:
RECORD PROGRAMS
[Link] program
1 Prime or not
2 Bubble sort
3 Multiplication of two matrices
4 Call by value & call by reference
5 Factorial of a number
6 Strings (Concatenation)
7 Structures
8 Fputs(), fgets() functions
9 Enums
10 Arrays using pointers
TRIVENI 107
Model paper1
SUBJECT-C PROGRAMMING
Max Marks: 75
Model paper2
SUBJECT-C PROGRAMMING
Max Marks: 75
12. What is Function? Explain difference between call by value and call by
reference?
(or)
Explain String functions?
April 2017
SUBJECT-C PROGRAMMING
Max Marks: 75
UNIT-II
[Link] iterative loops in c.
(or)
[Link] three categories of function prototype.
UNIT-III
13. Explain one dimensional array? Write a program to accept array of numbers and to find the
largest and smallest of the interred numbers.
(or)
[Link] string handling functions in detail.
UNIT-IV
[Link] in detail about dynamic memory management functions.
(or)
[Link] structures and union with examples.
UNIT-V
[Link] about file processing facilities available in c.
(or)
[Link] is a file? How to detect end of a file and explain the creation of temporary file.
TRIVENI 110