0% found this document useful (0 votes)
235 views44 pages

Popc Superimp

The document outlines the basic structure of a C program, which consists of six sections: Documentation, Preprocessor Section, Definition, Global Declaration, Main() Function, and Sub Programs. It also explains various data types in C, including Int, Char, Float, Double, and Void, along with rules for declaring variables and the usage of printf() and scanf() functions. Additionally, it describes input and output devices, defining a computer and its characteristics such as speed, accuracy, automation, diligence, and versatility.

Uploaded by

1hk24is073
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
235 views44 pages

Popc Superimp

The document outlines the basic structure of a C program, which consists of six sections: Documentation, Preprocessor Section, Definition, Global Declaration, Main() Function, and Sub Programs. It also explains various data types in C, including Int, Char, Float, Double, and Void, along with rules for declaring variables and the usage of printf() and scanf() functions. Additionally, it describes input and output devices, defining a computer and its characteristics such as speed, accuracy, automation, diligence, and versatility.

Uploaded by

1hk24is073
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Module - 1

1. With suitable example, explain the basic structure of C program?


Sol:- The basic structure of a C program is divided into 6 parts which makes it is easy to read, modify,
document, and understand in a particular format. C program must follow the below-mentioned
outline in order to successfully compile and execute. Debugging is easier in a well-structured C
program. Sections of the C Program

There are 6 basic sections responsible for the proper execution of a program.
Sections are mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs

