Sunteți pe pagina 1din 88

1

C Programming Language

Unit-1

Short Question:

Q:1What are Keywords in C?


Ans:Keywords are preserved words that have special meaning in C language. The
meaning of C language keywords has already been described to the C compiler. These
meaning cannot be changed. Thus, keywords cannot be used as variable names
because that would try to change the existing meaning of the keyword, which is not
allowed.

There are total 32 keywords in C language.

auto double int struct

break else long switch

case enum register typedef

const extern return union

char float short unsigned

continue for signed volatile

default goto sizeof void

do if static while
2

Q: 2 What are Identifiers?

Ans: In C language, identifiers are the names given to variables, constants, functions
and user-define data. These identifier are defined against a set of rules.

Rules for an Identifier :

1. An Identifier can only have alphanumeric characters(a-z , A-Z , 0-9) and


underscore(_).
2. The first character of an identifier can only contain alphabet or underscore.
3. Identifiers are also case sensitive in C.
4. Keywords are not allowed to be used as Identifiers.
5. No special characters, such as semicolon, whitespaces, slash or comma are
permitted to be used in or as Identifier.

For example:intmyvariable = “studytonight” ;

Here myvariable is the name or identifier for the variable which stores the value
"Studytonight" in it.

Q:3 What do you mean by Character set in C language.


Ans: Character Set: A character denotes any alphabet,digit or special symbol which
is used to represent information.
In C language characters are grouped into the following categories:-

1. Letters(all alphabets a to z & A to Z).


2. Digits (all digits 0 to 9).
3. Special characters(such as colon :, semicolon ;, underscore _, ampersand & etc).
3

------------------------------------------------------------------------------------------

Q:4 What do you mean by variable and constant ?

Ans: The alphabets, numbers and special symbols when properly combined form
constants and variables.

Constants: A constant is a quantity that does not change. This quantity can be stored
in the memory of the computer. A constant is always a fixed value, which we can not
change.

Variable: A variable is the name given to the location in memory where this constant
is stored. The content of the variable can change but variable in itself can not change.

For example: in the equation:

3x + y = 20

Since 3 and 20can not change. So, they are called as constant. And the quantities x &
y can change. So, these are called as variable.

-------------------------------------------------------------------------------------------

Q:5 What is the use of scanf() and printf() function ?

Ans:scanf() and printf() function:

The standard input-output header file, named stdio.h contains the definition of the
functions printf()and scanf(), which are used to display output on screen and to take
input from user respectively.

printf() function returns the number of characters printed by it. %d inside the printf()
is known as format string and this informs the compiler, what type of output to
expect.

scanf() returns the number of characters read by it. %d inside the scanf() is known
as format string and this informs the scanf() function, what type of input to expect
4

----------------------------------------------------------------------------------

Q: 6 What do you mean by Assignment Statement?

Ans: Assignment Statement: When we use assignment operator in some expression


and we use that expression in our program code then that is called as Assignment
statement.

For example:

a+=b is an assignment expression and it can be written as a=a+b.

a-=b is an assignment expression and it can be written as a=a-b.

a*=b is an assignment expression and it can be written as a=a*b.

a/=b is an assignment expression and it can be written as a=a/b.

---------------------------------------------------------------------------------------------

Q:7 What do you mean by Symbolic Constant:


Ans: A symbolic constant is name that substitute for a sequence of character that
cannot be changed. The character may represent a numeric constant, a
characterconstant, or a string. When the program is compiled, each occurrence of
asymbolic constant is replaced by its corresponding character sequence.

A symbolic constant is an "variable" whose value does not change during the entire
lifetime of the program.

A symbolic constant is declared as follows: #define symbolic_name value of


constant.
Examples of symbolic constant:
#define Pl 3.14159.

------------------------------------------------------------------------------------------
5

Q:8 What do you mean by Operator hierarchy and Associativity in C


programming language?

Ans: Operator hierarchy or Precedence in C:


If we have more than one operator in an expression then the operator having high
priority will ne processed first.Operator precedence determines which operator is
evaluated first when an expression has more than one operators.

For example: 100-2*30 would yield 40, because it is evaluated as 100 – (2*30) and
not (100-2)*30. The reason is that multiplication * has higher precedence than
subtraction(-).

List of operator hierarchy:-

Associativity in C :
Associativity is used when there are two or more operators of same precedence or
priority is present in an expression.

For example: multiplication and division arithmetic operators have same


precedence, lets say we have an expression 5*2/10, this expression would be
evaluated as (5*2)/10 because the associativity is left to right for these operators.
6

-----------------------------------------------------------------------------------------

Q:9Difference between Variable and Identifier?


Ans: An Identifier is a name given to any variable, function, structure, pointer or any
other entity in a programming language. While a variable, is a named memory
location to store data which is used in the program.

Identifier Variable

Identifier is the name given to a While, variable is used to name a


variable, function etc. memory location which stores data.

An identifier can be a variable, but not All variable names are identifiers.
all indentifiers are variables.

------------------------------------------------------------------------------------
7

Long Question:

Q:1 Describe in detail how C language evolve and came into existence. What are
the various C standards ?

Ans: Overview of C Language


C is a structured programming language developed by Dennis Ritchie in 1973 at Bell
Laboratories. It is one of the most popular computer languages today because of its
structure, high-level abstraction, machine independent feature etc.
C language was developed to write the UNIX operating system, hence it is strongly
associated with UNIX, which is one of the most popular network operating system in
use today.

History of C language:
8

Cpl (Combined Programing Language): It was based on Algol 60. to which it made
many important additions applicable. CPL language was made for research in both
programming concepts & the design of compilers.
It has never been fully implemented because of its size & complexity.

BCPL( Basic Combined Programing Language):After CPL, BCPL came into


existence. It was developed as a reduced version of CPL. It is used to write a compiler
for the bigger language. It includes program with simple syntax & design. In this
language, one data type serve as an integer, character, floating point number etc.
It is a type less language.

B Language: After BCPL, B language was developed. It is recursive & machine


independent application such as system software. But it was still a type less language.

C Language:It came after B language. So, the name was chosen as C Language. It
was developed by Dennis Ritchie at AT& T bell Lab in 1973.The idea behind creating
C language was to create an easy language which requires a simple compiler and
enables programmers to efficiently interact with the machine/system, just like
machine instructions.
The C programming language features were derived from an earlier language called
B , BCPL. BCPL and B are "type less" languages whereas C provides a variety of
data types. It uses many concepts from these languages while introduced many new
concepts such as data types, structure, pointer etc.

 Afterwards,American National Standards Institute (ANSI) established a


committee to provide a modern, definition of C. The“ANSI C”, was completed
late 1988. In 1989, the language was formalised by American National
Standard Institute(ANSI).

 In 1990, a version of C language was approved by the International Standard


Organisation(ISO) and that version of C is also referred to as C89.
9

C PROGRAMMING LANGUAGE STANDARDS OR VERSION:

 C89/C90 standard – First standardized specification for C language was


developed by the American National Standards Institute in 1989. C89 and C90
standards refer to the same programming language.
 C99 standard – Next revision was published in 1999 that introduced new
features like advanced data types and other changes.

 C11 standard adds new features to C programming language and library like
