C All Units
C All Units
UNIT -I:
Introduction to Algorithms and Programming Languages
Advantages of Algorithms:
• It is easy to understand.
• Algorithm is a step-wise representation of a solution to a given problem.
• In Algorithm the problem is broken down into smaller pieces or steps hence, it
is easier for the programmer to convert it into an actual program.
Disadvantages of Algorithms:
• Writing an algorithm takes a long time so it is time-consuming.
• Branching and Looping statements are difficult to show in Algorithms.
Examples of Algorithms:
In order to write an algorithm, following things are needed as a pre-requisite:
Now let’s design the algorithm with the help of above pre-requisites:
Algorithm to add 3 numbers and print their sum:
1. START
2. Declare 3 integer variables num1, num2 and num3.
3. Take the three numbers, to be added, as inputs in variables num1, num2, and
num3 respectively.
4. Declare an integer variable sum to store the resultant sum of the 3 numbers.
5. Add the 3 numbers and store the result in the variable sum.
6. Print the value of variable sum
7. END
---
Q. explain about algorithm
What is algorithm and what are the advantages and disadvantages of algorithms
Explain key features of algorithm
---
Flowchart:
A flowchart is a graphical representation of an algorithm. Programmers often use
it as a program-planning tool to solve a problem. It makes use of symbols which
are connected among them to indicate the flow of information and processing.
Flowchart Symbols
Flowcharts use special shapes to represent different types of actions or steps in a
process. Lines and arrows show the sequence of the steps, and the relationships
among them. These are known as flowchart symbols.
---
Q. what is a flow chart and what are different flow chart symbols
---
Algorithm is complex to
2. understand. Flowchart is easy to understand.
Algorithm is difficult to
5. construct. Flowchart is simple to construct.
---
Q. what are the differences between flowcharts and algorithms
---
Pseudo code:
is merely the sequence of steps taken to solve a problem. The steps are normally
"sequence," "selection, " "iteration," and a case-type statement.
---
Q. what is pseudocode?
Compare pseudocode and algorithms
---
Programming Languages :
a program is defined as set of instructions. The programmers give instructions to
system to fulfill the requirement of user, is called programming. The computer
languages are used to develop programs, i.e. to give instructions to system.
The languages that are capable of accessing processor features directly are
called low level languages. With respect to systems, it is said that the system
understands low level languages. There is a problem with low level languages that
a program designed in low level language for a specific modal processor cannot be
executed on other modal processors because of change in features. This is called
hardware dependency.
For execution the high level programs must be converted into low level code
called machine code with the help of compilers or interpreters.
The C language is provided with two compilers. The first compiler converts high
level code into intermediate code and saves with extension “.obj” called object file
and the second compiler converts intermediate code into low level code, saves with
extension “.exe” and further loads into memory for execution. With this two
phases of conversion mechanism, the C provides security to high level code.
2G: The assembly language was classified into 2G. In this, the instructions were
not in binary system. Rather English letters / words were used to give instructions.
But when a program is written, it is need to be converted into machine code using
ASSEMBLERS (like compilers in C). These are machine dependent.
3G: The third generation languages are machine independent. These are more user-
friendly. When the program is written in 3GL, it needs to be converted into
machine code using compilers or interpreters.
4GL: These are more specialized towards specific purposes. These are used for
report generations from databases, mathematical optimization etc.
5GL: In these, the languages concentrate more on problem solving than the logic
implemented. The algorithms are not much bothered. These are used in Artificial
Intelligence
** now a days, the term generation of languages is not much used in the IT market.
Rather the classification of languages like structured programming languages ,
object oriented programming system are much used in the IT market.
---
Q. explain different generation of languages
---
The languages that support dividing of project into modules called programs,
and further into sub modules called functions, and link them together to execute as
a software project are called structured programming languages.
1. They have one entry (starting) point and one exit (ending) point.
2. They support sequential execution of program
3. They doesn’t support jumps in the program.
4. They execute instruction by instruction
So, these programs are simple, and can be well maintained. The advantages are :
---
Q. what is structured programming?
---
Introduction to C
C is a high level programming language developed by a team of people
under leadership of Dennis Ritchie in the year 1972. It was developed at AT &T’s
bell laboratories. It was developed on the systems consisting of UNIX operating
system and later 83% of the UNIX is reconstructed in C. It is developed by
combining the features of old languages B & BCPL and some of the own features
of Dennis Ritchie.
Though C is a high level programming language, it can access some of
processor features, so C is called middle level language.
General structure of C program
Comment section
Preprocessor
Global data members (variables) (if required)
Functions including statements and expressions
The comment section can be placed wherever required. These are used to
make sure programmer understands what he does in program when revisiting. In
C++ editor, the comments can be either single lined or multi lined. The single line
comments are placed with // and multi lined comments are placed within /* */
Ex: //this is single line comment
/* this is multi-
Lined comments */
The Preprocessor is a location where the programmer can link library files or
develop MACROs etc. the pre-processor is identified with a # symbol to runtime
environment. The directive “include” is used to link library files and “define” is
used to develop macros.
Ex:
# include< stdio.h >
# define PI 3.142857
Example program:
/* the first program to display welcome message */
#include<stdio.h>
void main(){
printf(“Welcome to C World”);
}
---
Q. give an introduction to C language
---
---
Key Words
Every programming language has its own set of pre-defined important words
called keywords, used to give instructions to system. Each keyword is reserved for
a specific purpose. The keywords can be used only for that purpose for which they
are reserved. The C language has 32 keywords. These cannot be used as identifiers.
Identifiers
Identifier is a name given to an entity in program. Generally the variables,
functions, structures etc are identified with names and these names are called
identifiers.
There are some rules for identifiers:
➔ In C, identifier must have less than 8 characters (on unix it is < 8, but in
windows it can be up to 32 characters)
➔ Identifier must start with alphabet and can have numbers in between.
➔ No special symbol including space is permitted other than underscore
➔ Keywords are not permitted
Format Specifiers
%c : single char
%s : string (group of characters)
%d : decimal format
%i : integer format
%u : unsigned format
%o : octal formal
%x : hexa-decimal format
%f : floating value
%e : scientific notation
Variables
During program execution, the programmer needs to reserve some memory
in RAM, to store data into that, to do process on it. As this reserved memory is
capable of varying its value it is called a variable. The variables are declared for
data types, and identified with an identifier (name).
Ex : int x; here 2 bytes memory is reserved of int type and it is named “x”.
Constants
Constants are something that donot change its value. In C, the constants are
classified into two types.
Constant variables: the variables declared with keyword “const” are called constant
variables. These once declared and assigned with a value, can not be modified
during program execution.
Ex : const int x=5;
Symbolic constants: in C, the macros developed are called symbolic constants.
Ex: # define PI 3.142857
In general practice, the symbolic constants are specified in upper case letters.
The constant variables when declared, they occupy some space in main memory
based on its data type. But the symbolic constants do not occupy any memory.
---
Q. write about tokens of C
Write about different components used in programming
---
IO Statements
The User Interface is providing interactivity between user and system. It is
managed with IO statements (instructions). The libraries stdio.h and conio.h have
functions pre-defined to handle IO operations.
printf() : is a standard output function, used to produce output onto monitor.
Syntax:
printf(“message to be displayed”);
printf(“message & format specifiers”, source variables / values);
ex:
printf(“Welcome to C”);
The main memory (RAM) includes no. of bytes memory , where each byte
is identified with a byte number. When a variable is declared, the first byte number
of reserved memory is called address of that variable and it is retrieved with the
operator & in C.
Ex:
int a;
scanf(“%d”,&a);
---
Q. explain basic IO statements in C
---
Operators in C
The operators are used to develop process.
Operators are basically classified into three types based on number of operands
they take.
Unary operators, Binary Operators and Ternary Operator.
Unary Operators : the operators that take single operand are called unary operators.
++, --, - (negation operator).
Binary Operators :
The operators that take two operands are called binary operators. These are
further classified into five types based on their purpose, viz.
➢ Arithmetic Operators : these are used to perform basic arithmetic operations
on numbers.
+, - , *, / and % (Modulus)
NOTE: The modulus operator can be used only with integer data type.
➢ Comparison operators: these are also called relational operators. These
operators take two operands and give a result of either true or false and
called Boolean values
---
Q. what are different operators in C
---
program example
/* program to add two numbers */
#include<stdio.h>
#include<conio.h>
void main(){
int a,b,c;
clrscr();
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“sum is %d”,c);
}
---
Syntax/Declaration:-
destination_datatype = (target_datatype)variable;
() : is a casting operator.
target_datatype: is a data type in which we want to convert the source data type.
example –
float x;
int y;
y=( int ) x;
here we are converting float(source) data type into int (target) data type.
2. Type conversion :
In type conversion, a data type is automatically converted into another
data type by a compiler at the compiler time. In type conversion, the destination
data type cannot be smaller than the source data type, that’s why it is also called
widening conversion. One more important thing is that it can only be applied to
compatible data types.
example –
int x=30;
float y;
y=x; // y==30.000000.
---
Q. explain what is type casting and type conversion
---
UNIT – II
When program executes, it gets executed line after line. But when some part of the
program need to be executed based on conditions, then decision control statements
are used. There are 2 decision control statements viz., Conditional Branching and
Iteration.
if( condition)
statement;
else
statement;
if( condition )
statement;
else if( condition )
statement;
else if( condition)
statement;
else
statement;
When the program needs to be divided into multiple branches and only one
executed amongst them, then the if-else-if ladder is used.
---
Q. Write about branching control statements
What are different types of if-else statements
---
Switch-case statement
Ex:
char ch;
printf(“Enter a character:”);
scanf(“%c”,&ch);
switch(ch)
{
case ‘a’:
case ‘e’:
case ‘i’:
case ‘o’:
case ’u’: printf(“VOWEL”); break;
default : printf(“consonant”);
}
---
Q. Write about switch-case statement
---
Iterative statements
The loops are used for iteration. Iteration is repeated execution of process. The
loops are controlled with a Boolean expression. If the Boolean expression results
true, the loops continue its execution and otherwise stops.
Based on placement of the condition, the loops are classified into two types.
i) entry controlled loops, ii) exit controlled loops. The loops that have Boolean
expression at end of loop body are called entry controlled loops and that have at
end of loop body are called exit controlled loops.
While statement:
The while keyword takes a Boolean expression (condition) and till the
expression results true, the loop continues its execution. The variable used in
Boolean expression must be initialized prior its use and we must use appropriate
counter in the loop body such that the Boolean expression becomes false at a state.
Otherwise it turns into an infinite loop.
Syntax :
Initialization;
While(boolen expression)
{
Statements;
Counter;
}
We can directly place the Boolean value true instead of Boolean expression to
make it as infinite loop.
The while statement is an entry controlled loop.
do statement: the do statement takes a while at end of loop, and it is called a do-
while loop. This is similar to the do-while of C and C++.
The difference between the while and do-while is that the Boolean
expression is placed at beginning of while and in do-while the Boolean expression
is placed at end. So it is called an exit controlled loop.
When we use the do-while, the loop body is executed at least once even if
the Boolean expression results false.
Syntax :
Initialization;
do{
statements;
counter;
}while(Boolean expression) ;
for statement:
the for is entry controlled loop and it takes the Boolean expression at
beginning of loop body.
Syntax :
Initialization;
for( ; Boolean expression; )
{
Statements;
Counter;
}
As in for loop, the program control comes to the location that is before first ;
we can logically shift initialization to that location and as every time the program
control comes to the location that is after second ; we can logically shift the
counter to that location, thus forming logical syntax of for as follows:
continue: is a keyword when executes skips rest of loop once and passes control
back to the loop.
Ex:
for(i=0;i<20;i++)
{
if(i%3==0)
Continue;
printf(“%d “,i);
}
The above code displays numbers between 0 and 20 by skipping multiples of 3.
break: is a keyword when executes, breaks the loop and passes control to rest of
the program.
for(i=0;i<10;i++)
{
if(i==5)
break;
printf(“%d “,i);
}
Will display 0 1 2 3 4
---
Q. What are different types of loops
What are different iterative statements
---
goto: is keyword , used to make jumps in the program. Fr making jumps in the
program, the location to which the program execution is to be jumped must be
labeled and the same label is to be specified to the goto keyword. The goto makes
program execution go to the location whose label is specified.
But one of the standards of the structured programming languages is
“sequential execution of program”. With the goto statement, this standard is
broken. So it is suggested to programmers not to user goto statements in program.
The programmers are to develop a controlled logic with goto statement, such
that it should not develop infinite occurrence.
Ex:
void main()
{
goto LABEL2;
LABEL1:
printf(“@ label 1”);
goto LABEL3;
LABEL2:
printf(“@ label 2”);
goto LABEL1;
LABEL3:
printf(“completed”);
}
---
Q. Write about goto statement
---
Functions
Functions
When a software project is developed, it includes lakhs of lines of code.
Writing thousands of lines of code within one main() function leads to confusion
and gives burden on system.
Almost all the high level languages provide a facility of dividing programs
into modules called functions. A function is piece of code identified with a name.
A function has two aspects, a definition and a call. The function definition
includes the process to be executed and the function call is invocation of definition.
A function defined once can be called number of times.
Advantages of functions:
➔ Increase in modularity of program
➔ Increase in readability of program
➔ Easy identification of errors
➔ Easy debugging of code
➔ Reusability of code
Function Definition:
The Function definition includes the process to be done. The entire process
to be done is grouped using braces and identified with a name. When the function
is called the process given in definition executes.
Syntax:
return_type fun_name( formal arguments)
{
Process to be done;
}
Function call:
The function call is invocation or activation of the definition. A function
defined once, can be called number of times.
The function’s return type is data type specification of the value being
returned by the function. In C, the Runtime’s default data type is int. So, if no
return type is specified, the C RE takes the return type as int. if the function won’t
return any value, then the return type must be specified as “void”.
As the main() won’t return any value, it is generally returned on “void main()”.
Ex:
int add(int a, int b) ;
void main()
{ int a,b,c;
printf(“Enter two numbers:”);
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf(“sum is %d”,c);
}
int add(int x, int y)
{
return x+y;
}
---
Q. Write about functions
What is a function and explain function call, definition and declaration
---
SCOPE of variables:
The scope of variables are based on the location they are declared. The
variables based on location of declaration, are classified into two types.
STORAGE CLASSES: The C has a concept called storage classes, that specifies
the lifetime of the variable and its scope. The different storage classes are as
follows.
declared as local variable, it has its scope with in that function and if
declared as global, then it has its scope in entire program. When declared
these will have garbage values.
Ex: auto int a;
RECURSIVE FUNCTIONS:
Recursion is the process of repeating items in a self-similar way. In
programming languages, if a program allows you to call a function inside the same
function, then it is called a recursive call of the function
The C programming language supports recursion, i.e., a function to call
itself. But while using recursion, programmers need to be careful to define an exit
condition from the function otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems,
such as calculating the factorial of a number, generating Fibonacci series, etc.
Ex1:
#include <stdio.h>
unsigned long long int factorial(unsigned int i) {
if(i <= 1)
return 1;
return i * factorial(i - 1);
}
int main() {
int i = 5;
Ex 2:
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
return 0;
---
Q. Explain recursive function with an example
---
UNIT-III
Arrays:
Introduction, Declaration of Arrays, Accessing elements of the Array, Storing Values
in Array,
When an array is declared, the C-RE gives index numbers to each element
for identification as all elements are identified with same name. The index number
of array elements start with ZERO. So the index of last element is always size-1.
The same [ ] are used to specify the index number of element while
manipulating the array. i.e. the array members can be accessed with their index
numbers.
int arr[5] = { 10, 20, 30,40, 50}; in this case, the number of initializers must be
either matching with size of array or less than array. If less initializers given when
size is specified, then the other elements are initialized with ZEROs.
or
int arr[ ]={10,20,30,40,50}; in this case, the size of array is based on number of
initializers.
The loops can be used to read data from keyboard and store into the array.
Ex:
for(i=0;i<5;i++)
scanf(“%d”,&arr[i]);
Calculating the length of the Array : if the array elements are initialised, then we take
help of sizeof() operator to find lengthof array.
There are different operations that can be performed with arrays like,
---
Q. Give an introduction to arrays
How to store values into array and access them
What is an array? What are the operations that can be done on arrays.
---
Accessing one dimensional array: the one dimensional array elements can be
accessed by specifying single index number for each element like arr[0], arr[1]
etc. we can use a loop for easy accessing each element by traversing across
each element as:
for(i=0;i<5;i++)
printf(“%d “, arr[i]);
Passing one dimensional array to function: we can also pass single dimensional
array as argument to function. While passing single dimensional array to a
function, we may specify the array size in formal arguments / forward
declarations or we may not.
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={10,20,30,40,50,60};
int size=sizeof(a)/sizeof(a[0]);
clrscr();
disp(a,size);
}
Or
#include<stdio.h>
#include<conio.h>
void disp(int[6]);
void main()
{
int a[]={10,20,30,40,50,60};
int size=sizeof(a)/sizeof(a[0]);
clrscr();
disp(a);
}
int i;
for(i=0;i<6;i++)
printf("%d ",a[i]);
}
---
Q. Write about single dimensional arrays
How to use single dimensional arrays
How to use functions with single dimensional arrays
---
2D and Multi dimensional arrays: the arrays can be used to manage large
data by providing multiple index references, for easy storage and manipulation.
Irrespective of number of dimensions specified, all the array elements will have
sequential memory allocated.
Ex : int arr[2][3];
In the above 2-D array, the memory allocated is sequential as given below:
arr
The above 2-D array can be manipulated using two loops, one to refer first
index number and the second referring second index number.
for( i=0;i<2;i++)
for(j=0;j<3;j++)
printf(“%d “,arr[i][j]);
A 2-D array can be logically felt as rows and columns by displaying content
row wise / column wise with below code.
for( i=0;i<2;i++)
for(j=0;j<3;j++)
printf(“%d “,arr[i][j]);
printf(“\n”);
Similarly, the arrays can have any number dimensions, and the size of each
dimension is specified with in a separate [ ].
Ex:
#include<stdio.h>
#include<conio.h>
void disp(int[2][3],int,int);
void main()
{
int a[2][3]={{10,20,30},{40,50,60}};
clrscr();
disp(a,2,3);
---
Q. Write about 2D arrays dimensional arrays
How to use multi dimensional arrays
How to use functions with multi dimensional or 2D arrays
---
Strings: Introduction,
When a string is assigned to a char array while initializing, there will be null
value represented as ‘\0’ stored at end of string for identification.
For easy manipulation of strings, the string.h library has number of pre-
defined functions like:
---
Q. write about Strings
Explain different string functions
Explain how to strings are managed in C
---
UNIT 4
Pointers
➔ Code part
➔ Static / global variables part
➔ Stack memory
➔ Heap memory
The machine code, in case of C, the executable file that has extension “.exe”
is loaded into CODE PART of the application’s memory.
The static variables and global variables of the program are allocated in a
special memory reserved for them.
The memory part in which the local variables are allocated with memory is
called STACK. The memory in stack is managed by the operating system itself.
The programmer need not specify explicitly how much memory is to be allocated
and this memory is released automatically soon after the program execution
completed. The stack size is fixed based on number of variables declared. Once
program execution starts, the stack size can not be either increased / decreased.
---
Q. Write about computer memory and application memory management?
---
Ex:
void main(){
int a=5;
int *p;
p=&a; //storing address of static memory (variable)
printf(“%d”,*p); //will display 5
}
Ex:
void main(){
int a,b,*p,*q;
a=5;
b=10;
p=&a;
q=&b;
Ex:
void main(){
int a,b,*p,*q;
a=5;
b=10;
p=&a;
q=&b;
When the pointer is manipulated with * , the values in the locations pointed
by the pointers are manipulated. The variable “a” is assigned with value pointed by
the pointer “q” and the value is assigned “NOT THROUGH variable” but through
the POINTER. So the value at location pointed by pointer “p” is modified, i.e. the
value of “a” become 10.
Now the above will display “a=10; b=10; *p=10; *q=10;”
---
Q. explain pointers and their usage
Q. Explain about pointer arithmetic operations.
Q. what is the difference between normal arithmetic operations and pointer
arithmetic operations
---
Null Pointers:
When a pointer is declared and not assigned with any address, it is suggested
to store a null value in that pointer, so that it won’t point to a garbage address. The
stdio.h library has a pre-defined macro NULL, that can be assigned to the pointer.
a=5;
b=10;
printf(“before swapping a=%d b=%d\n”,a,b);
swap(a,b);
printf(“after swapping a=%d b=%d\n”,a,b);
}
void swap(int a, int b)
{
int t;
t=a;
a=b;
b=t;
printf(“in swap function a=%d b=%d\n”,a,b);
}
Output:
before swapping a=5 b=10
in swap function a=10 b=5
after swapping a=5 b=10
though the function swapped, it is not affected in actual arguments.
swap(&a,&b);
printf(“after swapping a=%d b=%d\n”,a,b);
}
void swap(int *a, int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
printf(“in swap function a=%d b=%d\n”,*a,*b);
}
Output:
before swapping a=5 b=10
in swap function a=10 b=5
after swapping a=10 b=5
here as the pointers in called function points to the address of actual
arguments, the actual arguments are processed.
---
Q. Explain different ways of passing arguments to functions.
Q. what is function call by value and call by reference?
Q. Explain function call by reference with swap function example
---
void main(){
int a[]={5,10,15,20,25};
int *p;
p=&a[0];
printf(“%d”,*p) ; //will display 5
p++;
printf(“%d”,*p); //will display 10
}
The pointer arithmetic operation is different from normal arithmetic operation.
It is done on number of bytes based on data type of the pointer. The int* when
increased by 1 it gets increased by 2 bytes and the float* will increase by 4 bytes.
In any case, the pointer moves to next element in the memory.
• So the programmer must use appropriate pointer in the program, the int* can
be used to point only to int memory.
void main(){
int a[]={5,10,15,20,25};
int *p;
p=&a[0];
printf(“%d”,*p) ; //will display 5
printf(“%d”, *p+1 ); //will display 6
}
Here it displays 6, as pointer has higher priority, first *p is evaluated and +1
done.
The priority can be changed using ( ).
void main(){
int a[]={5,10,15,20,25};
int *p;
p=&a[0];
printf(“%d”,*p) ; //will display 5
printf(“%d”,* (p+1) ); //will display 10
}
Here first p+1 is done and then * applied to that new address. In p+1, as “p”
is an int pointer, it will increase by 2 bytes, and points to next element.
So in above example, when the array int a[] is declared, the RE has a pointer
with name “a” itself. That built in pointer can be manipulated as of normal pointer.
void main(){
int a[]={5,10,15,20,25};
int i;
for(i=0;i<5;i++)
printf(“%d “,*(a+i) );
}
Conclusion : in C or C++, we can declare arrays and use either array or pointer
syntax and also, we can declare pointers and use array or pointer syntaxes. The
difference is arrays are static memory and pointers support dynamic memory.
---
Q. write about pointers and arrays
Q. what are the difference between arrays and pointers
---
decreased with its size and also released. The dynamic memory is managed
with in heap of the application’s memory.
The dynamic memory is managed with the help of pointers. Functions related
with dynamic memory management are defined in the library “alloc.h” library.
malloc() : this function allocates specified number of bytes memory and returns its
base address that can be held by a pointer.
calloc() : it is similar to malloc(), but the malloc() leaves garbage values in the
reserved memory and the calloc() initializes all elements with zeros.
realloc() : is used to increase or decrease the size of memory reserved, but it is not
much used, as it leads to data loss.
free() : this function is used release the memory assigned to the pointer.
Ex: free(p);
---
---
Drawbacks of Pointers.
Advantages of pointers :
• Pointers provide direct access to memory
• Pointers provide a way to return more than one value to the functions
• Reduces the storage space and complexity of the program
• Reduces the execution time of the program
• Provides an alternate way to access array elements
• Pointers can be used to pass information back and forth between the calling
function and called function.
• Pointers allow to perform dynamic memory allocation and de-allocation.
Drawbacks of pointers in c:
• Uninitialized 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.
• Dangling pointers lead to memory crash
• If pointers are updated with incorrect values, it might lead to memory
corruption.
• Basically, pointer bugs are difficult to debug. Its programmers
responsibility to use pointers effectively and correctly.
---
---
Structure is a user defined data type, used to group no. of elements of different data
types with different names. A structure is defined with the keyword “struct”.
Syntax :
struct <structure_name>
{
Member variables;
};
Ex:
struct emp
{
int no, sal;
char name[20];
};
In above declaration, “struct emp” is data type. A variable has to be declared
for this data type to make use of its members. The structure variable is declared as
normal variable with syntax data_type var_name; . As here “struct emp” is data
type, the variable is declared as “struct emp e;” .
In above declaration the “e” is called structure variable and it is allocated
with memory for its members no, sal and name sequentially. The structure
members are accessed with structure variable with a DOT “ . ” operator called
PERIOD.
Ex:
e,no=5;
strcpy(e.name,“your_name”);
e.sal=5000;
Nested structures:
We can declare a structure variable as member within another structure, like
a normal other variables, and it is called nested structures.
In this case, the access the nested structure’s members, the period operator is used
twice as “sttuct_var . member_struct_var. member_var”
struct address
{
char city[20];
int pin;
};
struct employee
{
int no;
char name[20];
struct address add;
};
void main ()
{
struct employee e;
printff(“Enter number:”);
scanf(“%d”,&e.no);
printff(“Enter name:”);
scanf(“%s”,&e.name);
printff(“Enter City:”);
scanf(“%s”,&e.add.city);
printff(“Enter PIN code:”);
scanf(“%d”,&e.add.pin);
printf(“%d %s %s %d”,e.no,e.name,e.add.city,e.add.pin);
Arrays of structures:
The structures can be created with arrays of structure variables. In that case,
a loop is used to refer the index of structure variable’s array.
Ex:
struct emp{
int no,sal;
char name[20];
};
void main()
{
struct emp e[5];
int i;
for(i=0;i<5;i++)
{
printf(“Enter 5 employee data”);
scanf(“%d%s%d”,&e[i].no,&e[i].name, &e[i].sal);
}
Ex:
struct emp{
int no,sal;
char name[20];
};
void disp(struct emp);
void main()
{
struct emp e;
printf(“Enter employee data”);
scanf(“%d%s%d”,&e.no,&e.name, &e.sal);
disp(e);
}
void disp(struct emp e)
{
printf(“%d %s %d”,e.no,e.name.e.sal);
}
Union:
Unions are similar to structures but declared with keyword “union”. Similar
to structures, the unions are created with variables to make use of its members. But
when a union variable is declared, the largest member of the union is allocated
with memory and shared by all other members.
For example:
union abc
{
int x;
float y;
};
If a union is declared as above and created with a variable, “union abc a;”,
then the union variable “a” is allocated with 4 bytes memory and shared by both
members “x” and “y”. the first 2 bytes is called “x” and all 4 bytes together is
called “y”. thus unions provide better memory management.
union person{
int pensioner_id, employee_id;
};
void main(){
union person p;
}
In above case, the union variable “p” is assigned with only 2 bytes memory
and the same is called pensioner_id and the same itself is called employee_id. A
person can have either employee_id or pensioner_id. In this case, as there is a
requirement of using only one at a time, the programmers can prefer unions instead
of structures. Similar to structures, the unions can also be declared with array of
variables. We can declare nested structures or nested unions.
Ex:
enum week{ sun,mon,tue,wed,thu,fri,sat };
in above declaration, the first value sun is given with ZERO by default and
rest of the names are given with 1,2,3 etc numbers by default in a sequence.
printf(“%d”,sun) ; will display 0
The programmer can also assign required values for each or to the first
name. if a value is given only to the first name, then rest elements are given with
values incrementing by one. Or programmer may also assign individual values to
the names. Wherever programmer needs those values, instead of the values, he
may use the names of the enum.
Ex:
enum months{jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
void main()
{
clrscr();
printf(“%d - %d - %d”,16, apr, 2021);
}
Ex:
enum result{third=35,second=50,first=60,dist=75};
void main()
{
Marks taken input and calculated totals…..
if(tot<third)
printf(“fail”);
else if(tot<second)
printf(“third class”);
else if(tot<first)
printf(“second class”);
else if(tot<dist)
printf(“first class”);
else
printf(“distinction”);
}
---
Q what are enums?
Q. write about enumerated data types?
Q. what is the use of enumerations?
---
UNIT-5
FILES
When a program is developed, the code is divided into three parts viz.,
designing user interface, process and data storage.
The user interface in C is developed with IO functions and the process is
managed with operators, branching, loops, functions etc.
The data storage is managed with variables, arrays, pointers, structures,
unions etc. but all these are managed in RAM, which is volatile and stores data
temporarily. To use data in future, the data can be stored onto hard disk (secondary
memory) in the form of a file.
Through a C program, the programmer can create a new file, write data to it,
read data from it, append data to existing file etc.
Modes of operation:
If a file is opened in “w” mode, it creates a new file. If opened in “a” mode,
if a file exists, then data is appended at end of existing file and if no file exists, the
a new file is created.
A file opened in a specific mode can be operated for that purpose only.
As the file exists in hard disk and the program runs in RAM, the C provides a
facility of using a pointer in program to point to the file by storing its address.
The library stdio.h has a predefined typedef structure FILE, to which a pointer is
created and used for file manipulations.
fopen() : this function opens given file in specified mode and returns its address.
Syntax : fopen(“file name and path”,”mode”);
Ex: FILE *fp;
fp=fopen(“c: / college /data.txt”,”w”); this code creates a file data.txt in college
folder for data writing purpose.
fclose() : closes the file whose pointer is given. A file must be closed explicitly
once processing is done, unless which the file gets corrupted. when a file is closed
with fclose(), the C Runtime places a null value at end of file for identification
called EOF (End Of File).
Ex:
fclose(fp);
fseek() : used to place the file pointer to a specific byte in the file
ftell() : returns current byte number of pointer in the file.
foef() : this function is used to identify where the file pointer reached EOF or not.
---
Q. write about file handling
Q. write about reading / writing data from/to files
Ex:
void main()
{
FILE *fp;
int no,sal;
char name[20];
fp=fopen(“data.txt”, “w”);
printf(“Enter no,name and salary”);
scanf(“%d%s%d”,&no,name,&sal);
fprintf(fp, “%d %s %d\n”,no,name,sal);
fclose(fp);
}
Ex:
void main()
{
FILE *fp;
int no,sal;
char name[20];
fp=fopen(“data.txt”, “r”);
fscanf(fp,“%d%s%d”,&no,name,&sal);
while(!feof(fp))
{
printf( “%d %s %d”,no,name,sal);
fscanf(fp,“%d%s%d”,&no,name,&sal);
}
fclose(fp);
}
The EOF is End Of File , that can be detected in two ways. Either by checking
whether the character read through pointer has EOF or with the function feof().
• ch=fgetc(fp);
if( ch==EOF)
exit(1);
OR
---
Q. Write about how to read data from a file and how to write data?
---
The function ferror() returns true if any of the above error occurs during file
processing. If it returns true the programmer must terminate the program with
exit(1).
---
Q. Write about Error Handling in files.
---
This is not in your syllabus. But it is important topic for interviews. So added
this here.
The arguments passed from command line into the main() definition are
called command line arguments. These are passed into program, while starting its
execution from command prompt. Generally we pass the ‘configurations required
for program execution’ as command line arguments into program.
The arguments passed from command line are received into main()
definition, for further processing. The main() can have 2 formal arguments. The
first one is an integer that keeps the count of arguments, generally represented with
name “argc” and the second is char pointers array, that gets stored with argument
values and it is generally named “argv”.
When command line arguments are passed, the first argument is program
name itself.
Ex:
int i;
clrscr();
for(i=0;i<argc;i++)
printf(“%s\n”, argv[i]);
Once this program is compiled, and the executable file is created, the
executable file is executed from command prompt by passing arguments along
with program name.
Ex:
C:\turboc3\bin\ myprogram Welcome To Command Line Arguments <ENTER>
Will display :
myprogram
Welcome
To
Command
Line
Arguments