1. Documentation
This section consists of the description of the program, the name of the program, and the creation
date and time of the program. It is specified at the start of the program in the form of comments.
Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
or
/*
description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the program and this will not
interfere with the given code. Basically, it gives an overview to the reader of the program.

2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the program.
Header files help us to access other’s improved code into our code. A copy of these multiple files
is inserted into our program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
3. Definition
Preprocessors are the programs that process our source code before the process of compilation.
There are multiple steps which are involved in the writing and execution of the program.
Preprocessor directives start with the ‘#’ symbol. The #define preprocessor is used to create a
constant throughout the program. Whenever this name is encountered by the compiler, it is
replaced by the actual piece of defined code.
Example:
#define long long ll

4. Global Declaration
The global declaration section contains global variables, function declaration, and static variables.
Variables and functions which are declared in this scope can be used anywhere in the program.
Example:
int num = 18;

5. Main() Function
Every C program must have a main function. The main() function of the program is written in this
section. Operations like declaration and execution are performed inside the curly braces of the
main program. The return type of the main() function can be int as well as void too. void() main
tells the compiler that the program will not return any value. The int main() tells the compiler that
the program will return an integer value.
Example:
void main()
or
int main()

6. Sub Programs
User-defined functions are called in this section of the program. The control of the program is
shifted to the called function whenever they are called from the main or outside the main()
function. These are specified as per the requirements of the programmer.
Example:
int sum(int x, int y)
{
return x+y;
}
2. What are the various datatypes available in C?
Sol:-
• The data type defines the type of data stored in a memory location.
• The data type determines how much memory should be allocated for a variable.
• The data types that can be manipulated by machine instructions are called “basic or primitive
data types‟.

Basic data types


• Int
• Char
• Float
• Double
• Void

1. Int:
• An int is a keyword which is used for defining integers in C language.
• Using int the programmer can inform the compiler that the data associated with this should be
treated as integer.
• Using ‘int’ compiler determines the size of the data (2 bytes) and reserve space in memory to
store the data.
• Integer data types namely:
1. short int 2. int 3.long int

Type Size
Short 2 bytes
Int 2 bytes
Long int 4 bytes

Ex: int a,b,c;

2. Float:
• A float is a keyword which is used to define floating point numbers in C language.
• The programmer can inform the compiler that the data associated with this keyword should be
treated as floating point number.
• The default precision of floating point number is 6 digits after dot(.).
Size of float
Size of float
16-bit Machine 4 bytes
32-bit Machine 8 bytes

Ex: float x,y,z;

3. Double:
• It is a keyword which is used to define long floating point numbers in C language.
The default precision of floating point number is 14 digits after dot(.).
Size of double
16-bit Machine 8 bytes
32-bit Machine 16 bytes

Ex: double p,q,r;

4. Char:
• It is a keyword which is used to define single character or a sequence of characters called String
in C language.
• Using this keyword, the compiler determines the size of the data and reserve space in memory to
store the data.
• Each character stored in the memory is associated with a unique value called an ASCII (American
Standards Code for Information Interchange).
Size of char Range of Unsigned char Range of Signed char
16/32-bit Machine 1 byte 0 to 255 -128 to +127

Ex: char ch; // ch variable stores a single character Ex: ch= „a‟;
char s[20]; // s variable stores a string(group of characters) Ex: s= “jitdvg”;

5. Void:
• It is an empty data type, since no value is associated with this data type.
• It does not occupy any space in the memory.
Size of void Range
16/32-bit Machine 0 No value

Ex: void main( )


{
}

3. What are variables? Explain the rules for declaring variables in C.


Sol:- A variable is defined as a meaningful name given to the data storage location in computer memory.
When using a variable, we actually refer to address of the memory where the data is stored. C language
supports two basic kinds of variables.

Rules for forming variable name


• It cannot include any special characters or punctuation marks (like #, $, ^, ?, ., etc) except the
underscore"_".
• There cannot be two successive underscores.
• Keywords cannot be used as identifiers
• The names are case sensitive. So, example, “FIRST” is different from “first” and “First”.
• It must begin with an alphabet or an underscore.
• It can be of any reasonable length. Though it should not contain more than 31 characters.

Valid variable Invalid variable

num2 $num1
_apple +add
a_2 199_space
#12

4. Explain printf(), scanf() functions with their syntax


Sol:-
• C language supports two formatting functions printf and scanf.
• printf is used to convert data stored in the program into a text stream for output to the monitor
and scanf is used to convert the text stream coming from the keyboard to data values and stores
them in program variables.

1. printf()
• The printf() function (stands for print formatting), is used to display information required by the
user and also prints the values of variables.
• For this, the printf() function takes data values, converts them to a text stream using formatting
specifications in the control string and passes the resulting text stream to standard output.
• Each data value to be formatted in the text stream is described using a separate conversion
specification in the control string.
• The specification in the control string describes data value’s type, size, specific format.

The syntax of printf function:


printf(“control string”, variable list);
• The function accepts two parameters- control string & variable list.
• The control string may also contain the text to be printed like instructions to the user, captions,
identifiers or any other text to make the output readable.
• In some printf statements there may be only a text string that has to be displayed on the screen.
• The control characters can also be included in the printf statement like \n, \t, \a, etc.
• The prototype of control string:
%[flags][width[[.precision][length modifier] type specifier
• Each control string must begin with a % sign. The % sign specifies how the next variable in the
list of variables has to be printed.

Guidelines/Rules for printf()


• A printf() always contains a string or format string in quotation marks.
• The control string may or may not be followed by some variables or expressions whose value
we want printed.
• Each value to be printed needs a ‘conversion specification’ like %d to hold its place in the control
string.
• This conversion specification describes the exact way the value is to be printed.
• When printf() is executed each conversion specification is replaced by the value of the
corresponding expression, then print according to the rules in specification.
• The symbols \n or \t in control string tell the machine to skip to new line or tab. It affects the
appearance of the output but not displayed as part of it.
• A word or blank space or punctuation symbols within the control string will print exactly as it
appears.

2. scanf()
• The scanf() function stands for scan formatting and is used to read formatted data from the
keyboard.
• The scanf() function takes a text stream from the keyboard, extracts and formats the data from
the stream according to a format control string and then stores the data in a specified program
variables.
Syntax of the scanf() function:
scanf ( “control string”, arg1, arg2, arg3,..... argn);

• Control string specifies the type and format of the data that has to be obtained from the
keyboard and stored in the memory locations pointed by arg1, arg2, ..., argn,i.e., arguments
are actually the variable addresses where each piece of data is to be stored.
• Prototype of the control string can be given as:
%[*][width][modifier] type
• Here the * is an optional argument which indicates that data should be read from the stream,
but ignored (not stored in memory location).

Rules to use a scanf function:


Rule 1: The scanf function works until:
o the maximum number of characters has been processed
o a white space character is encountered,
o or an error is detected.

Rule 2: Every variable that has to be processed must have a conversion specification associated
with it. Therefore, following scanf statement will generate an error as num3 has no conversion
specification associated with it.
scanf(“ %d %d”, &num1, &num2, &num3);

Rule 3: There must be a variable address for each conversion specification. Therefore following
scanf will generate an error as no variable address is given for the third conversion specification.
scanf(%d %d %d”, &num1, &num2);

Rule 4: An error will be generated if the format string is ended with the white space character.

Rule 5: The data entered by the user must match the character specified in the control string,
otherwise, an error will be generated and scanf will stop its processing.
For example, consider the following scanf of statement
scanf(“%d / %d”, &num1, &num2);
Here the slash in the constant string is neither a white space character nor a part of the conversion
specification, so the users must enter data of the form 21/46.

Rule 6: Input data values must be separated by spaces.


Rule 7: Any unread data value will be considered as a part of data input in the next call to the
scanf.

Rule 8: When the field width specifier is used, it should be large enough to contain the input data
size.

Examples of printf/scanf:
1. Code to input values in variables of different data types:
• int num;
scanf(“%d”,&num);

• float salary;
scanf(“%f”, &salary);

• char ch;
scanf(“%c”,&ch);

• char str[10];
scanf(“%s”, str);

2. Reading variables of different data types in one statement:


int num;
float fnum;
char ch;
char str[10];
scanf(“%d %f %c %s”, &num, &fnum, &ch, str);
5. Explain various input devices (or) list and explain two input – output devices
Sol:- An input device is used to feed data and instructions into the computer. In the absence of an
input device, a computer would have only been a display device.

Input Devices
Keyboard
With a keyboard, the user can type a document, use keystroke shortcuts, access menus, play games
and perform numerous other tasks. Most keyboards have between 80 and 110 keys which include:
Typing keys: These include the letters of the alphabet. The layout of the keyboard is known
as QWERTY for its first 6 letters.
Numeric keys: These include a set of keys, arranged in the same configuration found on calculators
to speed up data entry of numbers.
Function keys: These are used by applications and operating system to input specific commands. They
are often placed on the top of the keyboard in a single row.
Control keys: These keys provide cursor and screen control. It includes four directional arrow key.
Control keys also include Home, End, Insert, Delete, Page Up, Page Down, Control (Ctrl), Alternate
(Alt), Escape(Esc).
Special purpose keys: Keyboard also contains some special purpose keys such as Enter, Shift, Caps
Lock, Num Lock, Space bar, Tab, and Print screen.

Advantages: Easy to use and inexpensive.


Disadvantages:
• Keyboard cannot be used to draw figures.
• The process of moving the cursor to some other position is very slow.
Pointing Devices
1. MOUSE

The mouse is the key input device to be used in a graphical user interface (GUI). The users can use
mouse to handle the pointer easily on the screen to perform various functions like opening a
program or file. With mouse, the users no longer need to memorize commands, which was earlier
a necessity when working with text-based command line environment such as MS-DOS.

Advantages:
• Easy to use; Cheap; Can be used to quickly place the cursor anywhere on the screen;
• Helps to quickly and easily draw figures;
• Point and click capabilities makes it unnecessary to remember certain commands
Disadvantages:
• Needs extra desk space to be placed and moved easily.
• The ball in the mechanical mouse must be cleaned to remove dust from it

Output Devices
1. PROJECTOR:
A projector is a device which takes an image from a video source and projects it onto a screen or
other surface. These days, projectors are used for a wide range of applications varying from home
theater e systems to organizations for projecting information and presentations onto screens large
enough for rooms filled with people to see.

2. SPEAKERS :
Today all business and home users demand sound capabilities and thus different types of speakers
to enable users to enjoy music, movie, or a game and the voice will be spread through the entire
room. With good quality speakers, the voice will also be audible even to people sitting in another
or room or even to neighbors.
However, in case the user wants to enjoy loud music without disturbing the people around him,
he can use a headphone.
Another device called headset was developed to allow the users to talk and listen at the same
time, using the same device.
6. Define computer. Describe the characteristics of computer in detail.

Sol:- A computer is an electronic device that processes data and performs tasks based on instructions
given by a user or a program. It can store, retrieve, and process information quickly and accurately.
Computers are used for various purposes, including calculations, communication, entertainment,
and automation.

Speed: Computers can perform millions of operations per second. The speed of computers is usually
given in nanoseconds and picoseconds, where 1 nanosecond = 1 × 10 −9 seconds and 1 picosecond
= 1 × 10 −12 seconds.

Accuracy: A computer is a very fast, reliable, and robust electronic device. It always gives accurate
results, provided the correct data and set of instructions are input to it.

Automation: Besides being very fast and accurate, computers are automatable devices that can
perform a task without any user intervention.

Diligence: Unlike humans, computers never get tired of a repetitive task. It can continually work for
hours without creating errors.
Versatile: Versatility is the quality of being flexible. Today, computers are used in our daily life in
different fields. For example, they are used as personal computers (PCs) for home use, for business-
oriented tasks, weather forecasting, space exploration, teaching, railways, banking, medicine, and
so on,

Memory: Similar to humans, computers also have memory. Just the way we cannot store everything
in our memory and need secondary media, such as a notebook, to record certain important things,
computers also have internal or primary memory (storage space) as well as external or secondary
memory.

No IQ: Although the trend today is to make computers intelligent by inducing artificial intelligence
(AI) in them, they still do not have any decision-making abilities of their own. They need guidance to
perform various tasks.

Economical: Today, computers are considered as short-term investments for achieving long-term
gains. computers also reduces manpower requirements and leads to an elegant and efficient way of
performing various tasks.
Module - 2
1. Differentiate and illustrate use of break and continue statements in loops
Sol:- Break Statement:
• The break statement is used to terminate the execution of the nearest enclosing
loop in which it appears.
• When compiler encounters a break statement, the control passes to the statement
that follows the loop in which the break statement appears.
• Its syntax is quite simple, just type keyword break followed with a semi-colon.
break;
In switch statement if the break statement is missing then every case from the matched
case label to the end of the switch, including the default, is executed.

Continue Statement:
• The continue statement can only appear in the body of a loop.
• When the compiler encounters a continue statement then the rest of the
statements in the loop are skipped and the control is unconditionally transferred
to the loop-continuation portion of the nearest enclosing loop.
• Its syntax is quite simple, just type keyword continue followed with a semi-colon.
continue;
• If placed within a for loop, the continue statement causes a branch to the code
that updates the loop variable.
• For example,
2. Differentiate between type conversion and type casting in C
Sol:-
• The process of converting the data or variable from one data type to another data type is called
Type Conversion or Typecasting.
• Type conversion is done implicitly by the compiler, whereas typecasting has to be done
explicitly by the programmer.

Type Conversion
• Type conversion is done when the expression has variables of different data types.
• To evaluate the expression, the data type is promoted from lower to higher level where the
hierarchy of data types (from higher to lower level) can be given as: double, float, long, int,
short and char.
• char → short int → int→ unsigned int → long int → float → double Lower Rank → double
Higher Rank
• C compiler converts the data type with lower rank to the data type with higher rank. This
process of conversion of data from lower rank to higher rank automatically by the C compiler
is called “Implicit type Conversion”.

• If one operand type is same as that of other operand type, no conversion takes place.
Ex: int + int = int, float + float = float
• If one operand type is ‘int’ and other operand type is ‘float’, then the operand with type int is
promoted to ‘float’ (because float is up in ladder compared with int).
• Type conversion is automatically done when we assign an integer value to floating point
variable. Consider the code given below in which an integer data type is promoted to float. This
is known as promotion (where the lower level data type is promoted to higher type).
float x;
int y=3;
x=y;
Now, x=3.0, as automatically integer value is converted into its equivalent floating point
representation.
Typecasting
• Typecasting is also known as forced conversion.
• It is done when the value of a higher data type has to be converted into a value of a lower data
type.
• But this casting is done under the programmer’s control and not under the compiler’s control.
• The programmer can instruct the compiler to change the type of the operand or variable from
one data type to another data type. This forcible conversion from one data type to another
data type is called “Explicit type Conversion” (Type Casting).

Ex: (int) 9.43


i= (int) 5.99 / (int) 2.4, now it becomes 5/2 = 2, i=2
(float) (3/10) = 3.0 / 10.0 = 0.3

3. Write a C program to check whether the given number is a palindrome or not.


Sol:- #include <stdio.h>
int main() {
int n,r,s=0,x;
scanf("%d",&n);
x=n;
while(x!=0)
{
r=x%10;
s=s*10+r;
x/=10;
}
printf("Reverse of the number is %d",s);
if(s==n)
printf("\nNumber is a palindrome");
else
printf("\nNumber is not a palindrome");
return 0;
}
4. Explain the concept of nested loops with suitable program
Sol:- C allows its users to have nested loops, i.e., loops that can be placed inside other loops. Although
this feature will work with any loop such as while, do-while, and for, it is most commonly used
with the for loop, because this is easiest to control. A for loop can be used to control the number
of times that a particular set of statements will be executed. Another outer loop could be used to
control the number of times that a whole loop is repeated.

Syntax
The syntax for a nested for loop statement in C is as follows: −
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{
statement(s);
}
statement(s);
}

Programs to print triangles using *, numbers and characters


*
**
***
****
*****

#include <stdio.h>
void main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
}

5. Write a C program to compute the roots of a quadratic equation by accepting the coefficient
print messages.
Sol:- #include <stdio.h>
#include <math.h>

int main() {
float a, b, c, discriminant, root1, root2, realPart, imagPart;

// Taking input for coefficients


printf("Enter coefficients a, b, and c: ");
scanf("%f %f %f", &a, &b, &c);

// Checking if 'a' is zero


if (a == 0) {
printf("Invalid input! 'a' cannot be zero for a quadratic equation.\n");
return 1;
}

// Calculating the discriminant


discriminant = b * b - 4 * a * c;

// Checking for nature of roots


if (discriminant > 0) {
// Real and distinct roots
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("The roots are real and distinct: %.2f and %.2f\n", root1, root2);
}
else if (discriminant == 0) {
// Real and equal roots
root1 = -b / (2 * a);
printf("The roots are real and equal: %.2f\n", root1);
}
else {
// Complex roots
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("The roots are complex and conjugate: %.2f + %.2fi and %.2f - %.2fi\n", realPart,
imagPart, realPart, imagPart);
}

return 0;
}

6. Explain switch statement with syntax. Write a C program to simulate calculator.

Sol:- The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute
multiple operations for the different possibles values of a single variable called switch
variable.Here, We can define various statements in the multiple cases for the different values of
a single variable.

Syntax:

switch(expression){

case value1:

//code to be executed;

break; //optional

case value2:

//code to be executed;

break; //optional

......

default:

code to be executed if all cases are not matched;

}
Example :

#include<stdio.h>

#include<stdlib.h>

int main()

int a, b, res; char op;

printf("Enter a simple arithmetic expression:\n");

scanf("%d%c%d",&a,&op,&b);

switch(op)

case '+':res=a+b;

break;

case '-':res=a-b;

break;

case '*':res=a*b;

break;

case '/':if(b!=0)

res=a/b;

else

printf("division by zero is not possible\n");

exit(0);

break;

case '%':res=a%b;
break;

default:printf("Illigal operator\n");

exit(0);

printf("\nResult=%d”,res);

return 0;

}
Module - 3
1. Write a C program to swap two numbers using call by reference
Sol:- /* Program to swap 2 number using pass by reference */
#include<stdio.h>
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int a,b;
printf(“Enter the values of a and b:”);
scanf(“%d%d”,&a,&b);
printf(“Before swapping: a=%d\tb=%d”, a, b);
swap(&a,&b);
printf(“After swapping: a=%d\tb=%d”, a, b)
}