type generic macros, structures, multi-threading and bounds-checked functions.

---------------------------------------------------------------------------------------------

Q:2 What are the features of C programming Language ? And discuss


the importance of C Language.

Ans: C is a structured programming language developed by Dennis Ritchie in 1973


at
Bell Lab.

Features of C language:

C language is one of the powerful language. The various features of C language are as
follows:-

o Fast and Efficient:Programs written in C language are efficient, fast. Program


written in C are efficient due to several variety of data types and powerful
operators.

o Easy Syntax:Mostly people use C programming language because it is easy to


learn and understand.

o Portable: C is portable language; this means that C programs written for one
computer system can be run on another system, with little or no modification.
10

o Structured Programming: C language is well suited for structured programming,


this requires user to think of a problems in terms of function or modules or block.
A collection of these modules make a program debugging and testing easier.

o Robust: It is robust language whose rich setup of built in functions and operator
can be used to write any complex program.

o Ease of Modification:You can easily run a C program in any computer with little
change.

o Ability to extend:Another important feature of C program, is its ability to extend


itself.A C program is basically a collection of functions that are supported by C
library. We can also create our own function and add it to C library.

o The C compiler combines the capabilities of an assembly language with the feature
of high level language. Therefore it is well suited for writing both system software
and business package.

o C language is the most widely used language in operating systems and embedded
system development today.

Importance of C:
11


Operating system is one of the very important thing in any device and most
of the Operating systems developed by with the help of C language because
it produces code that runs nearly as fast as code written in any assembly
language.

 Maximum devices which we use in daily life there functionality also


developed by C language.

 Programs written in C language takes very less time to execute and almost
executes at the speed of assembly language instructions.
 Initially C language was mainly used for writing system level programs, like
designing operating systems, but there are other applications as well which
can be very well designed and developed using C language, like Text
Editors, Compilers, Network Drivers etc.

------------------------------------------------------------------------------------------------------------------------

Q:3 Describe the Structure of a C Program.

Ans: Structure of C:

 C is a case sensitive language so all C instructions must be written in lower case


letter.
 First of all, we have to include the header files in C program.
 Then there is a main function, from where the program execution will begin.
 Within curly brace we have to provide C statement.
 If we are using any variable in our program, then we have to declare the variable
in the main function. Declaration of variable includes its datatype, which tells
about the type of data it contains.
12

 Then we can use program statements and all C statement must end with a
semicolon.

For Example:

# (hash): It is used to point out lines in a program that are not program statements but
Pre-Processor Directives.

include: Itwill add additional code to your program that help you. include is a
preprocesser directive, as the word itself suggests. It is used to tell the compiler to
include all the functions, and stuff from a header file. Pre-Processor Directives are
executed before the actual compilation of code begins.
stdio.h: We use stdio.hso that compiler come to now that you are going to use
function such as ( printf , scanf ,....etc ) all of this functions are define in that library
as you define main in your program
13

console.h: This header declares several useful library functions for performing
"console input and output" from a program. Some of the most commonly used
functions of conio.h are clrscr, getch, getche
void main(): main() is the main function of c from where execution of c program
starts. & void main() means it does not have return type. That means it does not return
anything.

Printf() : Printf() function is used to to print formatted output onto the screen.

Scanf() function: It is a builtin library function of c. it is stored in c library.scanf


stands for "scan format", because it scans the input for valid tokens and parses them
according to a specified format.

Use of & :If an input need an address to reach the location then we use ampersand.
The ampersand is a reference parameter. It passes a reference to the argument. Or its
is a address parameter.

Use of getch():It is used to hold the output screen until you hit a character . It is used
to catch a character from the keyboard. And that character would not be seen in the
output screen.

---------------------------------------------------------------------------------------------

Q:4 What are the various Data types used in C Language ?

Ans:

Data types in C Language:


Data types specify how we enter data into our programs and what type of data we
enter. Data type determines the type of data a variable will hold. If a variable x is
declared as int. It means x can hold only integer values. Every variable which is used
in the program must be declared as what data-type it is.
14

C language supports 2 different type of data types:

1. Primary data types:

These are fundamental data types in C like:-


 Integer (int),
 floating point (float),
 character (char)
 void

2. Derived data types:

Derived data types are nothing but primary datatypes butlittle twisted or grouped
together like:
 Array
 Structure
 Union
 pointer.

Here, we are discussing Primary Data type:

a) Integer type: Integers are used to store whole numbers. Integers are whole
numbers that can have both positive and negative values but no decimal values.
Example: 0, -5, 10

In C programming, keyword int is used for declaring integer variable.

For example:

int id;

Here, id is a variable of type integer.

Size and range of Integer type on 16-bit machine:

Type Size (bytes) Range


15

Short signed int 1 -32768 to +32767


Short unsigned int 2 0 to 65535

b) Floating point type: Floating types are used to store real numbers. Floating type
variables can hold real numbers such as: 2.34, -9.38, 5.0 etc. You can declare a
floating point variable in C by using either float or double keyword.

For example:

float balance;
double bookPrice;

Here, both Balance and bookPrice are floating type variables.

In C, floating values can be represented in exponential form as well. For example:

float normalizationFactor = 22.442e2;

Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

Float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

c) Character type: Character types are used to store characters value. Keyword char
is used for declaring character type variables.

For example:
char test = 'h';
16

Here, test is a character variable. The value of test is 'h'.

Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

d) void type: void type means no value. This is usually used to specify the type of
functions which returns nothing. We will get acquainted to this datatype as we start
learning more advanced topics in C language, like functions, pointers etc.

------------------------------------------------------------------------------------------------

Q:5 How can you declare and initialize a variable in C language? Also discuss
the
scope of a variable.

Ans: Variables in C Language


When we want to store any information(data) on our computer/laptop, we store it in
the computer's memory space. our operating system provides us with an option to
create folders, name them, so that it becomes easier for us to find it and access it.
Similarly, in C language, when we want to use some data value in our program, we
can store it in a memory space and name the memory space so that it becomes easier
to access it.
17

The naming of an address is known as variable. Variable is the name of memory


location, where our data is stored.We can change the value of a variable during
execution of a program. A programmer can choose a meaningful variable name.

Rules to name a Variable

1. Variable name must not start with a digit.


2. Variable name can consist of alphabets, digits and special symbols like
underscore _.
3. Blank or spaces are not allowed in variable name.
4. Keywords are not allowed as variable name.

Declaring, Defining and Initializing a variable:

Declaration of variables must be done before they are used in the program.
Declaration does the following things:-

1. It tells the compiler what the variable name is.


2. It specifies what type of data the variable will hold.
3. Declaration is more like informing the compiler that there exist a variable with
following datatype which is used in the program.

Defining a variable means the compiler has to now assign a memory space to the
variable because it will be used in the program.. You can directly define a variable
inside the main() function and use it.

To define a function we must provide the datatype and the variable name. We can
even define multiple variables of same datatype in a single line by using comma to
separate them.
Example:
int a;
Float b,c;
18

Initializing a variable means to provide it with a value. A variable can be initialized


and defined in a single statement, like:

Int a = 10;

Scope of a Variable: Local and Global

Scope of a variable means where the variable is available within the program.

