Popc Superimp
Popc Superimp
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‟.
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
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
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
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
num2 $num1
_apple +add
a_2 199_space
#12
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.
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).
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 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);
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.
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).
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);
}
#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;
return 0;
}
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:
}
Example :
#include<stdio.h>
#include<stdlib.h>
int main()
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
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)
}
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}};
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.
• 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:
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.
➢ 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:
.............
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.
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.
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.
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);
}
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[]);
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;
};
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;
int main() {
enum Day today;
today = WEDNESDAY;
return 0;
}
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:
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);
}
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.