2. Discuss the applications of multidimensional arrays in C programming


Sol:- Multi-Dimensional Arrays
• A multi-dimensional array in simple terms is an array of arrays.
• As we have one index in a one-dimensional array, two indices in a two-dimensional array, in the
same way, we have n indices in an n-dimensional array or multi-dimensional array.
• Conversely, an n–dimensional array is specified using n indices.
• An n-dimensional m1 × m2 ×m3 × ... × mn array is a collection of m1 × m2 × m3 × ...× mn
elements. In a multi-dimensional array, a particular element is specified by using n subscripts
as A[I1][I2][I3]...[In],
Applications of Arrays
• Arrays are frequently used in C, as they have a number of useful applications. These
applications are
• Arrays are widely used to implement mathematical vectors, matrices, and other kinds of
rectangular tables.
• Many databases include one-dimensional arrays whose elements are records.
• Arrays are also used to implement other data structures such as strings, stacks, queues, heaps,
and hash tables.
• Arrays can be used for sorting elements in ascending or descending order.

3. Explain declaration and initialization of one-dimensional and two-dimensional arrays with


example.
Sol:-
• An array is a collection of similar data elements.
• These data elements have the same data type.
• The elements of the array are stored in consecutive memory locations and are referenced by
an index (also known as the subscript).
• Declaring an array means specifying three things:
The data type- what kind of values it can store ex, int, char, float
Name- to identify the array
The size- the maximum number of values that the array can hold
• Arrays are declared using the following syntax.
type name[size];