Variable can have 2 types of scope:-

 Local

 Global

Local Variable: Local variable are defined inside a function. And the scope of local
variable is available only to certain selected statements in the program. Its scope is
restricted to the function within which it is defined.

Global Variable: Global variable are declared outside all functions. The scope of
global variable is available to all the statements in the program. It can be used by all
the functions of the program.

----------------------------------------------------------------------------------------

Q:6 What are the various operators used in C Language ?

Ans:

Operators in C Language:
C language supports a rich set of built-in operators. An operator is a symbol that tells
the compiler to perform a certain mathematical or logical manipulation. Operators are
used in programs to manipulate data and variables.
19

C operators can be classified into following types:

 Arithmetic operators
 Relational operators
 Logical operators
 Bitwise operators
 Assignment operators
 Conditional operators
 Special operators

1) Arithmetic operators:
These are the operators used to perform arithmetic/mathematical operations on
operands.C supports all the basic arithmetic operators.

The following table shows all the basic arithmetic operators.

Operator Description

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denominator

% remainder of division

++ Increment operator - increases integer value by one


20

-- Decrement operator - decreases integer value by one

2) Increment & Decrement Operators:

C Programming has two very useful operators increment (++) and decrement (–).
Increment operators are used to increase the value of variable by one and decrement
operators are used to decrease the value of the variable by one in C Programs.

Increment Operators: ++i, i++


Decrement Operators: --i , i --

Operator type Operations Description

Value of i is incremented before assigning it to


Pre increment ++i
variable i.

Post Value of i is incremented after assigning it to


i++
increment variable i.

Pre Value of i is decremented before assigning it to


–i
decrement variable i.

Post Value of i is decremented after assigning it to


i–
decrement variable i.

3) Unary Operator:
The operator which works on only one operand is known as unary operator.

For example: increment and Decrement operator , Not operator

4) Relational operators:

Relational operators are used for comparison of the values of two operands.
21

The following table shows all relation operators supported by C.

Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

5) Logical operators:
Logical Operators are used to combine two or more conditions/constraints or to
complement the evaluation of the original condition in consideration. The result of the
operation of a logical operator is a boolean value either true or false.

C language supports following 3 logical operators. Suppose a = 1 and b = 0,

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false


22

6) Bitwise operators:
The Bitwise operators is used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then calculation is performed on the
operands. The mathematical operations such as addition , subtraction , multiplication
etc. can be performed at bit-level for faster processing.
Bitwise operators perform manipulations of data at bit level. These operators also
perform shifting of bits from right to left. Bitwise operators are not applied
to float or double.

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

Now lets see truth table for bitwise &, | and ^

a b a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1
23

1 1 1 1 0

The bitwise shift operator, shifts the bit value. The left operand specifies the value to
be shifted and the right operand specifies the number of positions that the bits in the
value have to be shifted. Both operands have the same precedence.
Example :
a = 0001000
b=2
a << b = 0100000
a >> b = 0000010

7) Assignment Operators:
Assignment operators are used to assign value to a variable. The left side operand of
the assignment operator is a variable and right side operand of the assignment
operator is a value. The value on the right side must be of the same data-type of
variable on the left side otherwise the compiler will raise an error.

Assignment operators supported by C language are as follows.

Operator Description Example

= assigns values from right side operands to left side a=b


operand

+= adds right operand to the left operand and assign the a+=b is same as
result to left a=a+b

-= subtracts right operand from the left operand and a-=b is same as
24

assign the result to left operand a=a-b

*= mutiply left operand with the right operand and assign a*=b is same as
the result to left operand a=a*b

/= divides left operand with the right operand and assign a/=b is same as
the result to left operand a=a/b

%= a%=b is same as
calculate modulus using two operands and assign the a=a%b

result to left operand

8) Conditional operator:
Conditional operator is of the form Expression1 ?Expression2 : Expression3 .
Here, Expression1 is the condition to be evaluated. If the condition(Expression1)
is True then we will execute and return the result of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the result of
Expression3

Conditional Operator are :

? : Operator

The syntax of a conditional operator is :


expression1 ? expression2: expression 3

Explanation:

 The question mark "?" in the syntax represents the if part.


25

 The first expression (expression 1) generally returns either true or false, based on
which it is decided whether (expression 2) will be executed or (expression 3)
 If (expression 1) returns true then the expression on the left side of " : " i.e
(expression 2) is executed.
 If (expression 1) returns false then the expression on the right side of " : " i.e
(expression 3) is executed.

9) Ternary Operator:

Ternary operator are those operators which operates on 3 operands. So, conditional
operators are also called as Ternary operator.

10) Special operator:

Operator Description Example

sizeof Returns the size of an variable sizeof(x) return size of the variable x

& Returns the address of an variable &x ; return address of the variable x

* Pointer to a variable *x ; will be pointer to a variable x

--------------------------------------------------------------------------------------

Q:7 What is Type conversion and Type Casting. Explain in detail.


OR
What do you mean by Implicit and Explicit conversion. Explain with
example.
26

Ans: Type Conversion in C:

Type conversion or typecasting refers to changing an entity of one datatype into


another. There are two types of typeconversion: implicit and explicit.

1. Implicit Type Conversion Also known as ‘automatic type conversion’.

 Done by the compiler on its own, without any external trigger from the user.
 Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place to
avoid lose of data.
 All the data types of the variables are upgraded to the data type of the
variable with largest data type.

Example of Type Implicit Conversion:

#include<stdio.h>
int main()
{
int x = 10;

// x is implicitly converted to float

float z = x + 1.0;
printf("z = %f",z);
return0;
}

Output:

z = 11.000000
27

2. Explicit Type Conversion– This process is also called type casting.

 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

Here, type indicated the data type to which the final result is converted.

For Example:

// C program to demonstrate explicit type casting


#include<stdio.h>
int main()
{
double x = 1.2;
int sum;

// Explicit conversion from double to int

sum = (int)x + 1;
printf("sum = %d", sum);
return0;
}

Output:
28

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.

--------------------------------------------------------------------------------------------
1

C Programming
Unit-2

Short Questions:

Q:1 What is nested Loop ?


Ans: Nested Loop: A loop inside another loop is called a nested loop. ...
Consider a nested loop where the outer loop runs n times and consists of
another loop inside it. The inner loop runs m times. Then, the total number of
times the inner loop runs during the program execution is n*m.

Example of Nested For Loop:


#include <stdio.h>
#include<conio.h>
void main()
{

for (int i=0; i<2; i++)


{
for (int j=0; j<2; j++)
{
printf("%d, %d\n",i ,j);
}
}

getch();
}

Output:

0, 0
0, 1
1, 0
1, 1
2

-------------------------------------------------------------------------------

Q:2 What is Goto statement. Why it is avoided?

Ans:
goto statement:

When a goto statement is encountered in a C program, the control jumps directly


to the label mentioned in the goto statement.

Goto is avoided because: The goto statement is rarely used because it makes
program confusing, less readable and complex. Also, when this is used, the
control of the program won’t be easy to trace, hence it makes testing and
debugging difficult.

Syntax of goto statement in C:

goto label_name;
..
..
label_name: C-statements

----------------------------------------------------------------------------------

