1 List and Describe Various Parts of Computer Hardware. Ans
1 List and Describe Various Parts of Computer Hardware. Ans
Motherboards
The motherboard is the component that unifies the internal hardware. You will need to
ensure that the processor, memory, and other computer parts are compatible with the
motherboard.
Though the motherboard can affect system performance, it can be difficult to quantify
how much of an impact it has. Several important considerations include, the maximum
amount of memory supported, compatible processors, data interface standards, and
expansion card slots.
Computer Cases
There are many different types of computer cases, from small portable ITX cases to
larger E-ATX cases for servers and workstations.
When selecting a case, you should consider how and where the computer will be used.
Also, determine if the case’s internal dimensions are adequate for the components that
you plan to use.
Power Supply Unit (PSU) or SMPS
Computer power supplies are components that connect to an electrical outlet and send
power to the individual computer parts. When selecting a power supply, you will need
to determine if can handle the total power requirement of all the components.
To do that, add up the power loads of all the internal components and ensure that the
PSU can supply at least that much power. It is recommended that you choose a power
supply well above that minimum for more flexibility.
Hard Drives
The hard drive is a data storage device that can be used to store the operating system,
programs, documents, and other important files. When selecting a hard drive, ensure
that it is compatible with the motherboard as well as being large and quick enough for
your needs.
Alternatively, you can use a solid state drive for increased data transfer speeds, lower
noise output, and better energy efficiency.
Video Cards
A video card is a required component, but many motherboards already have one built-
in. However, some tasks may require the use of a dedicated video card even if the
motherboard has onboard video capabilities. Tasks such as 3D rendering and simulation
can sometimes require the use of workstation-grade video cards.
Network Adapters
While not required for the computer to be used, network connectivity is necessary for
internet and local area network (LAN) access. Some motherboards have network
adapters built into them, so separate adapters are not always required.
There are two main types of network adapters, internal and external. Internal network
adapters utilize expansion slots while external variants are usually USB.
Sound Cards
Many desktop motherboards have sound cards built-in, allowing for audio playback
without the need for a dedicated sound card. However, the quality of these built-in
sound cards is generally not on par with high-end dedicated sound cards. For tasks that
require high definition audio playback, dedicated sound cards are usually better than
onboard solutions.
Optical Drives
An optical drive is beneficial for many uses, including backing up data, installing
software, and playing multimedia content. Before shopping for an optical drive however,
you should check what type of data connector the motherboard utilizes and if any are
available for use.
Typically, there are two major classifications of software, namely System Software and
Application Software.
Definition:
1. System Software can be designed as the software in such a way so that it can control and
work with computer hardware. It acts as an interface between the device and the end user.
It also provides the platform for the running of other software
Examples of System software are:
i) Operating systems
ii) Device Drivers
iii) Language compilers and interpreters
i) Operating systems:
Basically, the OS coordinates the different hardware components of a computer.
It performs operations like process management, memory management, I/O
management etc.
There are many OS in the market. There are several operating systems are available.
Ex: Windows, Linux, Unix, Xenix, MacOS, Android etc.
General purpose software is purchased from a software developer and can be used
for more than one application.
Examples of general purpose software include word processors, database
management systems ,and computer aided design systems. They are labeled general
purpose because they can solve a variety of user computing problems.
Application–specific software can be used only for its intended purpose. A general
ledger system used by accountants and a material requirements planning system
used by a manufacturing organization are examples of application-specific software.
They can be used only for the task for which they were designed they cannot be used
for other generalized tasks.
Definition:
An algorithm is a finite set of instructions to accomplish a particular task in a given
problem. In other words, it is a step by step procedure to solve a problem. There are
time and space complexity associated with each algorithm.
Time complexity specifies the amount of time required by an algorithm to perform a
desired task.
The space complexity specifies the amount of memory space required by the
algorithm to perform the desired task.
Important criteria for algorithms are as follows: (Characteristics of Algorithms)
1. Input
2. Output
3. Finiteness
4. Definiteness
5. Solvable
4 Define pseudo code and write a pseudo code to find the largest of three numbers.
Ans:
Definition:
Pseudo code is an informal way of programming description that does not require
any strict programming language syntax or underlying technology considerations.
It is similar to algorithm, and can be easily convertible to any programming
language.
Pseudo code can be broken down into five components.
• Variables:
• Assignment:
• Input/output:
• Selection:
• Repetition:
A variable has a name, a data type, and a value. There is a location in memory
associated with each variable. A variable can be called anything or be given any
name. It is considered good practice to use variable names that are relevant to the
task at hand.
Assignment is the physical act of placing a value into a variable. Assignment can be
shown using
set = 5;
set = num + set;
The left side is the variable a value is being stored in and the right side is where the
variable is being accessed. When a variable is assigned a value, the old value is
written over with the new value so the old value is gone. x = 5 does not mean that x
is equal to 5; it means set the variable x to have the value 5. Give x the value 5, make
x equal to 5.
Input / Output both deal with an outside source (can be a user or another program)
receiving or giving information. An example would be assuming a fast food
restaurant is a program. A driver (user) would submit their order for a burger and
fries (input), they would then drive to the side window and pick up their ordered
meal (output.)
• Output – Write / display / print
• Input – Read / get / input
Selection construct allows for a choice between performing an action and skipping it.
It is our conditional statements.
Selection statements are written as such:
if ( conditional statement)
statement list
else
statement list
5 Describe a Flowchart? Show the symbols used in a flow chart with an example each.
Ans:
Flowchart is a graphical representation of an algorithm.
Flowchart is the diagrammatic representation of an algorithm. It is constructed
with different types of symbols and boxes. The operation to be performed is
written inside the box. All symbols are connected by arrows among themselves to
indicate the flow of information and processing.
The symbols used in flowcharts have been standardized by the American
National Standards Institute. Arrows are used on the connecting flow lines if the
direction of flow is not clear. A flowchart should have one start and one or more
stop points and should be arranged so that the direction of processing is from
top to bottom and from left to right. Although flowlines can cross, the crossing
flowlines are independent of each other. Whenever possible, crossing of flowlines
should be avoided, since it makes the flowchart difficult to read.
for processing
Rectangle Process Any processing is
performed.
Represents computations
and data manipulations
Diamond Decission Represents the
branching to
alternative paths
based on a test
Creating phase:
i. We can create a C program in any text editor or any any integrated
environment. i.e., the code must be entered into a file.
ii. The created program is called as source code.
iii. Once the editing or creating is over, we have to save the file. For Ex:
“filename.c”
iv. The File must have an extentionof “.c” for every c program file.
Compiling phase:
Linking phase:
Execution phase:
i. In this phase the executable object code is loaded into the memory and the
program execution begins.
ii. At the time of execution, we may get some logical errors or run time errors.
iii. If any logical errors are found, we have to re edit the program and proceed to
all pahses again.
iv. If we gave any wrong data as the input, we have to re run (execute) the exe
file to give the coorect data as input to get the correct output.
7 List the different types of computer languages. Describe them briefly.
Ans:
Machine Language:
At the lowest level computer understands only 0 and 1. Programs expressed in terms
of binary language are called machine language. A computer’s programming
language consists of strings of binary numbers (0’s and 1’s) and is the only one
language computer can understand. This language is the lowest level of computer
language recognized and used by the CPU. An instruction prepared in any machine
language consists of 2 parts. The first part is the command or opcode or operation
code. The second part of the instruction is the operand/s or data and it tells the
processor where to find or store the data or other instructions that are manipulated.
A short sample of machine language to perform addition in the storage location
0166 will look like this
00010000 00000001 01100010
A machine language programmer has to know the binary code for each operation to
be carried out. Machine language programmers must also be familiar with the
internal organization of the computer. A machine language programmer must also
keep track of all the addresser of main memory locations that are referred to in the
program. The machine language format is slow and tedious. We the human beings
work on natural language and not on binary language. Hence writing machine
language program is difficult for the humans.
The off state can be represented by 0 and the on state can be represented by 1. Each
0 or 1 digit is referred to as a bit.
A bit is a single 0 or 1 in binary code.
A byte is a sequence of 8 bits. Each byte could also be represented as a decimal
number from 0 to 255.
Advantages:
Disadvantages:
Assembly language:
In the 1950’s, the first symbolic languages were created. The idea was to have each
type of instruction represented by some intuitive code word, and to allow data to be
represented as decimal numbers. Here is an excerpt from a symbolic language
program:
LDA 9000
MOV B,A
MOV C,A
HLT
An assembler is a special program used to translate symbolic code into machine
code. Symbolic languages also became known as assembly languages.
Assembler is used to convert assembly language into the machine language.
For example object program or machine language equivalent for the above assembly
language is 01110 0100001100
01110011101
0111110000
1011100000
Advantages:
i. Assembly language programs are commonly used to write programs for electronic
controls using microprocessors e.g., compilers, operating systems, animation in
computer graphics and so on.
ii. Assembly language is relatively easy for the human beings compared to machine
language. Programs writing are faster compared to machine language.
Disadvantages:
1. Assembly language programmer should know details of the architecture of the
machine. Assembly language programs are not portable.
2. Machine, symbolic and high level languages
They are used to solve specific problems and they are known as fourth generation
languages. Generally these languages uses WYSIWYG( What You See Is What You
Get) environment
For ex: Querry languages like SQL, Visual C++, Visual BASIC etc.,
Natural Languages:
Natural Languages behave like an expert to solve problems and tend to use artificial
intelligence. These languages are called Fifth Generation Languages and still they are
in developmental stage.
Ex: LISP and Prolog are having the characteristics and features of such languages.
8 Describe briefly about how interpreter and compiler work with the help of a neat
block diagram.
Ans:
Translators used:
Compiler & Interpreter
Compiler:
Compilers convert the program instructions from human understandable form to the
machine understandable form and the translated program instruction is called object
code. Compiler is nothing but a language translator used to translate the entire
program of the high level language into machine language. Every programming
language requires its own compiler to translate the program. For example, the
programming language PASCAL requires PASCAL compiler and C uses C compiler.
Interpreter:
Interpreters also convert the source program to machine language instruction but
execute each line as it is entered. The translation of the source program takes place
for every run and is slower than the compiled code. An interpreter must accompany
the object code to run a program. Programming languages BASIC, Python and LISP
use interpreters.
GW BASIC is an interpreter used to convert basic program into object program.
}
Sub program add (int x, int y)
Section Or {
User Defined Function --------
Section ---------
}
10 List the different data types along with their sizes in C, also give example for each.
Ans:
C data types are defined as the data storage format that a variable can store a
data to perform a specific operation.
Data types are used to define a variable before to use in a program.
Size of variable, constant and array are determined by data types.
C data types can be classified in to the following categories.
Type Data types
Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Enumeration Data Type enum, typedef
Void Data Type void
on a 4-byte compiler
Modifier Type Size max-value min-value
(bytes)
signed Char 1 127 (27-1) -128 (-27)
Unsigned char 1 255 (28-1) 0
signed int 4 2147483647 (231-1) -2147483648 (-231)
Unsigned int 4 4294967295 (232-1) 0
signed long 8 9223372036854775807 (263-1)-9223372036854775808 (-
263)
Unsigned long 8 18446744073709551615 (264- 0
1)
float 4 3.4*1038 1.4*10-45
double 8 1.7*10308 4.9*10-324
on a 2-byte compiler
Modifier type Size max-value min-value
(bytes)
signed char 1 127 (27-1) -128 (-27)
unsigned char 1 255 (28-1) 0
signed int 2 32767 (215-1) -32768 (-215)
unsigned int 2 65535 (216-1) 0
signed long 4 2147483647 (231-1) -2147483648 (-231)
unsigned long 4 4294967295 (232-1) 0
float 4 3.4*1038 1.4*10-45
double 8 1.7*10308 4.9*10-324
2. REAL CONSTANTS IN C:
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to be positive.
No commas or blanks are allowed within a real constant.
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)
12 i) Define a variable? List the rules for naming the variables. [4M]
Ans:
Variables
In programming, a variable is a container (storage area) to hold data. To indicate the
storage area, each variable should be given a unique name (identifier). Variable names
are just the symbolic representation of a memory location. A variable can change its
value in the course of a program.
For example:
int age = 25;
char gender = ‘M’;
Rules for naming a variable
The following are the rules for declaring the variables. Rules for constructing variable
names
1. The first character of the variable name must either be alphabet or underscore. It
should not start with the digit
2. No commas and blanks are allowed in the variable name
3. No special symbols other than underscore are allowed in the variable name
4. They can take maximum of length 31 characters.
5. Upper case and lower case variables are different i.e., int a is different from int A.
ii) Give examples for decimal, octal, hexadecimal integer literals. [3M]
Ans:
Literals
Literals are data used for representing fixed values. They can be used directly in the
code. For example: 1, 2.5, 'c' etc.
Here, 1, 2.5 and 'c' are literals. Why? You cannot assign different values to these terms.
Integers
An integer is a numeric literal(associated with numbers) without any fractional or
exponential part. There are three types of integer literals in C programming:
decimal (base 10)
octal (base 8)
hexadecimal (base 16)
For example:
Decimal: 0, -9, 22 etc
Octal: 021, 077, 033 etc
Hexadecimal: 0x7f, 0x2a, 0x521 etc
In C programming, octal starts with a 0, and hexadecimal starts with a 0x.
13 Describe Arthimetic Operators and write a C program to find the roots of quadratic
equation.
Ans:
Arithmetical Operators
The following table lists relational operators along with some examples:
Operator Description Example Result
> Greater than 1>2 0
>= Greater than or equal to 3 >= 2 1
< Smaller than 10 < 5 0
<= Smaller than or equal to 6 <= 7 1
== equal to 98==98 1
!= not equal to 10 != 9 1
// Is x is greater than y?
printf("x > y : %d\n", x > y);
// Is x is smaller than y?
printf("x < y : %d\n", x < y);
// Is x is equal to y?
printf("x == y : %d\n", x == y);
// Is x is not equal to y?
printf("x != y : %d\n", x != y);
x>y:0
x >= y : 0
x<y:1
x <= y : 1
x == y : 0
x != y : 1
15 List and describe logical operators in C and write a C program to check whether a
given year is leap year or not.
Ans:
Logical Operators in C
Logical operators are used to evaluate two or more conditions. In General, Logical
operators are used to combine relational expressions, but they are not limited to just
relational expression you can use any kind of expression even constants. If the result of
the logical operator is true then 1 is returned otherwise 0 is returned.
There are three types of logical operators:
Operator Meaning
&& AND operator
|| OR operator
! NOT operator
The AND ( && ) and OR ( || ) are binary operator while NOT ( ! ) is a unary operator.
In C, all non-zero values are considered as true ( 1 ) while 0 is considered as false.
AND(&&) operator
This operator gives the net result of true (i.e 1) if both operands are true, otherwise false
(i.e 0).
Operand 1 Operand Result
2
true true true
true false false
false true false
false false false
examples:
Expression Intermediate Expression Result
Result
(a==4) && (b==2) false && false => false 0 OR(||) operator
(a>100) && (b<10) false && true => false 0 This operator gives the net
a && b true && true => true 1 result of true (i.e 1) if at
a && 0 true && false => false 0 least one operand is true,
otherwise false.
Operand 1 Operand 2 Result
true true true
true false true
false true true
false false false
Example:
Expression Intermediate Result
Expression
!(a==4) !false => true 1
!(a || b) !true => false 0
!(a && b) !true => false 0
!(a > b) !true => false 0
if(y % 4 == 0)
{
//Nested if else
if( y % 100 == 0)
{
if ( y % 400 == 0)
printf("%d is a Leap Year", y);
else
printf("%d is not a Leap Year", y);
}
else
printf("%d is a Leap Year", y );
}
else
printf("%d is not a Leap Year", y);
return 0;
}
Output:
Enter year: 1991
1991 is not a Leap Year
C has two special unary operators called increment (++) and decrement (--) operators.
These operators increment and decrement value of a variable by 1.
Increment and decrement operators can be used only with variables.
They can’t be used with constants or expressions.
int x = 1, y = 1;
++x; // valid
++5; // invalid - increment operator operating on a constant value
++(x+y); // invalid - increment operating on an expression
y = ++x;
Here first, the current value of x is incremented by 1. The new value of x is then assigned
to y. Similarly, in the statement:
y = --x;
the current value of x is decremented by 1. The new value of x is then assigned to y.
The following program demonstrates prefix increment/decrement operator in action:
#include<stdio.h>
int main()
{
int x = 12, y = 1;
Expected Output:
Initial value of x = 12
Initial value of y = 1
After incrementing by 1: x = 13
y = 13
After decrementing by 1: x = 12
y = 12
int main()
{
int x = 12, y = 1;
After incrementing by 1: x = 13
y = 12
After decrementing by 1: x = 12
y = 13
“=”: This is the simplest assignment operator. This operator is used to assign the value
on the right to the variable on the left.
For example:
a = 10;
b = 20;
ch = 'y';
“+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the
current value of the variable on left to the value on the right and then assigns the result
to the variable on the left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
“-=”This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts
the current value of the variable on left from the value on the right and then assigns the
result to the variable on the left.
Example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
“*=”This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies
the current value of the variable on left to the value on the right and then assigns the
result to the variable on the left.
Example:
(a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
“/=”This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the
current value of the variable on left by the value on the right and then assigns the result
to the variable on the left.
Example:
(a /= b) can be written as (a = a / b)
// C program to demonstrate
// working of Assignment operators
#include <stdio.h>
int main()
{
// Assigning value 10 to a
// using "=" operator
int a = 10;
printf("Value of a is %d\n", a);
return 0;
}
Output:
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10
18 Explain about conditional operator and write a C Program to find the maximum of
three numbers.
Ans:
The Conditional operator the ternary operator (?:) is just like an if-else statement that
can be with in an expression. This operator is useful in situations, in which two or
more alternatives for an expression. They make the program code more compact.
The Syntax is :
exp1 ? exp2 : exp3
19 Explain the use of printf() and scanf() function in C. Illustrate with an example.
Ans:
printf() and scanf() functions are inbuilt library functions in C programming
language which are available in C library by default. These functions are declared
and related macros are defined in “stdio.h” which is a header file in C language.
We have to include “stdio.h” file as shown in below C program to make use of
these printf() and scanf() library functions in C language.
printf() function:
• In C programming language, printf() function is used to print the “character,
string, float, integer, octal and hexadecimal values” onto the output screen.
• We use printf() function with %d format specifier to display the value of an
integer variable.
• Similarly %c is used to display character, %f for float variable, %s for string
variable, %lf for double and %x for hexadecimal variable.
• To generate a newline,we use “\n” in C printf() statement.
Example for printf():
#include <stdio.h>
int main()
{
char ch = 'A';
char str[20] = "fresh2refresh.com";
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf("Character is %c \n", ch);
printf("String is %s \n" , str);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("Octal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
}
Output:
Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
Output:
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai
20 Explain the purpose of #include in a C program and write a C Program to find the
squareroot of a given number.
Ans:
In the C Programming Language, the #include directive tells the preprocessor to
insert the contents of another file into the source code at the point where the
#include directive is found. Include directives are typically used to include the C
header files for C functions that are held outsite of the current source file.
Syntax
The syntax for the #include directive in the C language is:
#include <header_file>
OR
#include "header_file"
header_file
The name of the header file that you wish to include. A header file is a C file that
typically ends in ".h" and contains declarations and macro definitions which can be
shared between several source files.
Note
The difference between these two syntaxes is subtle but important. If a header file is
included within <>, the preprocessor will search a predetermined directory path to
locate the header file. If the header file is enclosed in "", the preprocessor will look
for the header file in the same directory as the source file.
/**
* C program to find square root of a number
*/
#include<stdio.h>
#include<math.h>
int main()
{
int number;
double result;
result = sqrt(number);
printf("Square root value=%.2lf",result);
return 0;
}
Output:
2. i) Describe the left shift and right shift operators in C with suitable
examples and usage.
Ans:
The bitwise shift operators are used to move/shift the bit patterns
either to the left or right side. Left and right are two shift operators
provided by 'C' which are represented as follows:
Operand << n (Left Shift)
Operand >> n (Right Shift)
Here, an operand is an integer expression on which we have to
perform the shift operation.
'n' is the total number of bit positions that we have to shift in the
integer expression.
The left shift operation will shift the 'n' number of bits to the left side.
The leftmost bits in the expression will be popped out, and n bits with
the value 0 will be filled on the right side.
It performs multiplication
The right shift operation will shift the 'n' number of bits to the right
side. The rightmost 'n' bits in the expression will be popped out, and
the value 0 will be filled on the left side.
Example: x is an integer expression with data 1111. After performing
shift operation the result will be:
x << 2 (left shift) = 1111<<2 = 1100
x>>2 (right shift) = 1111>>2 = 0011
Shifts operators can be combined then it can be used to extract the
data from the integer expression.
A program to demonstrate the use of bitwise shift operators:
#include <stdio.h>
int main() {
int a = 20; /* 20 = 010100 */
int c = 0;
LED = 0x55;
printf("The original value before toggle = %x\n",LED);
LED = LED ^ 0xFF;
printf("Toggle Values after toggle = %x\n",LED);
}
Output:
The original value before masking = ff 11111111
The value of ter masking = f0 11110000
The original value before toggle = 55 01010101
Toggle Values after toggle = aa 10101010
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name. When the statement is
encountered, the expression is evaluated first and then replaces the
previous value of the variable on the left hand side. All variables used in
the expression must be assigned values before evaluation is attempted.
Example of evaluation statements are:
x=a*b–c
y=b/c*a
z = a – b / c + d;
Example of Expression with unary operator:
Unary expression requires only one operand.
For example :
Ex1:
int a = 5;
a++;
here a requires only one operator i.e. ++ and it evaluates as a = a+1;
Ex2:
int a = 10;
~a;
Here also ~ requires only one operand i.e a and it will be evaluated as a=
1010 and it becomes 0101
Explicit typecasting:
This process is also called type casting and it is user defined. Here the
user can type cast the result to make it of a particular data type.
The syntax in C:
(type) expression
Type indicated the data type to which the final result is converted.
// C program to demonstrate explicit type casting
#include<stdio.h>
int main()
{
double x = 1.2;
return 0;
}
Output:
sum = 2
Advantages of Type Conversion
This is done to take advantage of certain features of type
hierarchies or type representations.
It helps us to compute expressions containing variables of different
data types.
For example: ‘*’ and ‘/’ have same precedence and their associativity is
Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) *
10”.
Example 3:
For example: Solve
100 + 200 / 10 - 3 * 10
If else statement:
If else is a two way selection statement.
if-else ladder:
The if else ladder statement in C programming language is used to test
set of conditions in sequence. An if condition is tested only when all
previous if conditions in if-else ladder is false. If any of the conditional
expression evaluates to true, then it will execute the corresponding code
block and exits whole if-else ladder.
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf(“Enter a number : “);
scanf(“%d”,&a);
if(a > 0)
{
printf(“\nThe number is positive “);
}
else if(a<0)
{
printf(“\n The number is negative”);
}
else
{
printf(“Number is zero”);
}
}
Output:
Enter a number : 25
The number is positive
8. Explain Nested if with syntax and write a C program to find the largest of
three numbers using nested if.
Ans:
Nesting means using one if-else construct within another one.
If we use if statement in another if statement, we can call it as nested if
statement.
The syntax of nested if statement is :
Statement x;
if( condition-1)
{
if( condition-2)
{
Statement Block 1
}
else
{
Statement Block 2;
}
}
else
{
if(condition-3)
{
Statement Block 3
}
else
{
Statement Block 4;
}
}
Statement y;
Syntax Explanation:
The expression can be integer expression or a character expression.
Value-1, 2, n are case labels which are used to identify each case
individually. Remember that case labels should not be same as it
may create a problem
Case labels always end with a colon ( : ). Each of these cases is
associated with a block.
A block is nothing but multiple statements which are grouped for a
particular case.
Whenever the switch is executed, the value of test-expression is
compared with all the cases which we have defined inside the
switch.
The break keyword in each case indicates the end of a particular
case. If we do not put the break in each case then even though the
specific case is executed, the switch will continue to execute all the
cases until the end or (break) is reached. Break will terminate the
case once it is executed and the control will fall out of the switch.
The default case is an optional one. Whenever the value of test-
expression is not matched with any of the cases inside the switch,
then the default will be executed.
Once the switch is executed the control will go to the statement-x,
and the execution of a program will continue.
Program:
#include <stdio.h>
int main()
{
int language = 5;
switch (language)
{
case 1: printf("C#\n"); break;
case 2: printf("C\n"); break;
case 3: printf("C++\n"); break;
default: printf("Other programming language\n");
}
}
Output:
Other programming language
10. Write a C program to read two numbers and an arithmetic operator.
Using switch case perform the required arithmetic operations and display
the results.
Ans:
#include<stdio.h>
void main()
{
int a, b;
char op;
printf("Enter two integer values : ");
scanf("%d %d", &a, &b);
printf("Enter an arithmetic operator : ");
scanf(" %c", &op);
switch (op)
{
case '+': printf("%d + %d = %d\n", a, b, a+b);
break;
case '-': printf("%d - %d = %d\n", a, b, a-b);
break;
case '*': printf("%d * %d = %d\n", a, b, a*b);
break;
case '/': if (b != 0)
printf("%d / %d = %d\n", a, b, a/b);
else
printf("Division is not possible! Divide by zero error\
n");
break;
case '%': if (b != 0)
printf("%d %% %d = %d\n", a, b, a%b);
else
printf("Modulo division is not possible! Divide by zero
error\n");
break;
default: printf("Error! Operator is not correct\n");
}
}
Output:
Enter two integer values : 10 3
Enter an arithmetic operator : %
10 % 3 = 1
11. Explain while loop syntax with an example program.
Ans:
while loop in C:
A while loop statement in C programming language repeatedly executes a
target statement as long as a given condition is true.
Syntax:
The syntax of a while loop in C programming language is:
Statement x;
while( condition)
{
Statement1;
Statement2;
.
. Statement Block
.
Statementn;
Updation;
}
Statement y;
After executing Statement x, Condition will be evaluated first. The
condition may be any expression, and true is any nonzero value. The loop
iterates while the condition is true. Here, statement(s) may be a single
statement or a block of statements. The statement block consists of
updating statement also.
When the condition becomes false, program control passes to the line
immediately following the loop in this case, Statement y;.
Example program:
#include <stdio.h>
void main()
{
int count=1;
while (count <= 4)
{
printf("%d ", count);
count++;
}
}
Output:
1234
step1: The variable count is initialized with value 1 and then it has been
tested for the condition.
step2: If the condition returns true then the statements inside the body of
while loop are executed else control comes out of the loop.
step3: The value of count is incremented using ++ operator then it has
been tested again for the loop condition.
12. Describe while loop and write a C program to find the factorial of a given
number using while loop.
Ans:
C while loops statement allows to repeatedly run the same block of code
until a condition is satisfied. If the condition becomes false, the loop
terminates.
while loop is a most basic loop in C programming. while loop has one
control condition, and executes as long the condition is true. The
condition of the loop is tested before the body of the loop is executed,
hence it is called an entry-controlled loop.
The syntax for while loop is:
statement x;
while (condition)
{
statement(s);
updation;
}
statement y;
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression,
and true is any nonzero value. The loop iterates while the condition is
true.
When the condition becomes false, program control passes to the line
immediately following the loop.
Flow Diagram:
Here, key point of the while loop is that the loop might not ever run. When
the condition is tested and the result is false, the loop body will be
skipped and the first statement after the while loop will be executed.
C program to find the factorial of a given number:
#include <stdio.h>
void main()
{
int n,i=1,fact=1;
printf("Enter a Number : ");
scanf("%d", &n);
while(i<=n)
{
fact=fact * i;
i = i + 1;
}
printf("Factorial of %d = %d\n",n, fact);
}
Output:
Enter a Number: 6
Factorial of 6 = 720
13. Explain do-while loop syntax with an example program.
Ans:
C do while loops are very similar to the while loops, but it always executes
the code block at least once and furthermore as long as the condition
remains true.
Unlike for and while loops, which test the loop condition at the top of the
loop, the do...while loop in C programming language checks its condition
at the bottom of the loop.
This is an exit-controlled loop.
Syntax of do while loop:
Statement x;
do
{
statement(s);
updation;
} while ( condition );
Statement y;
Notice that the conditional expression appears at the end of the loop, so
the statement(s) in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop execute again. This process repeats until the
given condition becomes false.
Flow Diagram:
Example:
//C Program to find sum of ‘N’ natural numbers:
#include <stdio.h>
void main()
{
int N, i=1, sum=0;
printf("Enter N value: ");
scanf("%d", &N);
do
{
sum+=i;
i++;
} while (i<=N);
printf("Sum of %d Natural Nos = %d\n",N, sum);
}
Output:
Enter N value: 10
Sum of 10 Natural Nos = 55
14. Write a C program to print the sum of all even and odd numbers using
do-while loop.
Ans:
#include <stdio.h>
void main( )
{
int n,oddsum=0,evensum=0,i,x;
printf("Enter No. of elements : ");
scanf("%d", &n);
printf("Enter %d numbers: ", n);
for(i=1;i<=n;i++)
{
scanf("%d",&x);
if(x%2 == 0)
evensum+=x;
else
oddsum+=x;
}
printf("Sum of all Odd Numbers = %d\n",oddsum);
printf("Sum of all Even Numbers = %d\n",evensum);
}
Output:
Enter No. of elements : 6
Enter 6 numbers: 1 2 3 4 5 6
Sum of all Odd Numbers = 9
Sum of all Even Numbers = 12
15. Explain for loop construct with syntax and illustrate its usage with an
example.
Ans:
A for-loop is used to iterate over a range of values using a loop counter,
which is a variable taking a range of values in some orderly sequence (e.g.,
starting at 0 and ending at 5 in increments of 1).
The value stored in a loop counter is changed with each iteration of the loop,
providing a unique value for each individual iteration. The loop counter is
used to decide when to terminate the loop.
A for-loop construct can be termed as an entry controlled loop.
Syntax of a for-loop :
for (initialization; condition; update)
{
statement(s);
}
1. The initialization expression initializes the loop counter; it is executed
once at the start of the loop.
2. The loop continues to execute as long as the condition expression
evaluates to true.
3. The update expression is executed after each iteration through the
loop, to increment, decrement or change the loop counter.
Example with code :
int i;
for (i = 1; i < =5; i++)
{
printf("%d\n",i);
}
Output:
1
2
3
4
5
Explanation:
1. Above for-loop statement initializes an integer variable i (which is the
loop counter) as part of the initialization expression.
2. In the update section, it increments the variable i by 1 using the post-
increment expression i++.
3. The expression in condition is i <=5. The for-loop keeps on executing
the code inside the loop body as long as this condition evaluates to
true. And the loop terminates when the condition evaluates to false.
4. It is a good practice to always keep the loop body (which contains the
code to be executed) within an opening-brace { and a closing-brace }.
Note : No ; at the end of the for statement.
16. Write a C program to print the pyramid with numbers.
Ans:
#include <stdio.h>
void main()
{
int i,j,k,n;
printf(“Enter Number of rows: “);
scanf(“%d”,&n);
for(i=1; i<=n; i++)
{
for(k=1; k<=n-i; k++)
printf(" ");
for(j=1; j<=i; j++)
printf("%2d",i);
printf("\n");
}
}
Output:
Enter Number of rows: 5
1
22
333
4444
55555
17. Describe the purpose of break statement with a suitable program.
Ans:
The break statement terminates the loop immediately when it is
encountered.
In switch statement it will be used to terminate each block.
Its syntax is:
break;
The break statement is almost always used with if...else statement inside the
loop.
The working process of break statement in loops:
Example Program:
#include <stdio.h>
void main()
{
int i,j,k=1,n;
printf("Enter a number to stop: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
if(k<=n)
printf("%3d",k++);
else
{
i=n;
break;
}
}
printf("\n");
}
}
Output:
Enter a number to stop: 13
1
2 3
4 5 6
7 8 9 10
11 12 13
In the above program inner for loop will breaks with bellow code
if(k<=n)
printf("%3d",k++);
else
{
i=n;
break;
}
18. Describe the purpose of continue statement with a suitable example.
Ans:
The continue statement skips the current iteration of the loop and
continues with the next iteration.
Its syntax is:
continue;
The continue statement is almost always used with the if...else statement.
The working process of continue in loops:
Example Program for continue:
// Program to calculate the sum of a maximum of 10 numbers
// Negative numbers are skipped from the calculation
# include <stdio.h>
void main()
{
int n, i, sum = 0;
printf(“Enter 10 numbers: “);
for(i=1; i <= 10; ++i)
{
scanf("%d",&n);
if(n < 0)
{
continue;
}
sum += n; // sum = sum + number;
}
printf("Sum = %d\n",sum);
}
Output:
Enter 10 numbers: 2 -3 5 1 20 -10 3 15 -24 -2
Sum = 46.
In the above program continue makes the sum+= n statement omits when
the n is –ve number.
19. Define event controlled loops. Illustrate the same with suitable code
snippet.
Ans:
Event controlled loop
1. Here we don't know how many times loop is going to work
2. An event changes loop expression to be evaluated from true to false.
3. Example: when we read the data loop expression may be evaluated to
true. But, we encounter the end of the input. Loop expression may be
evaluated to false.
4. Sine series, palindrome, finding lcm and gcd are some of the examples
for event control loop programs.
Example Program.
//C program to find the GCD and LCM of two integers using Euclids' algorithm
#include <stdio.h>
void main()
{
int n1, n2, gcd, lcm, rem, numerator, denominator;
printf("Enter two numbers\n");
scanf("%d %d", &n1, &n2);
if (n1 > n2)
{
numerator = n1;
denominator = n2;
}
else
{
numerator = n2;
denominator = n1;
}
rem = numerator % denominator;
while (rem != 0)
{
numerator = denominator;
denominator = rem;
rem = numerator % denominator;
}
gcd = denominator;
lcm = n1 * n2 / gcd;
printf("GCD of %d and %d = %d\n", n1, n2, gcd);
printf("LCM of %d and %d = %d\n", n1, n2, lcm);
}
Output:
Enter two numbers: 24 8
GCD of 24 and 8 = 8
LCM of 24 and 8 = 24
In the above program we don’t know how many times the while loop will be
repeated. It will run until the remainder is not equals to 0 and stops when the
condition is false (which is an event).
20. Define counter controlled loops. Illustrate the same with suitable code
snippet.
Ans:
Counter controlled loop:
1. Here we know how many times loop is going to work.
2. Sum of n natural numbers, Fibonacci series these are examples for
counter controlled loop programs.
Example Program:
// Program to print Fibonacci series up to n terms
#include <stdio.h>
void main()
{
int a, b, c, i, terms;
Output:
Enter number of terms: 5
01123
Here We know that the for loop is going to be executed ‘n’ times with the
help of a counter variable ‘i’, hence it is a counter controlled loop.
Unit 3_1 Assignment Question and Answers
Declaring Arrays
To declare an array, a programmer specifies the type of the elements and
the number of elements required by an array as follows:
double balance[10];
Initializing Arrays
You can initialize array either one by one or using a single statement as
follows:
The above statement will take 10th element from the array and assign
the value to salary variable.
e.g.
#include <stdio.h>
void main ()
{
int n[5 ]; /* n is an array of 5 integers */
int i,j,x;
printf(“Engter 5 Elements : “);
for ( i = 0; i < 5; i++ )
{
scanf(“%d”,&n[i]);
}
for (j = 0; j < 5; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
}
When the above code is compiled and executed, it produces the following
result:
Enter 5 Elements : 4 5 6 8 9
Element[0] = 4
Element[1] = 5
Element[2] = 6
Element[3] = 8
Element[4] = 9
Element[9] = 109
2 Write a program to read an array of integers (with max size 10) and print
the largest and the smallest of the given numbers.
Ans:
#include<stdio.h>
void main()
{
int a[10], i, n, min, max;
printf("Enter how many values you want to read : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Enter the value of a[%d] : ", i);
scanf("%d", &a[i]);
}
min=max=a[0];
for(i=1; i<n; i++)
{
if(a[i]<=min)
min = a[i];
if(a[i]>=max)
max = a[i];
}
printf("The largest element of the array = %d\n",max);
printf("The smallest element of the array = %d\n", min);
}
Output:
Enter how many values you want to read : 5
Enter the value of a[0] : 2
Enter the value of a[1] : 1
Enter the value of a[2] : 3
Enter the value of a[3] : 5
Enter the value of a[4] : 4
The largest element of the array = 5
The smallest element of the array = 1
Declaration:
Example:
char name[50];
Initialization:
A One-dimensional character array is initialized as:
char ch[ ] = { 'a', 'e', 'i', 'o', 'u', '\0'};.
Or
char ch[] = “aeiou”;
Or
char ch[5]={ 'a', 'e', 'i', 'o', 'u'};
Method 1:
Accessing all content at once:
In C for accessing 1D character array we can use %s format
specifier in scanf() and printf() statements.
Using these statements we can access the whole array content at a
time.
For ex:
char name[20];
printf(“Enter your name: “);
scanf(“%s”, name);
printf(“Hello! \t %s\n”,name);
Output:
Enter your name: Ravi
Hello! Ravi
Method2:
Accessing the content by character by character:
- We have to use %c format specifier in printf() and scanf() statements
- We have to use a counter loop for printing the content character by
character
For ex:
char name[20];
int i=0;
printf(“Enter your name: “);
scanf(“%s”,name);
printf(“The name is : “);
while(name[i]!=\0’)
{
printf(“%c”,name[i]);
i++;
}
Output:
Enter your name: Rahul
The name is : Rahul
Output:
Enter a String : Hello
Reverse of the String Hello = olleH
Explanation:
Data-type array-name[row-size]
Example:
int x[3][3] ;
ers
We can initialize a 2-D array also while declaring it like 1-D arrays. There are two
forms of initializing 2-D arrays.
Data-type array-name[rowsize][colsize] =
{ initialize-list } ;
Data type refers to any data type supported by C. Array-name refers to
any valid C identifier. Rowsize indicates the no. of rows, colsize indicates
the no. of columns of the array. Initializer-list is a comma separated list of
values.
Example:
Since col-size is 4, the first 4 values of the initializer list are assigned to
the first row of x and the next 4 value are assigned to the second row of x
as sown bellow
1 2 3 4
5 6 7 8
Note:
Example:
The 1st row of x gets filled with the values in the intializer-list. The second
row gets filled with 0’s.
1 2 3 4
0 0 0 0
The values in the initializer-list 1 are assigned to the location in the first
row. The values in the initializer-list 2 are assigned to the locations in the
second row and so on.
Example:
1 2 3 4
5 6 7 8
Note:
1. If the no. of values specified in any intializer-list is less than col-size of
x, only the 1st location in the corresponding row would get these
values. The remaining locations in that row would get 0.
Example:
since the 1st initializer-list has only 3 values, x[0][0] is 1, x[0][1] is set to
2, x[0][2] is set to 3 and the 4th location in the first row is automatically
set to 0
1 2 3 0
5 6 7 8
Accessing 2D array:
int x[2][2];
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf(“%d”,&x[i][j]
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf(“%d”,x[i][j]
}
Printf(“\n”);
}
6 Write a C program that can take 2 matrices as input, add them and print
the result.
Ans:
#include <stdio.h>
void main() {
int i, j, m, n, p, q, a[5][5], b[5][5], c[5][5];
printf("Enter the row & column sizes of matrix-1 : ");
scanf("%d %d", &m, &n);
printf("Enter matrix-1 %d elements : ", m*n);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter the row & column sizes of matrix-2 : ");
scanf("%d %d", &p, &q);
printf("Enter matrix-2 %d elements : ", p*q);
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
scanf("%d", &b[i][j]);
}
}
if((m!=p) || (n!=q))
{
printf("Addition is not possible\n");
}
else
{
printf("Addition of two matrices is\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
printf("%d ", c[i][j]);
}
printf("\n");
}
}
}
Output:
Enter the row & column sizes of matrix-1 : 2 2
Enter matrix-1 4 elements : 1 2 3 4
Enter the row & column sizes of matrix-2 : 2 2
Enter matrix-2 4 elements : 1 2 3 4
The given matrix-1 is
12
34
The given matrix-2 is
12
34
Addition of two matrices is
24
68
7 Write a C program that can take 2 matrices as input, multiply them and
print the result.
Ans:
#include <stdio.h>
void main() {
int i, j, k, m, n, p, q, a[5][5], b[5][5], c[5][5];
printf("Enter the row & column sizes of matrix-1 : ");
scanf("%d %d", &m, &n);
printf("Enter matrix-1 %d elements : ", m*n);
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Enter the row & column sizes of matrix-2 : ");
scanf("%d %d", &p, &q);
printf("Enter matrix-2 %d elements : ", p*q);
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
scanf("%d", &b[i][j]);
}
}
printf("The given matrix-1 is\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
printf("The given matrix-2 is\n");
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
printf("%d ", b[i][j]);
}
printf("\n");
}
if (n == p) {
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
c[i][j] = 0;
for (k = 0; k < n; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
printf("Multiplication of two matrices is\n");
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
}
else
{
printf("Multiplication is not possible\n");
}
}
Output:
nter the row & column sizes of matrix-1 : 3 3
Enter matrix-1 9 elements : 1 2 3 4 5 6 7 8 9
Enter the row & column sizes of matrix-2 : 3 3
Enter matrix-2 9 elements : 1 0 0 0 1 0 0 0 1
The given matrix-1 is
123
456
789
The given matrix-2 is
100
010
001
Multiplication of two matrices is
123
456
789
Output:
Enter the order of matrix : 3 2
Enter 6 elements : 1 2 3 4 5 6
The given matrix is
12
34
56
Transpose of the given matrix is
135
246
Declaration:-
char arr[rowsize][colsize];
where,
arr - name of the array
rowsize -represents number of strings
colsize -represents size of each string
Initialization:-
Syntax:
char Array_Name[row][col] = { list of strings };
Example:-
char city[5][10] = { “DELHI”, “CHENNAI”, “BANGALORE”, “HYDERABAD”,
“MUMBAI” };
D E L H I \0
C H E N N A I \0
B A N G A L O R E \0
H Y D E R A B A D \0
M U M B A I \0
In the above storage representation memory is wasted due to the fixed
length for all strings.
For ex:
printf(“%c”,city[0][1]);
- It prints ‘E’ from the above city 2D array
printf(“%s”city[1]);
- It prints “CHENNAI” from the above 2D array.
#include<stdio.h>
void main() {
char names[5][30];
int i;
printf("Enter 5 Names : \n");
for(i=0;i<5;i++)
scanf("%s", names[i]);
printf("Names in the array are:\n");
for(i=0;i<5;i++)
printf("%s\n", names[i]);
}
Output:
Enter 5 Names :
Kavitha
Jeevan
Hari
Varma
Neelima
Names in the array are:
Kavitha
Jeevan
Hari
Varma
Neelima
Output:
Enter How many Names : 5
Enter 5 names :
Hari
Geetha
David
Harika
Gautham
Names in the List are :
Hari
Geetha
David
Harika
Gautham
Enter a name to search : David
David is found in the list at 3 location
strcat(string1, string2);
Example program:
#include <stdio.h>
#include <string.h>
void main()
{
char str1[10] = "Hello";
char str2[10] = "Students";
strcat(str1,str2);
printf("str1 = %s\n",str1);
printf("str2 = %s\n",str2);
}
Output:
str1 = HelloStudents
str2 = Students
strcpy():
The function strcpy() is used to copy one sting into another string
including the NULL character (terminator char '\0').
Where string1, string2 are two strings and the string2 is copied into
string1. In this case the copied string is available in string1 and both
strings contains the same data.
If the length of string1 is less than the length of string2 then entire string2
value will not be copied into string1.
For example, consider the length of string1 is 20 and the length of string2
is 30. Then, only the first 20 characters from string2 will be copied into
string1, the remaining 10 characters will not be copied and will be
truncated.
Example Program:
#include <stdio.h>
#include <string.h>
void main()
{
char str1[10] = "Hello";
char str2[10] = "Students";
strcpy(str1,str2);
printf("str1 = %s\n",str1);
printf("str2 = %s\n",str2);
}
Output:
str1 = Students
str2 = Students
void main( )
{
char str1[30],tmp;
int i,j;
printf("Enter a string: ");
scanf("%s",str1);
for(j=0;str1[j]!='\0';j++);
for(i=0,j=j-1;i<=j;i++,j--)
{
tmp=str1[i];
str1[i]=str1[j];
str1[j]=tmp;
}
printf("Reverse of the string : %s\n",str1);
}
Output:
Enter a string: College
Reverse of the string : egelloC
strlen():
The function strlen() is used to find the length of the given string. This
function returns only the integer data (or) numeric data.
The string.h header file supports all the string functions in C language.
Example Program:
#include <stdio.h>
#include <string.h>
void main() {
char name[20];
printf("Enter a string : ");
scanf("%s", name);
printf("The length of the string %s is : %d\n", name, strlen(name));
}
Output:
Enter a string : Ranarangam
The length of the string Ranarangam is : 10
strcmp():
The function strcmp() is used for comparison of two strings and it always
returns the numeric data.
Where string1, string2 are two strings and the variable is of the type
integer.
Example Program:
#include <stdio.h>
#include <string.h>
void main()
{
char a[20], b[20];
int i, j;
printf("Enter the first string : ");
scanf("%s", a);
printf("Enter the second string : ");
scanf("%s", b);
i=strcmp(a,b);
if (i==0)
printf("The given two strings are equal\n");
else if (i>0)
printf("The string %s is higher than the string %s\n", a, b);
else
printf("The string %s is higher than the string %s\n", b, a);
}
Output:
Enter the first string : Rajani
Enter the second string : Raju
The string Raju is higher than the string Rajani
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
Code Snippet:
flag = 0;
printf("Enter key element : ");
scanf("%d", &key);
for (i=0; i<n; i++ )
{
if (a[i]==key )
{
flag = 1;
pos = i;
break;
}
}
if (flag==1 )
printf("The key element %d is found at the position %d\n", key,
pos);
else
printf("The Key element %d is not found in the array\n", key);
for(i=0;i<n; i++)
{
if(a[i]==key)
{
printf("The key element %d is found at the position %d\n", key,
i);
break;
}
}
if(i==n)
printf("The Key element %d is not found in the array\n", key);
}
Output:
Enter value of n : 5
Enter element for a[0] : 2
Enter element for a[1] : 5
Enter element for a[2] : 6
Enter element for a[3] : 1
Enter element for a[4] : 4
Enter key element : 1
The key element 1 is found at the position 3
Binary search uses divide and conquer technique and it works on the
sorted list either in ascending or descending order.
Binary search compares the key element to the middle element of the
array; if they are unequal, the half in which the key element cannot lie is
eliminated and the search continues on the remaining half until it is
successful.
low = 0;
high = n;
while (low<=high)
{
mid=(low+high)/2 ;
if (key==a[mid] )
{
flag = 1;
break;
}
else if (key>a[mid] )
low = mid+1;
else if (key<a[mid] )
high = mid-1;
}
if (flag==1 )
printf("The key element %d is found at the position %d\n", key,
mid);
else
printf("The Key element %d is not found in the array\n", key);
Now we compare the value stored at location 4, with the value being
searched, i.e. 31. We find that the value at location 4 is 27, which is not a
match. As the value is greater than 27 and we have a sorted array, so we
also know that the target value must be in the upper portion of the array.
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with
our target value 31.
The value stored at location 7 is not a match, rather it is more than what
we are looking for. So, the value must be in the lower part from this
location.
Hence, we calculate the mid again. This time it is 5.
We compare the value stored at location 5 with our target value. We find
that it is a match.
Search - 1 :
Compare 10 with value of a[0] i.e., 50, both are not equal so repeat the
same process with a[1].
Search - 2 :
Compare 10 with value of a[1] i.e., 20, both are not equal so repeat the
same process with a[2].
Search - 3 :
Compare 10 with value of a[2] i.e., 40, both are not equal so repeat the
same process with a[3].
Search - 4 :
Compare 10 with value of a[3] i.e., 10, both are equal so stop the
process and print index value where it found, i.e., position 3.
Search - 1 :
First Sort the given array elements by using any one of the sorting
technique.
After sorting the elements in the array are 10 20 40 50 80 and initially
low = 0, high = 4.
Search - 2 :
Compare 10 with middle element i.e., (low + high) / 2 = (0 + 4) / 2 = 4
/ 2 = 2, a[2] is 40. Here 10 < 40 so search the element in the left half
of the element 40. So low = 0, high = mid - 1 = 2 - 1 = 1.
Search - 3 :
Compare 10 with middle element i.e., (low + high) / 2 = (0 + 1) / 2 = 1
/ 2 = 0, a[0] is 10. Here 10 == 10 so print the index 0 where the
element has found and stop the process
low = 0;
high = n;
while (low<=high)
{
mid=(low+high)/2 ;
if (key==a[mid] )
{
flag = 1;
break;
}
else if (key>a[mid] )
low = mid+1;
else if (key<a[mid] )
high = mid-1;
}
if (flag==1 )
printf("The key element %d is found at the position %d\n", key,
mid);
else
printf("The Key element %d is not found in the array\n", key);
}
Output:
Enter value of n : 5
Enter 5 Elements in ascending order : 2 4 6 7 8
Enter key element : 7
The key element 7 is found at the position 3
UNIT 3-2 Important Questions for 2nd Mid
Bubble sort is an internal sorting technique in which adjacent elements are compared and exchanged if
necessary.
The working procedure for bubble sort is as follows:
1. Compare the first two elements in the array i.e., a[0] and a[1], if a[1] is less
than a[0] then interchange the two values.
2 Next compare a[1] and a[2], if a[2] is less than a[1] then interchange the values.
3 Continue this process till the last two elements are compared and interchanged.
4 Repeat the above steps for n - 1 passes.
Let us consider an example of array numbers "50 20 40 10 80", and sort the array from lowest
number to greatest number using bubble sort.
In each step, elements written in bold are being compared. Number of elements in the array are 5,
so 4 passes will be required.
Pass - 1 :
( 50 20 40 10 80 ) -> ( 20 50 40 10 80 ) // Compared the first two elements, and swaps since 50 > 20.
( 20 50 40 10 80 ) -> ( 20 40 50 10 80 ) // Swap since 50 > 40.
( 20 40 50 10 80 ) -> ( 20 40 10 50 80 ) // Swap since 50 > 10.
( 20 40 10 50 80 ) -> ( 20 40 10 50 80 ) // Since the elements are already in order (50 < 80), algorithm
does not swap them.
Total number of elements in the given array are 5, so in Pass - 1 total numbers compared are 4. After
completion of Pass - 1 the largest element is moved to the last position of the array.
Now, Pass - 2 can compare the elements of the array from first position to second last position.
Pass - 2 :
( 20 40 10 50 80 ) -> ( 20 40 10 50 80 ) // Since the elements are already in order (20 < 50), algorithm
does not swap them.
( 20 40 10 50 80 ) -> ( 20 10 40 50 80 ) // Swap since 40 > 10.
( 20 10 40 50 80 ) -> ( 20 10 40 50 80 ) // Since the elements are already in order (40 < 50), algorithm
does not swap them.
In Pass - 2 total numbers compared are 3. After completion of Pass - 2 the second largest element is
moved to the second last position of the array.
Now, Pass - 3 can compare the elements of the array from first position to third last position.
Pass - 3 :
( 20 10 40 50 80 ) -> ( 10 20 40 50 80 ) // Swap since 20 > 10.
( 10 20 40 50 80 ) -> ( 10 20 40 50 80 ) // Since these elements are already in order (20 < 40), algorithm
does not swap them.
In Pass - 3 total numbers compared are 2. After completion of Pass - 3 the third largest element is
moved to the third last position of the array.
Now, Pass - 4 can compare the first and second elements of the array.
Pass - 4 :
( 10 2040 50 80 ) -> ( 10 20 40 50 80 ) // Since these elements are already in order (10 < 20), algorithm
does not swap them.
In Pass - 4 total numbers compared are 1. After completion of Pass - 4 all the elements of the array are
sorted. So, the result is 10 20 40 50 80.
Or
Bubble sort
Bubble sort compares the value of first element with the immediate next
element and swaps according to the requirement and goes till the last
element. This iteration repeats for (N - 1) times/steps where N is the
number of elements in the list.
Selection sort process can be done in two ways, one is the largest element method and the other is
smallest element method.
The working procedure for selection sort largest element method is as follows:
Pass - 1 :
( 80 10 50 20 40 ) -> ( 40 10 50 20 80 ) // First finds the largest element and it is exchanged with the last
position element.After completion of Pass - 1, the largest element is moved to the end of the array.
Now, Pass - 2 can find the next largest element with out considering the last position element.
Pass - 2 :
( 40 10 50 20 80 ) -> ( 40 10 20 50 80 ) // Largest in 40 10 50 20 is 50 and it is replaced with next last
position of the array.After completion of Pass - 2 the second largest element is moved to the second last
position of the array.
Now, Pass - 3 can find the next largest element with out considering the last two position elements
because they are already sorted.
Pass - 3 :
Now, Pass - 4 can find the next largest element with out considering the last three position elements
because they are already sorted.
Pass - 4 :
( 20 10 40 50 80 ) -> ( 10 20 40 50 80 ) // Largest in 20 10 is 20 and it is replaced with next last position of
the array.After completion of Pass - 4 all the elements of the array are sorted. So, the result is 10 20 40
50 80.
for ( i=0;i<n;i++) {
printf("Enter element for a[%d] : ", i);
scanf("%d", &a[i]);
}
printf("Before sorting the elements in the array are\n");
for (i=0;i<n;i++ ) {
printf("Value of a[%d] = %d\n", i, a[i]);
}
for (i=n-1;i>=1;i-- ) {
index = i;
for (j=i;j>=0;j-- ) {
if (a[j]>a[index] ) {
index = j;
}
}
large = a[index];
a[index] = a[i];
a[i]=large;
}
printf("After sorting the elements in the array are\n");
for (i=0;i<n;i++ ) {
printf("Value of a[%d] = %d\n", i, a[i]);
}
}
Output:
Enter value of n : 3
Enter element for a[0] : 22
Enter element for a[1] : 33
Enter element for a[2] : 12
Before sorting the elements in the array are
Value of a[0] = 22
Value of a[1] = 33
Value of a[2] = 12
After sorting the elements in the array are
Value of a[0] = 12
Value of a[1] = 22
Value of a[2] = 33
Insertion sort is one that sorts a set of elements by inserting an element into the existing sorted
elements.
The working procedure for insertion sort is as follows:
For example of array numbers "50 20 40 10 30", and sort the array from lowest number to greatest
number using insertion sort.
In each step, elements written in color is compared with elements written in bold. Number of elements
in the array are 5, so 4 passes will be required.
Pass - 1 :
( 50 20 40 10 30 ) -> ( 20 50 40 10 30 ) // The second element a[1] is compared with the first element
a[0] and swaps since 50 > 20, so first 2 elements are sorted.
Now, Pass - 2 can compare a[2] with a[0] and a[1].
Pass - 2 :
( 20 5040 10 30 ) -> ( 20 40 50 10 30 ) // Since 40 > 20 and 40 < 50, so 40 is inserted in between 20 and
50.
Now, Pass - a[3] with a[0], a[1] and a[2].
Pass - 3 :
( 20 40 50 10 30 ) -> ( 10 20 40 50 30 ) // Since 10 < 20, so it is inserted before 20.
Now, Pass - 4 can compare a[4] with a[0], a[1], a[2] and a[3].
Pass - 4 :
( 10 20 40 50 30 ) -> ( 10 20 30 40 50 ) // Since 30 > 10, 30 > 20 but 30 < 40, so 30 is inserted in between
20 and 40 .
After completion of Pass - 4 all the elements of the array are sorted. So, the result is 10 20 30 40 50.
for (i=0;i<n;i++ ) {
printf("Enter element for a[%d] : ", i);
scanf("%d", &a[i]);
}
printf("Before sorting the elements in the array are\n");
for (i=0;i<n;i++ ) {
printf("Value of a[%d] = %d\n", i, a[i]);
}
for (i=0;i<n;i++ ) {
printf("Value of a[%d] = %d\n",i, a[i] );
}
}
Output:
Enter value of n : 3
Enter element for a[0] : 22
Enter element for a[1] : 33
Enter element for a[2] : 12
Before sorting the elements in the array are
Value of a[0] = 22
Value of a[1] = 33
Value of a[2] = 12
After sorting the elements in the array are
Value of a[0] = 12
Value of a[1] = 22
Value of a[2] = 33
7 Compare Bubble sort & Selection sort with suitable example and list their respective time
complexities.
Ans:
1. Bubble Sort
Bubble sort repeatedly compares and swaps(if needed) adjacent elements in every pass. In i-th pass of
Bubble Sort (ascending order), last (i-1) elements are already sorted, and i-th largest element is placed at
(N-i)-th position, i.e. i-th last position.
Algorithm:
2. Selection Sort
Selection sort selects i-th smallest element and places at i-th position. This algorithm divides the array
into two parts: sorted (left) and unsorted (right) subarray. It selects the smallest element from
unsorted subarray and places in the first position of that subarray (ascending order). It repeatedly
selects the next smallest element.
Algorithm:
min_index = I;
For ( J:= I+1 to N ) // Search Unsorted Subarray (Right lalf)
{
If ( Arr [J] < Arr[min_index] )
min_index = J; // Current minimum
}
Swap ( Arr[I], Arr[min_index] );
// Swap I-th smallest element with current I-th place element
}
}
8 Compare Insertion sort & Selection sort with suitable example and list their respective time
complexities.
Ans:
Insertion Sort:
Insertion Sort: Given a list, take the current element and insert it at the appropriate position of the list,
adjusting the list every time you insert. It is similar to arranging the cards in a Card game.
Time Complexity of selection sort is always n(n - 1)/2, whereas insertion sort has better time complexity
as its worst case complexity is n(n - 1)/2. Generally it will take lesser or equal comparisons then n(n - 1)/
2.
Selection Sort:
Selection Sort: Given a list, take the current element and exchange it with the smallest element on the
right hand side of the current element.
SORTING ALGORITHM TIME COMPLEXITY
Best Case Average Case Worst Case
Selection Sort O(N^2) O(N^2) O(N^2)
Insertion Sort O(N) O(N^2) O(N^2)
9 Define Function & outline the structure of a user defined function with example.
Ans:
A function is a block of code that performs a specific task. It has a name and it is reusable .It can be
executed from as many different parts in a program as required, it can also return a value to calling
program.
All executable code resides within a function. It takes input, does something with it, then give the
answer. A C program consists of one or more functions.
A computer program cannot handle all the tasks by itself. It requests other program like entities called
functions in C. We pass information to the function called arguments which specified when the function
is called. A function either can return a value or returns nothing. Function is a subprogram that helps
reduce coding.
function prototype:
function call:
Function Definition
Local variables;
Local statements;
}
Example of Function in C
#include<stdio.h>
#include <conio.h>
int main()
{
int z;
z= addion(10,3); //Function Call
printf ("The Result is %d", z);
return 0;
}
10 Differentiate Pre-defined and User-defined functions. Write a function to find the factorial of a given
number.
Ans:
A function is a self-contained block of code that carries out some specific and well-defined task.
C functions are classified into two categories
1. Library Functions / Predefined functions
2. User Defined Functions
The user-defined functions are defined by a user as per its own requirement and library functions come
with compiler.
#include<stdio.h>
int fact(int);
void main() {
int n, f;
printf(“Enter a number : “);
scanf(‘%d”, &n);
f=fact(n);
printf(“Factorial of %d = %d\n”,n,f);
}
int fact(int n) {
int f=1, i;
for(i=1;i<=n;i++)
f=f*i;
return f;
}
Output:
Enter a number : 5
Factorial of 5 = 120
11 i) Explain about functions with no arguments and no return values with example.[3M]
Ans:
We can create a function with no arguments and no return values.
For Ex:
#include<stdio.h>
void add( void);
void main() {
add();
}
void add() {
int a, b;
printf(“Enter a b values: “);
scanf(“%d %d”, &a, &b);
printf(“%d + %d = %d\n”,a, b, a+b);
}
ii) Explain about functions with arguments and no return values with example.[4M]
Ans:
Similarly we can create a function with arguments and no return values:
For Ex:
#include<stdio.h>
void add( int , int);
void main() {
int a, b;
printf(“Enter a b values: “);
scanf(“%d %d”, &a, &b);
add(a, b);
}
void add(int x , int y) {
int z;
z=x+y;
printf(“%d + %d = %d\n”,x, y, z);
}
12 i) Explain about functions with no arguments and with return values with example.[3M]
Ans:
In this function type the calling function does not have any arguments from the called function.
But the calling function will send argument to the called function.
For Ex:
#include<stdio.h>
int add( void);
void main() {
int x = add();
printf( “Result = %d\n”, x);
}
int add() {
int a=5, b=10;
return (a+b);
}
Output:
Result = 15
ii) Explain about functions with arguments and return values with example.[4M]
Ans:
In this type of function type the calling function will send some arguments to called function and
called function will return a variable or value to calling function.
For Ex:
#include<stdio.h>
int add( int, int);
void main() {
int x=10, y=20, z;
z = add(x,y);
printf( “Result = %d\n”, z);
}
int add(int a, int b) {
return (a+b);
}
Output:
Result = 30
13 How parameters are passed using call by value? Explain with suitable example code snippets.
Ans:
In call by value we send either variables, constants or expressions to the calling function. Here the
values will be passed to the calling function. The called function values are not modified at the
calling function, even though they are modified at the calling function.
For example:
#include<stdio.h>
void add(int , int);
void main() {
int a=10, b=20;
printf(“Before calling add() in main() a = %d, b= %d\n”,a,b);
add(a,b);
printf(“After calling add() in main() a = %d, b= %d\n”,a,b);
}
void add( int a, int b) {
a= a+10;
b=b+10;
printf(“In add() function a = %d, b= %d\n”,a,b);
}
Output:
Before calling add() in main() a = 10, b=20;
In add() function a = 20, b=30
After calling add() in main() a = 10, b=20
14 What is call by value and write a C program for swapping of two numbers using call by value.
Ans:
In call by value the parameters passed to calling function as values. They will be copied to new
variables which are newly created at calling function.
Once the called function is completed its task, it will be destroyed.
The variables which are created, are local to that function only.
They will not create in impact on original variables.
In call by value, we can not send (return) more than one variable to the calling function.
For Example:
#include<stdio.h>
void swap( int, int);
void main() {
int a, b;
printf(“Enter two values : “);
scanf(“%d %d”, &a, &b);
printf(“Before swap in main() a = %d b = %d\n”, a, b);
swap(a,b);
printf(“After swap in main() a = %d b = %d\n”, a,b);
}
Output:
15 Explain automatic, global and register storage classes in detail with examples.
Ans:
See Notes
16 Define storage class and explain extern and static storage classes in detail with examples.
Ans: (See Notes)
Storage classes provide the following information:
• Where the variable would be stored.
• What will be the initial value of the variable; i.e., the default value for the variable.
• What is the scope of the variable; i.e., if the variable is accessible globally or is local to a
function.
• What is the life of the variable; i.e., how long would the variable exist in memory.
Extern Storage class:
• External variables are used with separate compilations. It is common, on large projects, to
decompose the project into many source files.
• The decomposed source files are compiled separately and linked together to form one unit.
• Within file variables outside functions have external storage class, even without the keyword
extern.
• Global variables (defined outside functions) and all functions are of the storage class extern and
storage is permanently assigned to them.
• Files can be compiled separately, even for one program.
• extern is used for global variables that are shared across code in several files.
• a variable declared with a storage class of extent has a file scope; the extent is, static, but
linkage is external.
Declaration:
An external variable before must be declared before that is used by other source files. The
above syntax is used to external variables from other files.
Initialization
If the variable not initialized, then the first declaration seem by the linkage is considered the
definition and all other declarations reference it. If an initializer is used with a global definition it
is defining declaration.
file2.c
int fun (void)
{
extern int a; /* look for it elsewhere */
int b, c;
a = b = c = 4; b and c are local and don‘t survive
return (a + b + c);
} return 12
Note: The difference between a normal static variable and a extern static variable is that the
static external variable is available only within the file where it is defined while the simple
external variable can be accessed by other files.
The main difference between auto and static is that the static variables do not disappear when the
function is no longer active (in scope) and their values persist across multiple calls of the same function.
here x is static variable hence it retains the value during the function calls, and y is a normal variable
hence it is not retained its value.
17 Define preprocessing. Explain #define , #undef, #include directives with suitable examples.
Ans:
Preprocessing:
The preprocessor is a program which processes the source code before it passes through the
compiler.It operates under the control of preprocessor directive. These are placed in the source
program before the main.
Compilation
Preprocessor programs provide preprocessors directives which tell the compiler to preprocess the
source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash) symbol.
This (‘#’) symbol at the beginning of a statement in a C indicates that it is a pre-processor directive.
We can place these preprocessor directives anywhere in our program. Examples of some
preprocessor directives are: #include, #define, #ifndef etc.
#define:
a. Symbolic constants
Macro definition without arguments is referred as a constant. The body of the macro definition can
be any constant value including integer, float, double, character, or string. However, character
constants must be enclosed in single quotes and string constants in double quotes.
Example:
#define PI 3.14159
Here “PI” replaces with "3.14159"
b. Macros
A macro definition command associates a name with a sequence of tokens. The name is called the
macro name and the tokens are referred to as the macro body.
Example:
#define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) )
would cause
area = CIRCLE_AREA( 4 );
to become
area = ( 3.14159 * ( 4 ) * ( 4 ) );
#undef :
In the C Programming Language, the #undef directive tells the preprocessor to remove all definitions
for the specified macro. A macro can be redefined after it has been removed by the #undef
directive.
Once a macro is undefined, an #ifdef directive on that macro will evaluate to false.
Undefines a symbol specified by <identifier> which was previously defined with a #define directive.
macro_definition: The name of the macro which will be removed by the preprocessor.
Example:
/**
* C program to define, undefine and redefine a macro
*/
#include <stdio.h>
// Define PI
#define PI 3.14
int main()
{
printf("Value of PI: %f\n", PI);
// Undefine PI
#ifdef PI
#undef PI
#endif
// Redefine value of PI
#define PI 3.14159
return 0;
}
Output:
Value of PI: 3.140000
Value of PI after redefinition: 3.141590
#include
We use #include directive to include contents of another file (especially header file's) to a program.
We can include a file in two different ways.
#include <file.h>
This variant of including header file, searches header file in the "standard header file directory".
Standard header file directory is the path where all header files are stored.
Syntax:
#include <header.h>
Example:
#include <stdio.h>
#include<math.h>
#include "file"
We use this variant of including file when we want to include our own/custom header file. It
searches the file in the current directory and then in the standard header file’s directory.
Syntax:
#include "path_to_header_file";
Ex:
#include “myheader.c”
18 Explain how pre-processor directives can be used for defining macros with suitable examples.
Ans:
A macro definition command associates a name with a sequence of tokens. The name is called
the macro name and the tokens are referred to as the macro body.
#define CIRCLE_AREA( x ) PI * ( x ) * ( x )
would cause
area = CIRCLE_AREA( c + 2 );
to become
area = 3.14159 * c + 2 * c + 2;
19 Define conditional compilation. Explain different conditional compilation directives with examples.
Ans:
CONDITIONAL COMPILATION
In C, a programmer can instruct the preprocessor whether or not to include certain section of the
code. This is accomplished using conditional directives.
#ifdef macro
Stmt1;
Stmt2;
#endif
If macro has been #defined, the block of code will be processed as usual; otherwise not.
These are similar to if statements in syntax and usage. However, unlike if statements which are
executed during runtime, the conditional directives are executed before compilation by the
preprocessor.
These directives are used whenever there is a need to compile a portion of the program
conditionally. It is also known as conditional compilation.
It allows us to control the compilation process by including or excluding statements.
Cast expressions, size of, enumeration constants cannot be evaluated in preprocessor
directives.
Its structure similar to if statement.
Syntax
#if expression1
code to be included for true
#elif expression2
code to be included for true
#else
code to be included false
#endif
The most common conditional directive #ifdef (spelt as if-defined) verifies if a given identifier is
defined or not.
The syntax for its usage is :#ifdef identifier or #if defined (identifier).
The source code following #ifdef will be compiled only if the given identifier is defined either in the
code or if it is provided as a compilation option as -Didentifier_name .
The opposite of #ifdef is #ifndef, which is written as #ifndef identifier or #if !defined (identifier).
Example:
Determines if symbolic constant NULL has been defined If NULL is defined, defined( NULL ) evaluates
to 1,If NULL is not defined, and this function defines NULL to be 0.
Every #if must end with #endif.
#ifdef short for #if defined( name ).
#ifndef short for #if !defined( name ).
Command Meaning
The source code following #ifdef will be compiled only if the given identifier is defined either in the
code or if it is provided as a compilation option as identifier_name .
The opposite of #ifdef is #ifndef, which is written as #ifndef identifier or #if !defined (identifier).
Ans:
#include <stdio.h>
int fact(int num);
void main()
{
int n, r, ncr_var;
Definition
Recursion is a process in which a function calls itself as a subroutine. This allows the function to be
repeated several times, since it calls itself during its execution. Functions that incorporate recursion are
called recursive functions.
Recursion is often seen as an efficient method of programming since it requires the least amount of code
to perform the necessary functions. However, recursion must be incorporated carefully, since it can lead
to an infinite loop if no condition is met that will terminate the function.
i) Base condition
ii) Recursiveness
#include<stdio.h>
#include<conio.h>
void main()
{
int f,f1,f2,n,i,res;
printf("enter the limit:");
scanf("%d",&n);
printf("The fibonacci series is:");
for(i=0;i<n;i++)
{
res=fib(i);
printf("%d\t",res);
}
}
int fib(int i)
{
if(i==0)
return 0; // Base condition
else if(i==1)
return 1;
else
return(fib(i-1)+fib(i-2)); //Recursiveness
} /
#include <stdio.h>
#include <math.h>
void main() {
long int m, n;
printf("Enter two numbers : ");
scanf("%li %li", &m, &n);
printf("A(%li, %li) = %lli\n", m, n, ackermannFun(m, n));
}
2nd Method:
#include <stdio.h>
long long int ackermann(long long int m, long long int n)
{
if (!m) return n + 1;
if (!n) return ackermann(m - 1, 1);
return ackermann(m - 1, ackermann(m, n - 1));
}
int main()
{
long long int m, n;
for (m = 0; m <= 4; m++)
for (n = 0; n < 6 - m; n++)
printf("A(%lld, %lld) = %lld\n", m, n, ackermann(m, n));
return 0;
}
Output:
A(0, 0) = 1
A(0, 1) = 2
A(0, 2) = 3
A(0, 3) = 4
A(0, 4) = 5
A(0, 5) = 6
A(1, 0) = 2
A(1, 1) = 3
A(1, 2) = 4
A(1, 3) = 5
A(1, 4) = 6
A(2, 0) = 3
A(2, 1) = 5
A(2, 2) = 7
A(2, 3) = 9
A(3, 0) = 5
A(3, 1) = 13
A(3, 2) = 29
A(4, 0) = 13
Approach:
Input : 2
Output : Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C
Input : 3
Output : Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C
A recursive algorithm for Tower of Hanoi :
START
Procedure Hanoi(disk, source, dest, aux)
IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF
END Procedure
STOP
#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main(){
int i, count, number[25];
printf("Enter some elements (Max. - 25): ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("The Sorted Order is: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
Output:
Enter some elements (Max. - 25): 5
Enter 5 elements: 2 1 5 4 3
The Sorted Order is: 1 2 3 4 5
6. What is pointer? Illustrate with a sample code. What are its merits and demerits?
Ans:
A pointer is a variable which contains the address in memory of another variable. We can have a
pointer to any variable type. The ampersand operator & gives the “address of a variable”. The
indirection or dereference operator * gives the “contents of an object pointed to by a pointer”.
int *ptr;
where *ptr is a pointer of int type.
A Program to display the value of an int variable through pointer is listed below
#include<stdo.h>
void main()
{
int k;
int *ptr;
k=10;
ptr=&k;
printf("\n Value of k is %d\n\n",k);
printf("%d is stored at addr %u\n",k,&k);
printf("%d is stored at addr %u\n",*ptr,ptr);
*ptr=25;
printf("\n Now k = %d\n",k);
}
Output of the program is:
Value of k is 10
10 is stored at addr 65524
10 is stored at addr 65524
Now k=25.
Demerits of Pointers:
1. If sufficient memory is not available during runtime for the storage of pointers, the program may
crash.
2. If the programmer is not careful and consistent with the use of pointers, the program may crash.
3. Direct access to memory means you can do things that perhaps you should not. Sometimes
unintentionally (or intentionally) access to memory that is not yours, you could overwrite critical
memory, modify the code of a running application, or cause your application or another
application to behave or exit unexpectedly.
8. With suitable code snippets, explain the different arithmetic operations that can be
performed with pointers in C.
(See Notes)
Like normal variables, pointer variables can be used in
expressions. Ex: x= (*p1) + (*p2);
C language allows us to add integers to pointers and to subtract integers from pointers
Ex: If p1, p2 are two pointer variables then operations such as p1+4, p2 - 2, p1 - p2
can be performed.
Let us assume the address of p1 is 1002. After using p1=p1+1, the value becomes
1004 but not 1003.
Thus when we increment a pointer, its values is increased by length of data type that
points to. This length is called scale factor.
9. How parameters are passed using call by reference? Explain with suitable example code
snippets.
Ans:
Pass by reference or sending the addresses of the arguments- the addresses of actual arguments in the
calling function are copied into formal arguments of the called function.
Using these addresses we are actually working on actual argument so changes will be reflected in the
calling function. This technique of passing arguments is called pass by reference, illustrated by following
example.
#include<stdio.h>
void main()
{
int i=10,j=20;
printf("The values before swap is i: %d, j:%d\n",i,j);
swapr(&i,&j);
printf("The values after swap is i: %d, j:%d\n",i,j);
}
swapr(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
11. Describe in detail the different dynamic memory handling functions with example.
Ans:
malloc( ): It is a memory allocation function that allocates requested size of bytes and returns a pointer to
the first byte of the allocated space. The malloc function returns a pointer of type void so we can assign it
to any type of pointer. It takes the the following form:
x=(int *) malloc(10 *sizeof(int)) means that a memory space equivalent to 10 times the size of an int byte
is reserved and the address of the first byte of memory allocated is assigned to the pointer x of int type.
The malloc function can also allocate space for complex data types such as structures. For example:
ptr= (struct student*) malloc(sizeof (struct student)); where ptr is a pointer of type struct student.
calloc( ): It is another memory allocation function that allocates space for an array of elements, initializes
them to zero and then returns a pointer to the memory. This function is normally used for requesting
memory space at run time. It takes the following form:
This statement allocates contiguous space for n blocks, each of size element-size bytes.
realloc( ): realloc is a memory allocation function that modifies the size of previously allocated space.
Sometime it may happen that the allocated memory space is larger than what is required or it is less than
what is required. In both cases, we can change the memory size already allocated with the help of the
realloc function known as reallocation of memory. For example, if the original allocation is done by
statement
ptr= malloc(size);
ptr=realloc(ptr,newsize); which will allocate a new memory space of size newsize to the pointer variable
ptr and returns a pointer to the first byte of the new memory block.
13. Explain the process of representing 1D arrays using pointers using suitable code snippets.
Ans:
14.
15. Explain the process of represeting 2D arrays using array of pointers through appropriate code
snippets.
Ans:
16. Write a program to find the sum of elements of 1D integer array by using Dynamic Memory
Allocation.
Ans:
#include<stdio.h>
#include<stdlib.h>
void main() {
int *p, n, i, sum=0;
printf("Enter No.of array elements : ");
scanf("%d", &n);
p=(int *) malloc(n * sizeof(int));
printf("Enter %d Elements : ",n);
for(i=0;i<n;i++)
scanf("%d",(p+i));
printf("The elements in the array are : ");
for(i=0;i<n;i++){
printf("%d ",*(p+i));
sum+=*(p+i);
}
printf("\nSum of the Array elements is : %d\n", sum);
}
Output:
NULL Pointer
NULL Pointer is a pointer which is pointing to nothing. In case, if we don’t have address to be assigned
to a pointer, then we can simply use NULL.
#include <stdio.h>
int main()
{
// Null Pointer
int *ptr = NULL;
Important Points
Void pointer is a specific pointer type – void * – a pointer that points to some data location in storage,
which doesn’t have any specific type. Void refers to the type. Basically the type of data that it points to is
can be any. If we assign address of char data type to void pointer it will become char Pointer, if int data
type then int pointer and so on. Any pointer type is convertible to a void pointer hence it can point to any
value.
Important Points
void pointers cannot be dereferenced. It can however be done using typecasting the void pointer.
Pointer arithmetic is not possible on pointers of void due to lack of concrete value and thus size.
Example:
#include<stdlib.h>
int main()
{
int x = 4;
float y = 5.5;
return 0;
}
Output:
Integer variable is = 4
Float variable is= 5.500000
18. Explain about CONSTANT POINTER & POINTER TO CONSTANT VARIBLE with example.
Ans:
1) Constant Pointers :
These type of pointers are the one which cannot change address they are pointing to. This means suppose
there is a pointer which points to a variable (or stores the address of that variable). Now if we try to point
the pointer to some other variable (or try to make the pointer store address of some other variable), then
constant pointers are incapable of this.
int *const ptr; ( the location of 'const' make the pointer 'ptr' as constant pointer)
Example
Constant Pointer
#include<stdio.h>
int main(void)
{
int a[] = {10,11};
int* const ptr = a;
*ptr = 11;
ptr++;
printf("\n Address pointed by ptr : [%p]\n",(unsigned int*)ptr);
return 0;
}
int main(void)
{
int a = 10;
const int* ptr = &a;
*ptr = 11;
return 0;
}
Now, when the above code is compiled, the compiler complains :
A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. There
are three different ways where Pointer acts as dangling pointer.
1. De-allocation of memory
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int));
2. Function Call
// The pointer pointing to local variable becomes dangling when local variable is not static.
#include<stdio.h>
int *fun()
{
// x is local variable and goes out of scope after an execution of fun() is over.
int x = 5;
return &x;
}
// Driver Code
int main()
{
int *p = fun();
fflush(stdin);
Output:
A garbage Address
The above problem doesn’t appear (or p doesn’t become dangling) if x is a static variable.
20. Explain unreferenced memoy problem, memory leak with suitable examples.
Ans:
Dangling pointer is a pointer which points to a memory that has been freed or deallocated. Such a pointer
still points to the memory location of the deallocated memory, accessing such memory might cause
segmentation fault error.
In simple terms, a pointer pointing to a non-existing memory location is called a dangling pointer.
example:
void main() {
int *p = (int *) malloc(sizeof(int)); // allocating heap memory
....
free(p); // after deallocating the heap memory, *p now becomes a dangling pointer
*p = 12; // trying to access non-existing memory location can result in error
}
Example 2:
void main() {
int *q;
int *p = (int *) malloc(sizeof(int)); // allocating heap memory
q = p; // store the address containing in p to q i.e., p and q are referring the same heap memory
free(q); // after deallocating the heap memory through q
*p = 12;
// trying to access non-existing memory location through p which is also a dangling pointer, can result in
an error
}
Memory Leaks
Memory leak occurs when programmers create a memory in heap and forget to delete it. Memory leaks
are particularly serious issues for programs like daemons and servers which by definition never terminate.
A memory leak reduces the performance of the computer by reducing the amount of available memory.
A memory leak is that memory which hasn't been freed and there is usually no way to free it anymore.
This can result when a pointer which was the only reference to a memory location (that was dynamically
allocated and not freed) now points somewhere else.
example:
void main() {
int *p = (int *) malloc(sizeof(int)); // allocating heap memory
*p = 12;
printf("The given value = %d\n",*p);
*p = (int *) malloc( 3 * sizeof(int));
// allocating a new memory, the previously allocated memory results in a memory leak
}
1 Illustrate how to define and initialize structure datatype. Also illustrate how to access structure
elements.
Ans:
We can define a structure with struct key word. It can be defined in two ways.
Method 1:
struct structure-tag {
data_type structure member_1;
data_type structure member_2;
data_type structure member_3;
….
….
data_type structure member_n;
};
struct structure-tag structure_variable1, structure_variable2, ….structure_variablen;
Method 2:
struct structure-tag {
data_type structure member_1;
data_type structure member_2;
data_type structure member_3;
….
….
data_type structure member_n;
} structure_variable_1, structure_variable_2, ….structure_variable_n;
Example 1:
struct student {
int no;
char name[30];
float fee;
} s1;
We can access the structure elements by using dot (.) operator. If the member (element) is a pointer
type, then we have to use arrow (->)operator.
Example for above s1 structure variable is initialized at the time of declaration like bellow:
struct student {
int no;
char name[30];
float fee;
} s1={101, “Raju”,25000};
We cannot compare two structure variables directly bu using equality (==) operator. We have
compare each element in both the structure variables even though they are of same type.
Example Program:
struct employee{
int number;
int sal;
};
#include<stdio.h>
void main()
{
int x;
if(x == 1)
{
printf("\nEmployee1 and employee2 are same\n\n");
printf("%d %d\n", e1.number,e2.sal);
}
else
printf("\nEmployee1 and Employee2 are different\n\n");
Output
Employee1 and Employee2 are different
3 Define nested structure? Write a C program to print the details of college(College ID, College
Name) and student(Student No, Name, Marks) by embedding student structure in college
structure.
Ans:
Nested structure in C is nothing but structure within structure. One structure can be declared inside
other structure as we declare structure members inside a structure.
Ex:
struct student {
int sno;
char sname[30];
struct date {
int day;
int month;
int year;
} doa;
};
Otherwise we can declare two structures separately and we can insert other structure as a member of
the current structure.
Ex:
struct date {
int day;
int month;
int year;
};
struct student {
int sno;
char sname[30];
struct date doa;
};
The structure variables can be a normal structure variable or a pointer variable to access the data.
Structure within structure in C using normal variable
Structure within structure in C using pointer variable
Program:
#include <stdio.h>
#include <string.h>
struct college
{
int cid;
char cname[30];
struct student
{
int sid;
char sname[20];
int smarks;
}s;
};
void main()
{
struct college c = {33, "MVGRCE", {501,"Ravi",450}};
printf("College Id is: %d\n", c.cid);
printf("College Name is: %s\n\n", c.cname);
printf("Student Id is: %d\n\n", c.s.sid);
printf("Student Name : %s\n",c.s.sname);
printf("Student Marks: %d\n",c.s.smarks);
}
output:
College Id is: 33
College Name is: MVGRCE
4 Write a C program which reads n students data and print the details of the students who are
passed.
Ans:
#include<stdio.h>
struct student {
int no;
char name[30];
int marks;
char res;
}s[10];
void main() {
int n,i;
printf("Enter No. of students : ");
scanf("%d", &n);
printf("Enter %d student details : \n",n);
for(i=0;i<n;i++){
printf("Enter Student no, name and marks : ");
scanf("%d %s %d",&s[i].no, s[i].name, &s[i].marks);
if(s[i].marks<40)
s[i].res='F';
else
s[i].res='P';
}
printf("Student Details are : \n");
printf("Sno\tSname\tMarks\tResult\n");
for(i=0;i<n;i++)
printf("%d\t%s\t%d\t%c\n",s[i].no,s[i].name,s[i].marks,s[i].res);
}
Output:
Enter No. of students : 2
Enter 2 student details :
Enter Student no, name and marks : 101 rahul 45
Enter Student no, name and marks : 102 renuka 33
Student Details are :
Sno Sname Marks Result
101 rahul 45 P
102 renuka 33 F
5 Explain how the structure variable passed as a parameter to a function with example
Ans:
Structure variables can be passed to passed to any function like array variables, i.e., we can pass
the structures to functions in two ways.
Passing structure to a function by value
Passing structure to a function by address(reference)
No need to pass a structure – Declare structure variable as global
Example:
Either 1st method or 2nd method 5 Marks
Example Program:
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}
Like a pointer variable of any primitive data type, a pointer can also be declared as a structure variable
using the following syntax:
A structure pointer variable is capable of storing address of a structure variable. Once a pointer is
declared to a structure, members of that structure are accessed in two ways.
Using -> operator
Using *. Operator
#include <stdio.h>
struct account {
char name[20];
int acc_no;
float balance;
};
void main() {
struct account acc, *p;
p = &acc;
printf("Enter the name of account holder : ");
scanf("%s", p->name);
printf("Enter the account number : ");
scanf("%d", &p->acc_no);
printf("Enter the balance : ");
scanf("%f", &p->balance);
printf("The given account details are...\n");
printf("Name: %s\nAccount number: %d\nBalance: %f\n", (*p).name, (*p).acc_no, p->balance);
}
Output:
Enter the name of account holder : ravi
Enter the account number : 101
Enter the balance : 1000
The given account details are...
Name: ravi
Account number: 101
Balance: 1000.000000
7 Describe a self-referential structure and explain through code example in what context a self-
referential structure is necessary.
Ans:
A structure definition which includes at least one member as a pointer to the same structure is
known as self-referential structure.
It can be linked together to form useful data structures such as lists, queues, stacks and
trees. It is terminated with a NULL pointer .
struct tag_name
{
Type1 member1;
Type2 member2;
……….
struct tag_name *next;
};
Ex:-
struct node
{
int data;
struct node *next;
} n1, n2;
Example code
#include <stdio.h>
struct node {
int data;
struct node *next;
};
void main() {
struct node n1, n2;
printf("Enter an integer for first structure variable : ");
scanf("%d", &n1.data);
printf("Enter an integer for second structure variable : ");
scanf("%d", &n2.data);
n1.next = &n2;
n2.next = NULL;
printf(" %d --> %d\n", n1.data, n1.next->data);
}
Output:
Enter an integer for first structure variable : 10
Enter an integer for second structure variable : 20
10 --> 20
8 Write a short notes on typedef and show its usage in structure data type with a program.
Ans:
By using typedef keyword, we can define an alias of the structure.
typedef struct{
members_declarations;
}structure_tag;
structure_tag structure_name;
Here there is no need to use struct keyword while declaring its variable.
typedef struct {
char name[30];
int age;
}employee_str;
int main()
{
employee emp;
strcpy(emp.name, "Rahul B");
emp.age = 25;
printf("Employee detail:\n");
printf("Name: %s\n",emp.name);
printf("Age: %d\n",emp.age);
return 0;
}
Output:
Employee detail:
Name: Rahul B
Age: 25
Union definition:
Union is similar to structure, but the memory allocation is different to structure. The structure size is
collection all structure members size. But for union the largest element of union member’s size is
allocated to the union variable.
struct student {
int a;
float b;
char ch;
} s; // size of the s is 9 bytes
union student {
int a;
float b;
char ch;
} u; // size of the u is 4 bytes
We can initialize and access union members member by member Where as in structure we can initialize
and access all the variables at once.
Initializing Unions:
Union enables us to treat the same space in memory as a number of different variables. We can
define a union member as union item item1;
We cannot assign different values to the different union elements at the same time.
We can do u.a=5;
or
u.b=5.5;
or
u.ch=’A’;
10 Write a C program to read and print a date using dd/mm/yyyy format using bit-fields and
differentiate the same without using bit-fields
Ans:
#include<stdio.h>
struct date1{
unsigned int day;
unsigned int month;
unsigned int year;
}doj={24,10,2019};
struct date2{
unsigned int day:5;
unsigned int month:5;
unsigned int year:22;
}doa={10,12,1998};
void main() {
Output:
Date of Join = 24-10-2019
Date of admission = 10-12-1998
Size of the date1 using Structure without bitfields = 12
Size of the date2 using Structure with bitfields = 4
We can observe that the structure with bit fields take less space compare to normal structure.
In order to perform the basic file operations C supports a number of functions .Some of the
important file handling functions available in the C library are as follows :
fopen():
Ex:
FILE *fp;
fp=fopen(“a.txt”,”r”);
Available modes are: r, w, a, r+,w+, a+ for text files and rb, wb, ab, rb+,wb+, ab+ for binary
files.
fclose() :
The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using library function fclose().
example:
FILE *fp;
fp = fopen("sample.txt", "r");
ch= getc(fp);
Here, a single character is read from the file with logical name fp. That character is assigned to character
variable ch.
putw()
We can write integers using putw().
The function putw() is used to write an integer value to the file pointed by the file pointer.
The syntax of putw() is:
putw(int number, FILE *fp);
The putw() function takes two arguments, first is an integer value to be written to the file and second is
the file pointer where the number will be written.
Example:
FILE *fp;
int number;
fp = fopen("sample-numbers1.txt","w");
printf("Enter numbers up to 0 : ");
scanf("%d",&number);
while (number != 0) {
putw(number,fp);
scanf("%d",&number);
}
putw(number,fp);
fclose(fp);
fp = fopen("sample-numbers1.txt", "r");
printf("The given numbers are : ");
while ((number = getw(fp)) != 0) {
printf("%d ",number);
}
fclose(fp);
fcloseall()
Sometimes we open multiple files for processing then it is tedious task to close all the open streams one
by one after usage. C provides powerful feature to close all the open streams using single method.
fcloseall() : Does not closed following Streams
1 stdin Standard Input Stream
fopen("ONE.txt","w");
fopen("TWO.txt","w");
streams_closed = fcloseall();
if (streams_closed == EOF)
printf("Error");
else
printf("%d Streams Were Closed", streams_closed);
return 0;
}
Output :
2 Streams Were Closed
13 Define File? How do you declare a file? Explain different modes of operations on files with
examples.
Ans:
In C programming, file is a place on your physical disk where information is stored.
We have to declare a file pointer with FILE data structure.
Ex:
FILE *fp;
fp=fopen(“a.txt”,”r”);
wb Open for writing in binary mode. If the file exists, its contents are overwritten.
If the file does not exist, it will be created.
Open for both reading and writing in If the file does not exist, fopen() returns
rb+
binary mode. NULL.
Open for both reading and writing in If the file exists, its contents are overwritten.
wb+
binary mode. If the file does not exist, it will be created.
fclose(fp);
}
Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.
When you open those files, you'll see all the contents within the file as plain text. You can easily edit or
delete the contents.
They take minimum effort to maintain, are easily readable, and provide least security and takes bigger
storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security than text
files.
Text File Binary File
In text file 500 takes as 3 bytes as it having 3 In binary file 500 taken as integer and takes
characters only 2 bytes
Newline is the end of the line or line ending In a binary file, no such conversions take
or line break. It is usually a special character place.
which signifies the end of the line. A newline
character in a text file is first converted into
a carriage return-linefeed combination and
then written to the disk.
For (EOF), In the text mode, a special This is not the case in binary mode. In the
character with the ASCII code 26 is inserted binary mode, we do not have any special
at the end of the file. This character when character to signify the EOF. It keeps track
encountered returns the EOF signal to the with the help of the number of characters
program. present in the directory entry of the file.
16 What is binary file and explain operations performed on binary files.
Ans:
There are functions provided by C libraries to seek, read, and write to binary files. Let's explain this by reading
and writing a structure called rec in a binary file. The structure is defined like this:
This statement reads 'a' bytes (in this case, it's the size of the structure) from the file into the memory
address &myRecord. Here the number 1 denotes the number of blocks of 'a' bytes to be read. If we change it
to 10, then it denotes 10 blocks of 'a' bytes will be read and stored into &myRecord. ptr is the pointer to the
location of the file that is being read.
Now the fwrite() function is used to write to a binary file, like so:
In this example, the value inside the address &myRecord which is of the size of the structure record is written
into the file with the help of the file pointer ptr.
1. #include<stdio.h>
2. /* Our structure */
3. struct record
4. {
5. int a,b,c;
6. };
7. int main()
8. {
9. int count;
10. FILE *ptr;
11. struct record myRecord;
12. ptr=fopen("test.bin","rb");
13. if (!ptr)
14. {
15. printf("Unable to open file!"); return 1;
16. }
17. for ( count=1; count <= 10; count++)
18. {
19. fread(&myRecord,sizeof(struct record),1,ptr); printf("%d\n",myRecord.a);
20. } fclose(ptr);
21. return 0;
22. }
In this example, we tried to read each structure from the binary file using the fread() function. This reads the
structure one byte at a time and stores it inside the address myRecord. Let's now look at an example using
fwrite().
If we open the file with a file pointer fp, the pointer points to beginning character of the file i.e ‘H’
ftell(fp) gives the position from the beginning of the file pointer.
Similarly fread() and fwrite() are also useful in to read and write block of data from files i.e., we can
access record by record.
Output:
Enter text to store '@' to end..abcdefghij12345@
Enter how many last charcters to be printed : 5
Last 5 characters in the file are : 12345
19 Show with example and explain in detail the concept of command-line arguments and how and
when they can be used.
Ans:
We can also give command-line arguments in C. Command-line arguments are given after the name of
the program in command-line shell of Operating Systems.
To pass command line arguments, we typically define main() with two arguments : first argument is the
number of command line arguments and second is list of command-line arguments.
or
argc (Argument Count) is int and stores number of command-line arguments passed by the user
including the name of the program. So if we pass a value to a program, value of argc would be 2 (one for
argument and one for program name)
#include <stdio.h>
#include<math.h>
int main(int argc, char *argv[]) {
if (argc != 5) {
printf("Arguments passed through command line are not equal to 4\n");
return 1;
}
printf("Student name : %s\n", argv[1]);
printf("Subject-1 marks : %s\n", argv[2]);
printf("Subject-2 marks : %s\n", argv[3]);
printf("Subject-3 marks : %s\n", argv[4]);
int sum;
sum = atoi(argv[2]) + atoi(argv[3]) + atoi(argv[4]);
printf("Total marks : %d\n", sum);
return 0;
}
Output:
Student name : Anil
Subject-1 marks : 45
Subject-2 marks : 40
Subject-3 marks : 45
Total marks : 130
20 Write a C program to copy the contents of one file into another file using command line
arguments.
Ans:
#include<stdio.h>
int main(int argc,char *argv[])
{
FILE *fs,*ft;
int ch;
if(argc!=3)
{
printf("Invalide numbers of arguments.");
exit(1);
}
fs=fopen(argv[1],"r");
if(fs==NULL)
{
printf("Can't find the source file.");
exit(1);
}
ft=fopen(argv[2],"w");
if(ft==NULL)
{
printf("Can't open target file.");
fclose(fs);
exit(1);
}
while((ch=getc(fs))!=EOF)
{
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
return 0;
}