Initialization of Arrays
Arrays are initialized by writing,
type array_name[size]={list of values};
int marks[5]={90, 82, 78, 95, 88};

Example Program:
#include<stdio.h>
void main()
{
int i=0, n, arr[20];
clrscr();
printf(“\n Enter the number of elements : “);
scanf(“%d”, &n);
for(i=0;i<n;i++)
{
printf(“\n Arr[%d] = “, i);
scanf(“%d”,&num[i]);
}
printf(“\n The array elements are “);
for(i=0;i<n;i++)
printf(“Arr[%d] = %d\t”, i, arr[i]);
}

A two dimensional array is specified using two subscripts where one subscript denotes row and
the other denotes column. C looks a two dimensional array as an array of a one dimensional array.
A two dimensional array is declared as:
data_type array_name[row_size][column_size];
Therefore, a two dimensional mXn array is an array that contains m * n data elements and
each element is accessed using two subscripts, i and j where i<=m and j<=n.

There are two ways of storing a 2-D array can be stored in memory. The first way is row major
order and the second is column major order.

Initialization:
A two dimensional array is initialized in the same was as a single dimensional array is
initialized.
data_type array_name[row_size][column_size]= {Values};

For example,
int marks[2][3]={90, 87, 78, 68, 62, 71};
int marks[2][3]={{90,87,78},{68, 62, 71}};