Q: 3 What is the difference between while and do while loop?


Ans: Difference between While and do while are:

 .In the while loop, first the condition is checked and then the statements in
while loop are executed whereas do while loop executes the statements
inside the body of do-while first and then check the condition.
3

 So in while loop, if a condition is false at the first place then the while
loop would not run at all whereas the do while loop would run once.

--------------------------------------------------------------------------------------

Q:4 Name the Decision Control Structure and Loop Control Structure.
Ans: Decision control structure are:
 IF
 IF Else
 Nested IF Else
 Else if
 Switch

Loop Control Structure are :


 For Loop
 While Loop
 Do While Loop

---------------------------------------------------------------------------------------
4

Long Questions:

Q:1 Explain the IF and IF Else statement with example.

Ans:

1) IF Statement:

When we need to execute a block of statements only when a given condition is


true then we use if statement.

The statements inside the body of “if” only execute if the given condition returns
true. If the condition returns false then the statements inside “if” are skipped.

Syntax:

if (condition)
{
//Block of C statements here

Example of if statement
#include <stdio.h>
#include <conio.h>

Void main()
{
int x = 10;
int y = 20;

if (x<y)
{
printf("Variable x is less than y");
}

getch();
}
5

Output:

Variable x is less than y

2) If else statement:

If condition returns true then the statements inside the body of “if” are executed
and the statements inside body of “else” are skipped.
If condition returns false then the statements inside the body of “if” are skipped
and the statements in “else” are executed.

Syntax of if else statement:

if(condition) {
// Statements inside body of if
}
else {
//Statements inside body of else
}

Example of if else statement

#include <stdio.h>
#include <conio.h>

void main()
{
int x ;
int y ;

if (x<y)
6

{
printf(" x is less than y");
}

else

printf(“x is greater than y”);

getch();
}

Output:

If user provide the value of x =10 and y=20, then output will be:

X is less than y

And suppose, if user provide the value of x=20 and y=10, then output will be:

X is greater than y

------------------------------------------------------------------------------------------------

Q:2 Explain Nested If Else statement and Else If statement with example.

Ans:
1) Nested If..else statement:

When an if else statement is present inside the body of another “if” or “else” then
this is called nested if else.
7

Syntax of Nested if else statement:

if(condition)
{
statement 1

if(condition2)
{
Statement 2
}
else
{
Statement 3
}
}

else
{
Statements 4
}

Example of nested if..else


#include <stdio.h>
#include <conio.h>

void main()
{
int x, y;
printf("Input the value of x and y");
scanf("%d %d",&x,&y);

if (x != y)
{
printf("x is not equal to y);

if (x > y)
{
printf("x is greater than y”);
}
else
8

{
printf("y is greater than x");
}
}
else
{
printf("x is equal to y");
}

getch();
}

Output:

Input the value of x:12


Input the value of y:21

x is not equal to y
y is greater than x

------------------------------------

2) Else If statement:

The else..if statement is useful when you need to check multiple conditions within
the program, nesting of if-else blocks can be avoided using else..if statement.

Syntax of else..if statement:

if (condition1)
{
Statement 1
}
else if(condition2)
{
Statement 2
}
9

else if (condition3)
{
Statement 3
}
.
.
else
{
//These statements would execute if all the conditions return
false.
}

Example of else..if statement

Lets take the same example that we have seen above while discussing nested
if..else. We will rewrite the same program using else..if statements.

#include <stdio.h>
#include<conio.h>
void main()
{
int x, y;
printf("Input the value of x and y");
scanf("%d %d",&x,&y);

if (x !=y)
{
printf("x is not equal to y");
}
else if (x > y)
{
printf("x is greater than y");
}
else if (y > x)
{
printf("y is greater than x");
}

else
{
10

printf("x is equal to y");


}

getch();
}

Output:

Input the value of x:12


Input the value of y:21

x is not equal to y

--------------------------------------------------------------------------------------

Q:3 Explain the importance of Switch case statement. In which situation use
a switch case statement is desirable. Also give its limitation.

Ans:
Switch Case Statement:

The switch case statement is used when we have multiple options and we need to
perform a different task for each option.

Syntax:

switch (variable or an integer expression)


{
case constant:
C Statement 1;

case constant:
C Statement 2;
11

default:
C Statement;

Example of Switch Case in C


#include <stdio.h>
#include<conio.h>

void main()
{
int i=2;

switch (i)
{
case 1:
printf("Case1 ");
case 2:
printf("Case2 ");
case 3:
printf("Case3 ");
case 4:
printf("Case4 ");
default:
printf("Default ");
}

getch();
}
Output:

Case2 Case3 Case4 Default

Break statement in Switch Case:

Break statements are useful when you want your program-flow to come out of the
switch body. Whenever a break statement is encountered in the switch body, the
control comes out of the switch case statement.
12

Example of Switch Case with break:

I’m taking the same above code that we have seen above but this time we are
using break.

#include <stdio.h>
#include<conio.h>

void main()
{
int i=2;

switch (i)
{
case 1:
printf("Case1 ");
break;
case 2:
printf("Case2 ");
break;
case 3:
printf("Case3 ");
break;
case 4:
printf("Case4 ");
break;
default:
printf("Default ");
}
getch();
}

Output:

Case 2

-----------------------------------------------------------------------------------------
13

Q:4 What is the purpose of For loop in C language? How is it used?

Ans:

For Loop:

A loop is used for executing a block of statements repeatedly until a given


condition returns false. For loop is constructed from a control statement that
determines how many times the loop will run and a command section. Command
section is either a single command or a block of commands.

Syntax of For Loop:

For ( initialization; test condition; increment or decrement )


{
Statement to be executed
}

In For Loop, Control statement itself has three parts:

 Initialization: This part is performed only once at for loop start. We can
initialize a loop variable here.

 Test condition: It is the most important part of the loop. Loop will
continue to run if this condition is valid (true). If the condition becomes
invalid (false) then the loop will terminate.

 Increment or decrement: It will be performed in every loop cycle. We use


this part to reach the final condition for terminating the loop.

Example of For loop


#include <stdio.h>
#include<conio.h>
void main()
{
int i;
14

for (i=1; i<=3; i++)


{
printf("%d\n", i);
}
getch();
}

Output:

1 2 3

-------------------------------------------------------------------------------------

Q:5 Explain the While and Do While Loop with example.


Ans:
While Loop:

While loop is used for executing a block of statements repeatedly until a given
condition returns false. The while loop test the termination condition at the top.
In the while loop, first the condition is checked and then the statements in while
loop are executed else control comes out of the loop.

Syntax of while loop:

while (condition test)


{
Statements to be executed repeatedly
Increment (++) or Decrement (--) Operation
}

Example of while loop:


15

#include <stdio.h>
int main()
{
int a=1;

while (a <= 4)
{
printf("%d ", a);
a++;
}

return 0;
}

Output:

1234

------------------------------

Do While:
do-while loop, tests the condition at the bottom after making each pass through
the loop body. The body is always executed at least once.

A do while loop executes the statements inside the body of do-while before
checking the condition. So you can say that if a condition is false at the first place
then the do while would run once.

Syntax of do-while loop

do
{
Statements

} while(condition test);
16

Example of do while loop


#include <stdio.h>
int main()
{
int j=0;
do
{
printf("Value of variable j is: %d, j);
j++;

} while (j<=2);

return 0;
}

Output:

Value of variable j is: 0


Value of variable j is: 1
Value of variable j is: 2

---------------------------------------------------------------------------------------

Q:6 a) Write a Program to find Factorial of a given number using for loop.
b) Write a program to print the fibonacci series.

Ans: a) Program of factorial using for loop:

