BSC 2 Sem C Note 2023-24
BSC 2 Sem C Note 2023-24
MAJOR
I YEAR II SEMESTER
W.E.F. 2023-24
Course 1: Problem Solving using C
COURSE OBJECTIVES
1. To explore basic knowledge on computers
2. Learn how to solve common types of computing problems.
3. Learn to map problems to programming features of C.
4. Learn to write good portable C programs.
COURSE OUTCOMES
Upon successful completion of the course, a student will be able to:
1. Understand the working of a digital computer and Fundamental
constructs of Programming
2. Analyze and develop a solution to a given problem with suitable control
structures
3. Apply the derived data types in program solutions
4. Use the ‘C’ language constructs in the right way
5. Apply the Dynamic Memory Management for effective memory
utilization
UNIT-I
Introduction to computer and programming: Introduction, Block
diagram and functions of various components of computer, Concepts of
Hardware and software, Types of software, Compiler and interpreter,
Concepts of Machine level, Assembly level and high-level programming,
Flowcharts and Algorithms.
UNIT-II
Control statements: Decision making statements: if, if else, else if ladder,
switch statements. Loop control statements: while loop, for loop and do-
while loop. Jump Control statements: break, continue and goto.
UNIT-III
Derived data types in C: Arrays: One Dimensional arrays - Declaration,
Initialization and Memory representation; Two Dimensional arrays -
Declaration, Initialization and Memory representation.
UNIT-IV
Functions: Function Prototype, definition and calling, return statement,
categories of functions, recursion, parameter passing by address & by
value, local and global variables, storage classes.
UNIT-V
Structures: Basics of structure, structure members, accessing structure
members, nested structures, array of structures. Unions - Union
definition, declaration, initialization and accessing members; difference
between Structures and Unions.
●E. Balagurusamy, “Programming in ANSI C”, Tata McGraw Hill, 6th Edn,
ISBN-13: 978- 1-25- 90046-2.
●Herbert Schildt, ―Complete Reference with C, Tata McGraw Hill, 4th
Edn., ISBN- 13: 9780070411838, 2000.
●Computer fundamentals and programming in C, REEMA THAREJA,
OXFORD UNIVERSITY PRESS.
REFERENCE BOOKS
COMPUTER SCIENCE
List of Experiments
PART-A
Answer any FIVE of the following. Each Question Carries 5 marks.
(5X5=25)
1.
2.
3.
4.
5.
6.
7.
8.
PART-B
Answer any FIVE of the following. Each Question Carries 10 marks.
(5X10=50)
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
SRI VENKATESWARA UNIVERSITY::TIRUPATI
B.Sc. Computer Science Honours
I year II Semester
Course 4: Digital Logic Design
Theory Credits: 3 3 hrs/week
Course Objectives
● To familiarize with the concepts of designing digital circuits.
Course Outcomes
Upon successful completion of the course, the students will be able to
● Understand how to Convert numbers from one radix to another radix
and perform arithmetic operations.
● Simplify Boolean functions using Boolean algebra and k- maps
● Design adders and subtractors circuits
● Design combinational logic circuits such as decoders, encoders,
multiplexers and demultiplexers.
UNIT – I
Number Systems: Binary, octal, decimal, hexadecimal number
systems, conversion of numbers from one radix to another radix, r’s, (r-
1)’s complements, signed binary numbers, addition and subtraction of
unsigned and signed numbers, weighted and unweighted codes.
UNIT – II
Logic Gates and Boolean Algebra: NOT, AND, OR, universal
gates, X-OR and X-NOR gates, Boolean laws and theorems, complement
and dual of a logic function, canonical and standard forms, two level
realization of logic functions using universal gates, minimizations of
logic functions (POS and SOP) using Boolean theorems, K-map (up to
four variables), don’t care conditions.
UNIT – III
Combinational Logic Circuits – 1: Introduction, Analysis
Procedure, Design Procedure, Binary Adder-Subtractor-Design of
half adder, full adder, half subtractor, full subtractor, ripple adders and
subtractors(Binary adders/subtractors with carry Propagation ).
UNIT – IV
Combinational Logic Circuits – 2: Design of decoders, encoders,
priority encoder, multiplexers, demultiplexers.
UNIT – V
Sequential Logic Circuits: Classification of sequential circuits,
latch and flip-flop, RS- latch using NAND and NOR Gates, truth tables,
RS, JK, T and D flip-flops, truth and excitation tables.
Text Books:
1. M. Morris Mano, Michael D Ciletti, “Digital Design”, 5th edition, PEA.
Reference Books
1. Kohavi, Jha, “Switching and Finite Automata Theory”, 3rd edition,
Cambridge.
2. Leach, Malvino, Saha, “Digital Principles and Applications”, 7th
edition, TMH.
3. Roth, “Fundamentals of Logic Design”, 5th edition, Cengage.
SUGGESTED CO-CURRICULAR ACTIVITIES & EVALUATION METHODS:
List of Experiments
The laboratory work can be done by using physical gates and necessary
equipment or simulators.
Simulators: https://sourceforge.net/projects/gatesim/ or
https://circuitverse.org/ or any free open- source simulator
1. Introduction to digital electronics lab- nomenclature of digital ICs,
specifications, study of the data sheet, concept of Vcc and ground,
verification of the truth tables of logic gates using TTL ICs.
2. Implementation of the given Boolean functions using logic gates in both SOP
PART-A
PART-B
The above is
T i the blockk diagram of the com mputer thatt includes input
i unit,
output unit
u and a CPU C (Centtral Processsing Unit)). The CPUU includes the controol
unit, AL
LU and meemory unit.
C
Control Unit: It controols from where
w the data
d is to bee sent for processing
p and
how thee logic is to
o be implem mented andd to wheree the results is to be sent
s (in
memoryy)
Memory Un
M nit : it is ussed to storee data. Thee memory unit
u includdes primaryy
memoryy and secon
ndary mem mory.
The Primary memory includes RAM, ROM. The RAM (Random Access
Memory) is the main memory of the system and it is volatile and stores data
temporarily. The data used by the running application is held in the main memory
and once the application is terminated, the data of that application goes off this
memory.
The ROM (Read Only Memory), stored with the system software BIOS
(Basic Input Output System) that is used in POST (Power On Self Test) operation.
System Software
System software operates directly on hardware devices of computer. It provides a
platform to run an application. It provides and supports user functionality. System
software include BIOS, Drivers and operating systems such as Windows, Linux,
Unix, etc.
Application Software
An application software is designed for benefit of users to perform one or more
tasks. Examples of application software include Microsoft Word, Excel,
PowerPoint, Oracle, C, java etc.
---
Advantages of Algorithms:
x It is easy to understand.
x Algorithm is a step-wise representation of a solution to a given problem.
x 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:
Then the algorithm is written with the help of above parameters such that it
solves the problem.
Now let’s design the algorithm with the help of above pre-requisites:
Algorithm is complex to
2. understand. Flowchart is easy to understand.
Algorithm is difficult to
5. construct. Flowchart is simple to construct.
5) Rich Library : C provides a lot of inbuilt functions that make the development
fast.
7) Speed : The compilation and execution time of C language is fast since there are
lesser inbuilt functions and hence the lesser overhead.
8) Pointer: C provides the feature of pointers. We can directly interact with the
memory by using the pointers. We can use pointers for memory, structures,
functions, array, etc.
9) Recursion : In C, we can call the function within the function. It provides code
reusability for every function. Recursion enables us to use the approach of
backtracking.
10) Extensible : C language is extensible because it can easily adopt new features.
Structure of C Program :
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
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 can not 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:
x In C, identifier must have less than 8 characters (on unix it is < 8, but in
windows it can be up to 32 characters)
x Identifier must start with alphabet and can have numbers in between.
x No special symbol including space is permitted other than underscore
x Keywords are not permitted
x Duplicate names 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”.
Q. What are tokens of C
---
Operators in C- Programming Example:
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
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);
}
---
I/O Statements in 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);
unformatted IO functions :
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.
Switch-case statement
For decision making by comparing equality of values, the switch-case
statement can be used. The switch keyword takes a variable and under switch there
can be number of cases specified within a block.
The switch block executes from matching case till end of switch block. The
switch block can also have a “default” option, that executes if no matching case
exists.
switch(var)
{
case 1: statements;
case 2: statements;
………………….
………………….
case n: statements;
default : statements;
}
For controlled execution we may use the “break” keyword that break the
switch block and passes control to rest of program.
The switch case in C works with ASCII code. The “int” or “char” data
types can only be used in switch-case. The float , double cannot be used for
comparing. So in C, the switch supports 256 cases. Later in C++ it supports more
than 65000 cases.
In any case, the switch does not support duplicate cases written with in a
block.
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”);
}
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:
for(initialization ; condition ; counter)
Statement;
Nested loops
When a loop is placed with in another loop, it is called nested loops. The
inner loop executes no. of times for each run of outer loops. The count of total
number of executions of statements is equal to the number of executions of outer
loop multiplied by number of number of executions of inner loop.
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
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. here question may be framed on branching separately or on switch case
separately or on iteration separately or on break and continue statements each for 5
marks.
Or
There can be a question asking for controlling statements for 10 marks, then write
about branching and loops. (without switch-case, break, continue)
---
UNIT-III
Derived Data types : the data types that can be made as we needed from primitive (basic) data
types are called derived data types. Important among them are arrays, structures, unions.
Arrays Introduction –
The array means arranged things. It is a collection of similar type of elements that have
sequential memory. The term “data structure” is arranging data values in a specific order. There
are different types of data structures and array is linear data structure.
When a program needs to store large number of data elements of similar type, then
instead of using individual elements, the arrays can be preferred, and with arrays, data
manipulation becomes easy.
Declaration of Arrays –
In C-language, the [ ] symbol is used while declaring and manipulating the arrays. The [ ]
are used to specify no. of elements to be grouped while declaring.
Syntax : data_type array_name[ int size];
Ex: int a[5];
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.
Storing Values in Array & Accessing elements of the Array –
Arrays can be stored with values either by initializing or by taking input. The initializing
can be done in two ways.
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]);
we can access array elements by referring the index number as subscript within [ ] with array
name.
Ex:
for(i=0;i<5;i++)
printf(“%d”,&arr[i]);
Operations on Arrays :
There are different operations that can be performed with arrays like,
---
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.
In a 2-dimensional array the size of each dimension is specified with in a separate [ ].
Ex : int arr[2][3];
In the above 2-D array, the memory allocated is sequential as given below:
arr
Strings
String is sequence of characters. In C, the strings are managed with an array of char data
type.
Ex: char name[20];
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.
The C has a special format specifier %s to be used while reading or writing strings. The %s
won’t read spaces in a string. We can also specify the characters to be read as format specifier
instead of %s like “%[a-z]”. The ^ (caret) can be used to specify the character NOT to be read.
Many times programmers use “%[^\n’]” as format specifier to read all symbols spaces etc till
user hits ENTER.
For easy manipulation of strings, the string.h library has number of pre-defined functions like:
For character handling, the ctype.h library has number of pre-defined functions like:
islower(ch) : returns true if lowercase letter and false if not
isupper(ch) : returns true if upper case letter
tolower(ch) : converts into lowercase
toupper(ch) : converts into uppercase
isspace(ch) : returns true if it is a space
isalpha(ch) : returns true if it is alphabet
isdigit(ch) : returns if it is a digit
isalnum(ch) : returns true if it is either alphabet or a number
---
UNIT -IV
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
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.
Returning values:
The function definition after doing process can send values back from
called function into calling function with the “return” keyword. The values can be
returned for further use.
Î The return can return only one value at a time
Î The return is last statement to be executed in a function
Î A function can have only one return executed.
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;
}
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.
---
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>
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 5;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
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;
}
Depending on whether arguments are present or not and whether a value is returned or
not, functions are categorized into −
---
When the term memory is used in programming, it generally refers the RAM, the
main memory of the system. When the program is compiled, the compiler decides
how much memory is required for running that application. When the program
execution starts, the application gets reserved with some memory in RAM to have
its code loaded and memory allocated for the data members (variables).
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.
---
POINTERS: The Pointer is a special data type used to manipulate values by
holding address of the memory location. The pointer is declared with an
ASTERISK. The pointers can be used in two ways, either by allocating memory
dynamically to the pointer or by storing address of other static memory.
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;”
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.
Ex: int *p; p=NULL;
Q. Explain how to use pointers in C
---
The pointers can be used to point to large memory like arrays.
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.
x 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.
---
The functions when called, they can be passed either variables or addresses.
Based on what is passed, the function calls are classified into two types.
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);
---
UNIT-V
STRUCTURES:
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);
}
---
UNIONS:
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.
But there is a restriction on unions. As the members share same memory,
programmer can use only one member at a time. In above case, if a value stored
into member “x” as “a.x=5;”, then “a.y” cannot be used. And if a.y is stored with a
value, then a.x cannot be used. At a given time, user can use only one member of
the union variable.
Programmer has to apply his own logic while using unions like in below
example.
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.
** try applying common sense and identify differences between structures and
unions. There can be a question like differences between structures and unions.
---
ENUMERATED DATA TYPES
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);
}
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”);
}
---
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:
Read mode : “r”
Write mode : “w”
Append mode : “a”
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.
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 can be detected in two ways. Either by checking whether the character
read through pointer has EOF or with the function feof().
x ch=fgetc(fp);
if( ch==EOF)
exit(1);
OR
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. what are different file reading and file writing functions and explain with
example.
---
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