4. Describe different type of storage classes with example


Sol:- Storage Classes
• Storage class defines the scope (visibility) and lifetime of variables and/or functions declared
within a C program.
• In addition to this, the storage class gives the following information about the variable or the
function.
➢ The storage class of a function or a variable determines the part of memory where storage
space will be allocated for that variable or function (whether the variable function will be
stored in a register or in RAM).
➢ It specifies how long the storage allocation will continue to exist for that function or
variable.
➢ It specifies the scope of the variable or function.
➢ It specifies whether the variable or function has internal, external, or no linkage.
➢ It specifies whether the variable will be automatically initialized to zero or to any
indeterminate value.
• C supports four storage classes: automatic, register, external, and static.
• The general syntax for specifying the storage class of a variable can be given as:
<storage_class_specifier> <data type > <variable name>

Auto Storage Class


• The auto storage class specifier is used to explicitly declare a variable with automatic storage.
• It is the default storage class for variables declared inside a block.
• For example, if we write
auto int x;
then x is an integer that has automatic storage. It is deleted when the block in which x is
declared is exited.
• The auto storage doss can be used to declare variables in a block or the names of function
parameters.
• Important things to remember about the variables declared with auto storage class are as
follows :
➢ All the variables declared within a function belong to automatic storage class by default.
➢ They should be declared at the start of the program block, right after the opening curly
brackets {.
➢ Memory for the variable is automatically allocated upon entry to a block and freed
automatically upon exit from that block.
➢ The scope of the variable is local to the block in which it is declared.
➢ Every time the block is entered, the variable is initialized with the values declared.
➢ The auto variables are stored in the primary memory of the computer.
➢ If auto variables are not initialized at the time of declaration, then they contain some
garbage value.
Register Storage Class
• When a variable is declared using register as its storage class, it is stored in a CPU register
instead of RAM.
• Since the variable is stored in a register, the maximum size of the variable is equal to the register
size.
• A register variable is declared in the following manner:
register int x;
• Register variables are used when quick access to the variable is needed.
• Each time the block is entered, the register variables defined in that block are accessible and
the moment that block is exited, the variables become no longer accessible for use.

Extern Storage Class


• The extern storage class is used to give a reference of a global variable that is visible to all the
program files.
• Such global variables are declared like any other variables in one of the program files. .
• To declare a variable x as extern write,
extern int x;
• External variables may be declared outside any function source code file as any other variable
is declared.
• Usually external variables are declared and defined in the beginning of a source file.
• Memory is allocated for the external variables when the program begins execution and remains
allocated until the program terminates.
• In case if the external variable is not initialized, then it will be initialized to zero by default.
• External variables have global scope, i.e. these variables are visible and accessible from all the
functions in the program.

Static Storage Class


• Static is the default storage class for all global variables.
• Static variables have a lifetime over the entire program. i.e., memory for the static variables is
allocated when the program begins running and is freed when the program terminates.
• To declare an integer x as static, write
static int x = 10;
Here x is a local static variable.
• Static local variables when defined within a function are initialized at the runtime.
• The static variables are initialized just once, when defined within a function it is not re-initialized
when the function is called again and again.
• When a static variable is not explici1ly initialized by the programmer, then it is automa1ically
initialized to zero when memory is allocated for it

5. Write a C program to transpose a MxN matrix in C.


Sol:-
#include<stdio.h>
#include<conio.h>
void main() {
Int a[3][2],b[2][3],i,j;
clrscr();
printf(“Enter values of matrix:”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf(“%d”,&a[i][j]);
}
printf(“Matrix:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
printf(“%d”,a[i][j]);
printf(“\n”);
}
for(i=0;i<3;i++)
{
b[j][i]=a[i][j];
}
printf(“Transpose matrix:\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf(“%d”,b[i][j]);
printf(“\n”);
}
getch();
}
Output:
Enter values of the matrix: 4
5
6
1
2
3
Matrix:
45
61
23
Transpose matrix:
462
513

6. Write a C program to transpose a 3x3 matrix in C.


Sol:-
#include <stdio.h>
void main()
{
int i, j, mat[3][3], transposed_mat[3][3];
printf("\n Enter the elements of the matrix ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d", &mat[i][j]);
}
}
printf("\n The elements of the matrix are ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t", mat[i][j]);
}
printf("\n");
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
transposed_mat[i][j] = mat[j][i];
}
printf("\n The elements of the transposed matrix are ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",transposed_ mat[i][j]);
}
printf("\n");
}
}