#include<stdio.h>
#include<conio.h>
17

void main()
{
int n,i;
int f=1;

printf("Enter a Number");
scanf("%d",&n);

for(i=1; i<=n; i++)


{
f=f * i;
}

printf("The factorial is %d",f);

getch();
}

Output:
If the entered number is 3, then the output will be:
The factorial is 6

---------------------------------------------------------

Ans: b) Program to print the fibonacci Series

#include <stdio.h>
#include<conio.h>
void main()
{
18

int n,i;
int final=0,temp=1,prev=0;
Printf(“enter the number for Fibonacci series”);
Scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
printf(“%d”,final);
prev=temp;
temp=final;
final=prev+temp;
}
getch();
}

Output:
if value of n=8, then output will be
0 1 1 2 3 5 8 13
------------------------------------------------------------------------------------------------

Q:7 With is the purpose of break and continue statement. With in which
control statement, both can be included? Explain with the help of example.
Ans:
Break and Continue Statement:

1) Break statement:
19

Break statement is used to come out of the loop instantly. When a break statement
is encountered inside a loop, the control directly comes out of loop and the loop
gets terminated. It is used with if statement, whenever used inside loop.

Break statement can also be used in switch case control structure. Whenever it is
encountered in switch-case block, the control comes out of the switch-case

The break statement can be used inside loop Control Structures like (For,
While and do while loop) and can also be used in Switch case Control structure.

Syntax of break:

Break;

Example of (break) :

#include <stdio.h>
#include<conio.h>

void main()
{
int i=2;

switch (i)
{
case 1:
printf("Case1 ");
break;
case 2:
printf("Case2 ");
break;
case 3:
printf("Case3 ");
break;
case 4:
printf("Case4 ");
break;
default:
20

printf("Default ");
}
getch();
}

Output:

Case 2
----------------------------

2) Continue statement: The continue statement is used inside loops. When a


continue statement is encountered inside a loop, control jumps to the beginning of
the loop for next iteration, skipping the execution of statements inside the body of
loop for the current iteration.

The continue statement can only be used inside loop Control Structures.

Syntax:

continue;

Example: continue statement inside for loop


#include <stdio.h>
int main()
{
for (int j=1; j<=5; j++)
{
if (j==3)
{
continue;
}

printf("%d ", j);


21

}
return 0;
}

Output:

12 45

--------------------------------------------------------------------------------------

Q:8 What is Goto statement. Explain with example.

Ans:
goto statement:

When a goto statement is encountered in a C program, the control jumps directly


to the label mentioned in the goto statement.

Label:
A label has the same form as a variable name, and is followed by a colon. It can
be attached to any statement in the same function as the goto. The scope of a label
is the entire function.

Syntax of goto statement in C:

goto label_name;
..
..
label_name: C-statements
22

Example of goto statement and Label:


#include <stdio.h>
#include<conio.h>

void main()
{
int sum=0;

for(int i = 0; i<=10; i++)


{
sum = sum+i;

if(i= =5)
{
goto addition;
}
}

addition:
printf("%d", sum);

getch();
}

Output: 15
1

C Programming
Unit-3

Short Questions:

Q:1 What is the difference between Formatted and Unformatted I/O ?


Ans: Formatted I/O Function: It allow the input to be read from the keyboard
or the output displayed on the screen and that output we can format as per our
requirement.
For example: If values of average marks and percentage marks are to be
displayed on the screen, then the details like where this output would appear on
the screen, how many spaces would be present between the two values, the
number of places after the decimal points etc. can be controlled using formatted
functions.

For formatted output function, we use Printf() function.


For Formatted Input function, we use Scanf() function.

UnFormatted I/O Function: Unformatted input and output functions only


work with character data type. Unformatted input and output functions do not
require any format specifiers. Because they only work with character data type.
Unformatted line reads strings and writes strings but there's no conversions of
numeric values according to specific format. Unformatted input/output transfers
the internal binary representation of the data directly between memory and the
file.
For Unformatted output function, we use putchar(), puts() function.
For UnFormatted Input function, we use getch(), getche(), getchar(), gets()

--------------------------------------------------------------------------------------------
2

Q:2 Define Local and global variable.


Ans:
Local and global variable:
A local variable is a variable which is declared inside a function. if we
declare variables in a function then we can only use them within that function.
Local variables can be used only inside the function in which it is used.
The scope of local variable is restricted to that particular function.

Global variables are declared outside any function. Usually it is declared


outside the main function and global variable can be used by any function in
the program.
The scope of Global variable is with in the program. Any function of the
program can access these variables.

Example of Local and Global variable:


#include<stdio.h>
#include<conio.h>

int a=10,b=20; // a and b are the global variable

void main()
{
int c; // c is the local variables of main function
c=a+b;
Printf(“%d”, c);
getch();
}

Output: 30

-------------------------------------------------------------------------------------------
3

Q:3 What do you mean by Function Declaration, Function Definition and


function calling.
Ans: Function declaration :A function declaration tells the compiler about
a function's name, return type of function, and data type of parameters.

For functions the declaration needs to be done before the first call of
the function. Function declaration is also known as function prototype.By
default the return type of a function is integer (int) data type. You can also
specify any data type of function according to your need.

Function Definition:
A function definition specifies what a function does. A function
definition provides the actual body of the function. A function
definition specifies the name of the function, the types and number of
parameters it expects to receive, and its return type. A function definition also
includes a function body with the declarations of its local variables, and the
statements that determine what the function does.

Function Calling:
A function call is an expression that passes control and arguments (if any) to
a function. The point at which the function is being invoked or called is known
as the calling function.
The function which is calling that function is called as the calling function and
the function which is being executed due to the function call is known as the
called function.

-----------------------------------------------------------------------------------------
4

Long Question:

Q: 1 Discuss the use of following functions with the help of examples:


a) Getch()
b) getche()
c) puts()
d) gets()

Ans:

(a) getch():
This function presents in conio.h header file . getch() reads a single byte
character from input. It is a way to get a user inputted character. It can be used
to hold program execution, which is to wait until the user enters a character.
During the program execution, a single character gets or read through
the getch(). The given value is not displayed on the screen and the compiler
does not wait for another character to be typed. And then, the given character is
printed through the printf function.

Syntax:
getch();

Example of getch():
#include<stdio.h>
#include<conio.h>

Void main()
{

printf(“Hello World”);
5

getch();
}

Example program for getch() function in C programming language: This is a


simple Hello World! C program. After displaying Hello World! in output
screen, this program waits for any character input from keyboard. After any
single character is typed/pressed, this program returns 0.
-------------------------

(b) getche():
getche() function is a function in C programming language which waits for
any character input from keyboard and it will also echo the input character on to
the output screen.
During the program execution, a single character gets or read through
the getche(). The given value is displayed on the screen and the compiler does
not wait for another character to be typed. Then, afterward, the character is
printed through the printf function.