Output
Enter the elements of the matrix
123456789
The elements of the matrix are
123
456
789
The elements of the transposed matrix are
147
258
369
7. Explain the syntax of function declaration and function definition with example.

Sol:- Function Declaration/Function Prototype

• Before using a function, the compiler must know the number of parameters and the type of
parameters that the function expects to receive and the data type of value that it will return to
the calling program.
• Placing the function declaration statement prior to its use enables the compiler to make a check
on the arguments used while calling that function.
• The general format for declaring a function that accepts arguments and returns a value as result
can be given as:

return_data_type function_name(data_type variable1, data_type variable2,..);

Here, function_name is a valid name for the function. A function should have a meaningful name that
must specify the task that the function will perform.

return_data_type specifies the data type of the value that will be returned to the calling function as
a result of the processing performed by the called function.

(data_type variable1, data_type variable2, ...) is a list of variables of specified data types. These
variables are passed from the calling function to the called function. They are also known as
arguments or parameters that the called function accepts to perform its task.

Ex: int add(int a,int b);

• Things to remember about function declaration:


➢ After the declaration of every function, there should be a semicolon. If the semicolon is
missing, the compiler will generate an error message.
➢ The function declaration is global.
➢ Use of argument name in the function declaration is optional.
int func(int, char, float);
or
int func(int num, char ch, float fnum);
➢ A function cannot be declared within the body of another function.
➢ A function having void as its return type cannot return any value.
➢ A function having void as its parameter list cannot accept any value. So the function
declared as void print(); does not accept any input/arguments from the calling function .
➢ If the function declaration does not specify any return type, then by default, the function
returns an integer value. Therefore, when a function is declared as sum(int a, int b);
Then the function sum accepts two integer values from the calling function and in sum returns
an integer value to the caller.

➢ Some compilers make it compulsory to declare the function before its usage while other
compilers make it optional.

Function Definition

• When a function is defined, space is allocated for that function in the memory.
• A function definition comprises of two parts:
➢ Function header
➢ Function body
• The syntax of a function definition can be given as:

return_data_type function_name(data_type variable1, data_type variable2,..)

.............

statements

.............

return(variable);

• The number of arguments and the order of arguments in the function header must be the same
as that given in the function declaration statement.
• While return_data_type function_name(data_type variable1, data_type variable2,...) is known
as the function header, the rest of the portion comprising of program statements within the
curly brackets { } is the function body which contains the code to perform the specific task.
• Note that the function header is same as the function declaration. The only difference between
the two is that a function header is not followed by a semi-colon.

Ex: int add(int a,int b)

int sum;

sum=a+b;

return sum; }
Module - 4
1. Define pointer. Explain the declaration of a pointer variable with an example.
Sol:- Pointer
• A pointer is a variable that holds the address of another variable”. Or
• A pointer is a variable that contains the memory location of another variable. Therefore, a
pointer is a variable that represents the location of a data item, such as a variable or an array
element.

Declaring Pointer Variables


• Pointer provides access to a variable by using the address of that variable.
• A pointer variable is therefore a variable that stores the address of another variable.
• The general syntax of declaring pointer variables can be given as below.
data_type *ptr_name;
Here, data_type: is the data type of the value that the pointer will point to. It can be int, float,
char etc.
Asterisk (*): It tells the compiler that we are declaring a pointer variable.
pointer_variable_name: It is the name of the pointer variable.

Example:
1. int *ptr; // declares a pointer variable ptr of integer type.
2. float *temp; // declares a pointer variable temp of floating type.

2. Define a string. List the string manipulation functions. Explain any two with examples.
Sol:- String
• A string is a sequence of characters enclosed within double quotes”. Or
• “String is an array of characters and terminated by NULL character which is denoted by ‘\0’.
• In C, 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.

String manipulation functions


The standard library ‘string.h’ contains many functions for the string manipulation.
1. strlen(str): The length of a string
2. strcpy ( ): String Copy
3. strncpy(str1,str2,n): String Number Copy
4. strcat(str1,str2): String Concatenate(Joining two strings together)
5. strncat(str1,str2,n)- String Number Concatenate
6. strcmp(str1,str22): String Compare
7. strncmp(str1,str2,n): String Number Compare
8. strchr()
9. strrchr()
10. strspn()
11. strcspn()
12. strpbrk()
13. strtok()

1. strlen(str): The length of a string


• The ‘strlen()’ function can be used to find the length of the string in bytes.
• This function calculates the length of the string excluding the ‘null character’. i.e., the function
returns the number of characters in the string.
Syntax: size_t strlen(const char *str );

Ex: Write a C program to demonstrate the usage of strlen().


#include<stdio.h>
#include<string.h>
void main()
{
char str[] =“HELLO WORLD!”;
printf(“\n The length of the string is: %d”, strlen(str));
}
Output:
The length of the string is: 5

2. strcpy ( ): String Copy


• The ‘strcpy()’ function copies the contents of source string str2 to destination string str1
including ‘\0’.
• The strcpy() function copies characters from the source string to the destination string until it
finds null character. It returns the argument str1.
Syntax: char * strcpy(char *str1, const char *str2);
Where,
str1: it is the destination string
str2: it is the source string.

Ex: Write a C program to demonstrate the usage of strcpy().


#include<stdio.h>
#include<string.h>
void main()
{
char str1[10], str2[10]= “JAIN”;
strcpy(str1,str2);
printf(“The Source String=%s\n The Destination String=%s”, str1,str2);
}
Output:
The Source String= JAIN
The Destination String= JAIN

3. Write a C program using pointers to compute the sum, mean, and standard deviation of all
elements stored in an array.
Sol:- /* Program to find sum, mean, and Standard Deviation using pointer */
#include<stdio.h>
#include<math.h>
void main()
{
float a[10],*ptr,mean,std,sum=0,sumstd=0;
int n,i;
printf("Enter the no of elements n =");
scanf("%d",&n);
printf(" Enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+ *ptr;
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0;i<n;i++)
{
sumstd=sumstd+ pow((*ptr-mean),2);
ptr++;
}
std=sqrt(sumstd/n);
printf("Sum=%.3f\t",sum);
printf("Mean=%.3f\t",mean);
printf("Standard Deviation=%.3f\n",std);
}

4. Explain how strings are represented in memory, providing suitable examples.


Sol:- Strings are objects representing a sequence of character values. An array of characters works
the same as a string. So, a string is an array of characters or an object used to represent a sequence
of characters. A string is referred to as using a character pointer or a character array.

Storing Strings as Character Arrays


The strings declared as character arrays are stored like other arrays in C. For example, if str[] is an
auto variable, the string is stored in the stack segment; if it’s a global or static variable, then stored
in the data segment.

Strings as character arrays can be stored in two ways:


char str[6] = "Ninja"; /*One extra for string terminator*/
char str[6] = {‘N‘,‘i’, ‘n’, ‘j‘, ‘a‘, '\0'}; /* '\0' is string terminator */

Storing Strings as Character Pointers


Strings can be stored using character pointers in two ways:
Read-only string in a shared segment.
The directly assigned string values to a pointer are stored in a read-only block shared among
functions in most compilers.
char *str = "Ninja";
The word “Ninja” is stored in a shared read-only location while the pointer str is stored in read-write
memory. The pointer str can be changed to point to something else, but it cannot change the value
at the present str. So this kind of string should be used only when the string is not modified at a later
stage in the program.

Dynamically allocated in the heap segment.


Strings are stored like other dynamically allocated things in C and
shared among functions.
char *str;
int size = 6; /*one extra for ‘\0’*/
str = (char *)malloc(sizeof(char)*size);
*(str+0) = 'N';
*(str+1) = 'i';
*(str+2) = 'n';
*(str+3) = 'j';
*(str+4) = 'a';
*(str+5) = '\0';

Example (modify a string)


int main()
{
char str[] = "Ninja";
*(str+1) = 'n';
getchar();
return 0;
}

5. Explain gets() and puts() function with example.


Sol:- The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in the
input/output operations of the strings.

C gets() function
The gets() function enables the user to enter some characters followed by the enter key. All the
characters entered by the user get stored in a
character array. The null character is added to the array to make it a string. The gets() allows the
user to enter the space-separated strings. It returns the string entered by the user.

Declaration
char[] gets(char[]);

Reading string using gets()


#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
Output
Enter the string?
How are you doing?
You entered How are you doing?

C puts() function
The puts() function is used to print the string on the console which is previously read by using gets()
or scanf() function. The puts() function returns an integer value representing the number of
characters being printed on the console. Since, it prints an additional newline character with the
string, which moves the cursor to the new line on the console, the integer value returned by puts()
will always be equal to the number of characters present in the string plus 1.

Declaration:
int puts(char[])

Example:
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
Output:
Enter your name: chaitanya
Your name is: Chaitanya

Module - 5
1. Define structures in C. explain their declaration with an example program and their use.
Sol:- Structure
• Structure is basically a user-defined data type that can store related information (even of
different data types) together.
• The major difference between a structure and an array is that an array can store only
information of same data type.
• A structure is a collection of variables under a single name. The variables within a structure are
of different data types and each has a name that is used to select it from the structure.
• “A Structure is a user defined data type, which is used to store the values of different data types
together under the same name”.