Syntax:
getche();

Example of getche():
#include<stdio.h>
#include<conio.h>

void main()
{

printf(“Hello World”);

getche();
}
6

Run this program and press a character. Then again when we view the output
screen sing Turbo C compiler. We will find the character printed on the screen
because of getche() function.
---------------------------

(c) puts() :
Puts function is used to write a line to the output screen. It works like printf
function. But the difference is printf() function is used to print both strings
and variables to the screen while the puts() function only permits you to print a
string only to your screen.

Syntax:
Puts();

Example of puts() :
#include<stdio.h>
#include<conio.h>

void main()
{

puts (“Hello World”);

getch();
}

---------------------

(d) gets() :
This function is declared in the header file stdio.h. It reads a line from stdin and
stores it into the location pointed by string. This function stops when either the
7

newline character is read or when the end-of-file is reached, whichever comes


first.

Syntax:
gets(argument list);
where argument list can contain one or more arguments And here argument are
the stored location of string.

Example of gets() :
#include<stdio.h>
#include<conio.h>

void main()
{

Char name[20];

puts (“Enter name”);


gets(name);
puts(“name”);

getch();
}

Output:
Suppose if user has provided the input string as “Nitish” then through gets()
function nitish will be stored in the array name[] and when we use puts(name).
this means that it will print the string value which is stored in the array name[].

---------------------------------------------------------------------------------------------
8

Q:2 What do you mean by Function. What is the need of Function ?


Explain with example how you can use a function in a program.

Ans: Function: A function is a block of statements that performs a specific


task. Suppose we are building an application in C language and in one of our
program, we need to perform a same task more than once. In that case we have
to create a function to perform that task, and we can call it any time when we
need to perform that task.

Need of functions in C:

Functions are used because of following reasons–

a) To improve the readability of code.


b) Improves the reusability of the code, same function can be used in any
program rather than writing the same code again and again.
c) Debugging of the code would be easier if you use functions, as errors are
easy to be traced.
d) Reduces the size of the code, duplicate set of statements are replaced by
function calls.

Types of functions: There are 2 types of functions:-


1) Predefined standard library functions : These are the functions which
already have a definition in header files of C language such as printf(), scanf().

2) User Defined functions: The functions that we create in a program are


known as user defined functions.

Syntax of a function:
return_type function_name (argument list)
{
Set of statements – Block of code
}
9

Where return type can be of any data type such as int, float etc. And
argument list contains variables names along with their data types.

Example:
Program of Addition of 2 numbers using Function:

#include<stdio.h>
#include<conio.h>

Void main()
{

int a, b, s;
printf(“enter the value of a and b”);
scanf(“%d %d”, &a,&b);
s = sum(a,b);
printf(“The sum of given numbers is %d”, s);
getch();
}

int sum(int a, int b)


{

int c;
c=a+b;
return (c);

---------------------------------------------------------------------------------------------
10

Q: 3 What do you mean by function prototype. What are the methods to


pass an argument in a function. Explain with example.
OR
What do you mean by function Prototype. What are the call by value and
call by reference method ?

Ans: Function prototype:


In computer programming, a function prototype is a declaration of
a function that specifies the function's name and type signature. Type signature
includes data types of parameters, and return type of function.
By using this information, compiler cross checks function parameters and their
data-type with function definition and function call. A function prototype act
as an interface. It specifies which type of function it is.

Need of Function Prototype:


 Because of the compiler can go through the program exactly once,
knowing which functions are in scope at any given time.
To do this, functions would have to be declared before they're used;
 prototypes let you declare a function without implementing its body
until later.

We can pass an argument in a function by 2 ways:


 Call by value
 Call by reference

1) Function Call by value:


First we need to understand that there are 2 types of parameter in a function:-
11

 Actual parameters: The parameters that appear in function calls.


 Formal parameters: The parameters that appear in function declaration.

Function Call By value:

When we pass the actual parameters while calling a function then this is known
as function call by value. In this case the values of actual parameters are copied
to the formal parameters. Thus operations performed on the formal parameters
don’t reflect in the actual parameters.

Example : Swapping numbers using Function Call by Value

#include <stdio.h>
#include<conio.h>
int swap(int , int); //prototype

Void main( )
{
int num1 = 10, num2 = 20 ;
printf("Before swapping: %d, %d", num1, num2);

swap(num1, num2); //call by value


printf("After swapping: %d, %d", num1, num2);

getch();

int swap( int a, int b )


{
int temp ;

temp = a ;
a=b;
b = temp ;

}
12

Output:

Before swapping: 10, 20

After swapping: 10, 20


----------------------------------

2) Function call by Reference:

When we call a function by passing the addresses of actual parameters then this
way of calling the function is known as call by reference. In call by reference,
the operation performed on formal parameters, affects the value of actual
parameters because all the operations performed on the value stored in the
address of actual parameters.

Example 2: Function Call by Reference – Swapping numbers

Here we are swapping the numbers using call by reference. As you can see the
values of the variables have been changed after calling the num() function
because the swap happened on the addresses of the variables num1 and num2.

#include<stdio.h>
#include<conio.h>
int swap(int , int); // prototype

void main( )
{
int num1 = 10, num2 = 20 ;
printf("Before swapping: %d %d",num1,num2);

swap( &num1, &num2 ); // call by Reference

printf("After swapping: %d %d",num1,num2);

getch();
}
13

int swap( int *a, int *b )


{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}

Output:

Before swapping: 10, 20

After swapping: 20, 10

------------------------------------------------------------------------------------

Q4: What do you mean by Recursive Function. Explain it with example.


Ans: Recursion:
The process of calling a function by itself is called recursion and the function
which calls itself is called recursive function. Recursion is used to solve
various mathematical problems by dividing it into smaller problems.
The recursion continues until some condition is met to prevent it. To prevent
infinite recursion, if...else statement (or similar approach) can be used where
one branch makes the recursive call and other doesn't

Use of Recursion:
 Reduce unnecessary calling of function.
 To reduce the code size
14

 we use recursive because of its simplicity.


 People use recursion only when it is very complex to
write iterative code.
 Recursion can Solve problems in easy way while its iterative solution is
very big and complex.
 Recursion uses lesser programming constructs to solve the problem.

Example: Program of Factorial using Recursion

#include<stdio.h>
#include<conio.h>
Void main()
{
int n, f;
printf(“enter the number”);
scanf(“%d”, &n);
f = fact(n);
printf(“The factorial of given number is %d”, f);
getch();
}
int fact(int n)
{
if(n==0)
{
return (1);
}
else
return (n*fact(n-1));
15

Output: suppose if user has provided the input as 3. Then the output will be 6
because the factorial of 3 is 6.

---------------------------------------------------------------------------------------------

Q:5 What are the various String Manipulation functions.


Ans: String Manipulation Function in C:
A string in C is an array of characters. String manipulation means the
fundamental operations on strings, including their creation, concatenation, the
extraction of string segments, string matching, their comparison, discovering
their length, replacing substrings by other strings, storage.

The more commonly-used string functions:


The most commonly used String functions are:

 strlen - get string length


 strcmp - compare two strings
 strcat - concatenate two strings
 strcpy - copy a string

1) strlen() : The strlen() function is pre defined library function which is