Structure Declaration
• A structure is declared using the keyword struct followed by the structure name.
• All the variables of the structure are declared within the structure.
• A structure type is generally declared by using the following syntax:
struct struct–name
{
data_type var–name;
data_type var–name;
...............
};

For example:
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};

• A variable of structure student can be defined by writing:


struct student stud1;
struct student is a data type and stud1 is a variable.
• In the following syntax, the variables are declared at the time of structure declaration.
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
} stud1, stud2;
stud1 and stud2 of the structure student.

2. Differentiate between structures and unions, with examples for each in C.


Sol:-
Syntax
The syntax of structures in C language is,
struct structure_name {
member definition;
} structure_variables;
Where,
• structure_name is the name given to the structure.
• member definition is the set of member variables.
• structure_variable is the object of structure.

Example
struct Data {
int a;
long int b;
} data, data1;

Syntax
The syntax of unions in C language is,
union union_name {
member definition;
} union_variables;
Where,
• union_name is any name given to the union.
• member definition is the set of member variables.
• union_variable is the object of union.

Example
union Data {
int i;
float f;
} data, data1;

3. Write a C program to read from a file and display its contents on the console.
Sol:-
#include<stdio.h>
#include<stdlib.h>
int main()
{
char ch, source_file[25], target_file[25];
FILE *source, *target;
printf("Enter name of file to copy\n");
gets(source_file);
source = fopen(source_file, "r");
if( source == NULL )
{
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
printf("Enter name of target file\n");
gets(target_file);
target = fopen(target_file, "w");
if( target == NULL )
{
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(source) ) != EOF )
fputc(ch, target);
printf("File copied successfully.\n");
fclose(source);
fclose(target);
return 0;
}

4. Define enumerated data types, explain their declaration and access of enumerated datatypes
with a code in C
Sol:- Enumerated data types
• The enumerated data type is a user defined type based on the standard integer type.
• An enumeration consists of a set of named integer constants. That is, in an enumerated type,
each integer value is assigned an identifier. This identifier (also known as an enumeration
constant) can be used as symbolic names to make the program more readable.
• To define enumerated data types, enum keyword is used.
• Enumerations create new data types to contain values that are not limited to the values
fundamental data types may take. The syntax of creating an enumerated data type can be given
as below.
enum enumeration_name{ identifier1, identifier2, ......, identifier n };
Enum declaration
• The syntax for declaring a variable of an enumerated data type can be given as,
enum enumeration_name variable_name;

C Program to Demonstrate Enumerated Data Types:


#include <stdio.h>

// Declaration of an enumerated data type


enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY};

int main() {
enum Day today;
today = WEDNESDAY;

// Printing the integer value of enumeration


printf("Numerical Value of WEDNESDAY: %d\\n", today);

// Using enumeration in a switch case


switch (today) {
case SUNDAY:
printf("It's a relaxing day!\\n");
break;
case MONDAY:
printf("Start of the workweek.\\n");
break;
case TUESDAY:
printf("Second day of work.\\n");
break;
case WEDNESDAY:
printf("Midweek day.\\n");
break;
case THURSDAY:
printf("Almost weekend!\\n");
break;
case FRIDAY:
printf("Weekend is near!\\n");
break;
case SATURDAY:
printf("Weekend time!\\n");
break;
default:
printf("Invalid day.\\n");
}

return 0;
}

5. Explain the process of opening a file.


Sol:- Opening a File
• A file must be first opened before data can be read from it or written to it.
• In order to open a file and associate it with a stream, the fopen() function is used.
• The prototype of fopen() can be given as:
FILE *fopen(const char *file_name, const char *mode);
• Using the above prototype, the file whose pathname is the string pointed to by file_name is
opened in the mode specified using the mode.
• If successful, fopen() returns a pointer-to-structure and if it fails, it returns NULL.

File Name
• Every file on the disk has a name associated with it.
• In DOS the file name can have one to eight characters optionally followed by a period and an
extension that has one to three characters.
• Windows and UNIX permit filenames having maximum of 256 characters.
• In C, fopen() may contain the path information instead of specifying the filename. The path
gives information about the location of the file on the disk.

File Mode
• Mode conveys to C the type of processing that will be done with the file.
• The different modes in which a file can be opened for processing are given in Table below:
• The fopen() can fail to open the specified file under certain conditions that are listed below:

➢ Opening a file that is not ready for usage.


➢ Opening a file that is specified to be on a non-existent directory/drive.
➢ Opening a non-existent file for reading.
➢ Opening a file to which access is not permitted.

Ex:
FILE *fp;
fp = fopen("Student.DAT", "r");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
OR
char filename[30];
FILE *fp;
gets(filename);
fp = fopen(filename, "r+");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}

6. Explain the process of detecting the end of the file


Sol:- The function feof() is used to check the end of file after EOF. It tests the end of file indicator. It
returns non-zero value if successful otherwise, zero.
Here is the syntax of feof() in C language,
int feof(FILE *stream)

Here is an example of feof() in C language,


Let’s say we have "new.txt" file with the following content −
This is demo!
This is demo!
Now, let us see the example.

Example
#include <stdio.h>
int main()
{
FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
putchar(c);
c = getc(f);
}
if (feof(f))
printf("
Reached to the end of file.");
else
printf("
Failure.");
fclose(f);
getchar();
return 0;
}

Output
This is demo!
This is demo!
Reached to the end of file.

You might also like