defined in <string.h> header file. strlen( ) function in C gives the length of the
given string. strlen( ) function counts the number of characters in a given string
and returns the integer value. It stops counting the character when null character
is found.

Syntax for strlen( ) function is given below.


16

strlen ( argument );
The function takes a single argument which represents the array in which string
is stored.

2) Strcmp() : The strcmp() function is defined in string.h header


file. Strcmp() function takes two strings. Then it compares two strings character
by character. The strcmp function returns a negative, zero, or positive integer
depending on whether string 1 is less than, equal to, or greater to string 2.

Syntax for strcmp( ) function is given below.


Strcmp ( argument1, agrumnent2 );

where argument1 point to the object where string1 is stored and agriument2
points to the object where string 2 is stored.

3) strcat(): The strcat() function is defined in <string.h> header file. In the C


Programming Language, the strcat() function appends a copy of the string s2
to the end of the string pointed by s1. It returns a pointer to s1 where the
resulting concatenated string resides.

Syntax for strcat( ) function is given below.


strcat ( argument1, agrumnent2 );
where argument1 point to the object where string1 is stored and agrument 2
points to the object where string 2 is stored.

4) strcpy() : strcpy() is a standard library function in C. It is present in


string.h header file
17

and thois function is used to copy one string to another. It returns a pointer to
the destination.

Syntax for strcat( ) function is given below.


strcpy ( argument1, agrumnent2 );
where argument1 point to the object where string1 is to be copied and agrument
2 points to the object from where string 2 is being copied from.

--------------------------------------------------------------------------------------

Q: 6 a) How can you find the length of a string. Explain with example.
b) How can you compare the two string. Explain with example.
c) How can you copy a string. Explain with example.

Ans: a) Program to find the length of a string:


#include<stdio.h>
#include<conio.h>

Void main()
{

int l;
Char m[20];
Printf(“enter the string”);
gets(m);

l = strlen(m);
printf(“The length of the given string is %d”,l);
getch();
}

Output:
18

Suppose if user has given the string as “Jay” then it will print the output as 3
because there are 3 characters in the string. So, the length of the string is 3.
------------------

b) Program to compare the two string:


#include<stdio.h>
#include<conio.h>

void main()
{

int c;
Char m[20], n[20];
Printf(“enter the string 1”);
gets(m);

printf(“enter the string 2”);


gets(n);

c = strcmp(m,n);
printf(“The length of the given string is %d”,c);
getch();
}

Output:
It will provide the difference of the ascii values of the 2 strings.

--------------------------

c) Program to copy the string from one location to another:


#include<stdio.h>
#include<conio.h>

void main()
{
19

Char m[20], n[20];


printf(“enter the string 2”);
gets(n);

strcpy(m,n);
printf(“The string is %s”,m);
getch();
}

----------------------------------------------------------------------------------
1

C Programming
Unit-4

Short Question:

Q:1 How one dimensional Array is initialised?

Ans: Array: An array is a collection of same data types elements.

Way to initialize an array:


We have just declared the array with 5 elements stored in it and we can also
initialize the array during declaration like this:

int arr[5] = {1, 2, 3, 4 ,5};

--------------------------------------------------------------------------------------------

Q:2 What do you mean by a string. How can you initialise Array string.
Explain with example.

Ans: String: A string in C is an array of characters. '\0' represents the end of the
string. It is also referred as String terminator & Null Character.

String Declaration and Initialisation:

Method 1:
char address[]={'T', 'E', 'X', 'A', 'S', '\0'};

Method 2: The above string can also be defined as –


char address[]="TEXAS";

In the above declaration NULL character (\0) will automatically be inserted at the
end of the string.

Example of String:
2

Read & Write Strings in C using gets() and puts() functions:

#include <stdio.h>
#include <string.h>
int main()
{
char nickname[20]; /* String Declaration*/

puts("Enter your Nick name:");


gets(nickname);

puts(nickname);
return 0;
}

Output:
Enter your Nick Name: Sumit
Sumit

------------------------------------------------------------------------------------------

Q:3 What is the difference between Structure and Union.

Ans: Structure:

Structure is a group of variables of different data types represented by a single


name. All the data elements of the structure are stored in different memory
location. So, all the data members can be accessed at the same time. Structure is
declared by using the keyword struct.

Union: It is a group of variables of different data types represented by a single


name. But all the data elements of the Union are stored in the same memory
location. So, all the data members cannot be accessed at the same time. Only one
member can be accessed at a time. Union is declared by using the keyword
Union.
3

Example of Structure in C:

We can create a structure that has members for name, roll_no and age and then
we can create the variables of this structure for each student.

#include <stdio.h>
#include<conio.h>
void main()
{
struct Student
{
char name[10];
int roll_no;
int age;
}s;

Printf(“Enter the data elements”);


Scanf(“%s %d %d”, &s.name, &s.roll_no, &s.age);

Printf(“Student name is: %s, s.name);

Printf(“Student roll_no is: %d, s.roll_no);

Printf(“Student age is: %d, s.age);

getch()
}

Output:

Enter the data element: Amit 1 30


Student Name is: Amit
Student roll_no is: 1
Student Age is: 20

--------------------------------------------------------------------------------------
4

Long Question

Q:1 What are the different storage classes used in C Programming ?

Ans: Storage Class: Storage class is the class according to which the storage
space of some variable is decided. There are basically two kinds of location in a
computer where such a value may be kept:
 Memory
 CPU Registers

It is the variable’s storage class which decides in which of these two locations the
value is stored.

To fully define a variable, one needs to mention not only its type but also its
storage class. If we don’t specify the storage class of a variable in its declaration,
then, C has got default storage classes.

A variable Storage class tells us:

 Where the variable would be stored


 What will be the initial value of the variable, if the initial value is not
assigned
 What is the scope of the variable
 What is the life of the variable

There are 4 Storage classes in C:


 Automatic Storage class
 Register storage class
 Static Storage class
 External storage class
5

a) Automatic Storage Class:

The features of a variable defined to have an automatic storage class are as


under :

Storage : Memory

Default initial value : A garbage value

Scope : Local to the block in which the variable is defined

Life : Till the control remains within the block in which it is


defined.

Example of Automatic Storage Class:

main()
{
auto int i, j;

Printf(“%d %d”, i,j);


}

Output:
1211
221

Where 1211 and 221 are garbage values of I, j. when you run this program, you
may get different values, since garbage values could be any value.

--------------------

b) Register Storage Class:

The values stored in a CPU Register can always be accessed faster than the one
stored in memory. Therefore, if a variable is used at many places in a program, it
is better to declare its storage class as register.
6

The features of a variable defined to have a Register storage class are as


under:

Storage : CPU Register

Default initial value : A garbage value

Scope : Local to the block in which the variable is defined

Life : Till the control remains within the block in which it is


defined.

Example of Register Storage Class:

main()
{
register int I;

For(i=1;i<=10;i++)
{
Printf(“%d”, i);
}

----------------

c) Static Storage Class:

The features of a variable defined to have a static storage class are as under
:

Storage : Memory

Default initial value : Zero


7

Scope : Local to the block in which the variable is defined

Life : Value of the variable exist between different function calls

Example of Static Storage Class:

main()
{
increment();
increment();
increment();
}

increment()
{
Static int i=1;

Printf(“%d”, i);
i=i + 1;
}

Output:
1
2
3

-------------

d) External Storage Class:

The features of a variable defined to have an External storage class are as


under :

Storage : Memory

Default initial value : Zero


8

Scope : Global

Life : As long as the Program execution does not come to an end

Example of External Storage Class:

extern int i;

main()
{
Printf(“%d”, i);

increment();
increment();
decrement();
decrement();
}

increment()
{
i=i+1;
printf(“On incrementing %d”, i);
}

decrement()
{
i=i-1;
printf(“On decrementing %d”, i);
}

Output:

i=0
On incrementing 1
On incrementing 2
On Decrementing 3
On Decrementing 4

------------------------------------------------------------------------------------------
9

Q:2 What do you mean by an Array? Explain with example.

Ans:

Arrays: An array is a collection of same data types elements. For example an


int array holds the elements of int types while a float array holds the elements of
float types.

Need of Array in C Programming


Consider a scenario where you need to find out the average of 100 integer
numbers entered by user. In C, you have two ways to do this:
1) Define 100 variables with int data type and then perform 100 scanf()
operations to store the entered values in the variables and then at last calculate
the average of them.
2) Second way is to have a single integer array to store all the values, loop the
array to store all the entered values in an array and later calculate the average.

Obviously the second solution is better, it is convenient to store same data types
in one single variable and later access them using array

How to declare Array in C:

int num[35]; /* An integer array of 35 elements */

char ch[10]; /* An array of characters for 10 elements */

Similarly an array can be of any data type such as double, float, short etc.

Types of Array:
 One Dimensional Array
 Two Dimensional Array
10

Example of One Dimensional Array In C programming to find out the


average of 4 integers:

#include <stdio.h>
int main()
{
int x, avg;
int sum =0;

int num[4]; /* Array- declaration */

for (x=0; x<4;x++)


{
printf("Enter number”);
scanf("%d", & num[x]);
}

for (x=0; x<4;x++)


{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}

Output:
Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20
11

Lets discuss the important parts of the above program:

Input data into the array:

Here we are using iteration for the array from 0 to 3 because the size of the
array is 4. Inside the loop we are displaying a message to the user to enter the
values. All the input values are stored in the corresponding array elements using
scanf function.
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}

Reading out data from an array:

Suppose, if we want to display the elements of the array then we can use
the for loop in C like this.
for (x=0; x<4;x++)
{
printf("num[%d]\n", num[x]);
}

Two dimensional (2D) arrays in C programming with example:

An array of arrays is known as 2D array. The two dimensional (2D) array in C


programming is also known as matrix. A matrix can be represented as a table of
rows and columns.

Example of Two dimensional(2D) Array:

This program demonstrates how to store the elements entered by user in a 2d


array and how to display the elements of a two dimensional array.
#include<stdio.h>
12

int main()
{

int array[2][3]; /* 2D array declaration*/

int i, j;

for(i=0; i<2; i++)


{
for(j=0;j<2;j++)
{
printf("Enter value for i and j);
scanf("%d", & array[i][j]);
}
}

//Displaying array elements

printf("Two Dimensional array elements:\n");


for(i=0; i<2; i++)
{
Printf(“\n”);

for(j=0;j<2;j++)
{
printf("%d ", array[i][j]);

}
}
return 0;
}

Output:

Enter value for array[0][0]:1


Enter value for array [0][1]:2
Enter value for array [1][0]:3
Enter value for array [1][1]:4

Two Dimensional array elements:


12
34
13

------------------------------------------------------------------------------------------

Q:3 What do you mean by Pointer. How you can pass pointer to a function.
Explain with example?

Ans:

Pointers in C Programming:

A pointer is a variable that stores the address of another variable. A variables


hold values of a certain type, but pointer holds the address of a variable.

For example, an integer variable holds an integer value, however an integer


pointer holds the address of a integer variable.

For example: we live in a house and our house has an address, which helps
other people to find our house. The same way the value of the variable is stored
in a memory address, with the help of pointer in the C program, we can find that
value when it is needed.

How to declare a pointer?

int *p1 /*Pointer to an integer variable*/


double *p2 /*Pointer to a variable of data type double*/
14

char *p3 /*Pointer to a character variable*/


float *p4 /*pointer to a float variable*/

By using * operator we can access the value of a variable through a pointer.

Example of Pointer demonstrating the use of & and *

#include <stdio.h>
int main()
{

int *p;

int a = 10;

p= &var;

printf("Value of variable a is: %d", a);


printf("\nValue of variable a is: %d", *p);
printf("\nAddress of variable a is: %p", &a);
printf("\nAddress of variable a is: %p", p);

return 0;
}

Output:

Value of variable var is: 10


Value of variable var is: 10
Address of variable var is: 0x7fff
Address of variable var is: 0x7fff

Passing pointer to a function:


15

Just like any other argument, pointers can also be passed to a function as an
argument. Lets take an example to understand how this is done.

Example: Passing Pointer to a Function in C Programming

In this example, we are passing a pointer to a function. When we pass a pointer


as an argument instead of a variable then the address of the variable is passed
instead of the value. So any change made by the function using the pointer is
permanently made at the address of passed variable. This technique is known as
call by reference in C.

Example : Swapping two numbers using Pointers:

#include<stdio.h>
#include<conio.h>
int swap(int , int); // prototype

void main( )
{
int num1 = 10, num2 = 20 ;
printf("Before swapping: %d %d",num1,num2);

swap( &num1, &num2 ); // call by Reference

printf("After swapping: %d %d",num1,num2);

getch();
}

int swap( int *a, int *b )


{
int temp ;
temp = *a ;
*a = *b ;
*b = temp ;
}
Output:

Before swapping: 10, 20


16

After swapping: 20, 10


------------------------------------------------------------------------------------

Q:4 What is the use of Flowchart. What are the different symbols used in
Flowchart. Explain with example.

Ans: Flowchart: Flowchart is a technique which we use for graphical


representation of data in which we show the flow of data.
In flowchart, we use some symbols of different shapes for showing necessary
operations. Each symbol has some specific meaning and function in flowchart.

The Flowchart symbols along with their purpose are given below:

This symbol is used for showing Start or end.

This symbol is used for Input or Output data.


17

This symbol is used for processing data.

This symbol is used for Decision Logic.

This symbol is used for showing data flow.

Types of Flowchart:
 System Flowchart
 Modular Program Flowchart

a) System Flowchart: A system is a group of inter related components tied


together to a plan to achieve predefined goal. The elements and features of a
system are graphically shown and its structure and relationship are also
represented by Flowchart symbols.

b) Modular Program Flowchart: This flowchart defines the logical steps for
the input, output and processing of information of a specific program. In this the
independent modules are written for different procedure. In this the relationship
and the order in which processes are to be performed are included.

Example of Flowchart:
We are showing flowchart to find the biggest of 3 numbers.
18
19

----------------------------------------------------------------------------------

S-ar putea să vă placă și