C Notes Final
C Notes Final
Programming Process
Q: Explain the steps in solving a problem on the computers.(April 2009 , 2010, 2011,
2013)
or
Q: Write Steps in developing of a program.
Ans: In order to develop a program, whether it is small or complex a special procedure to be
followed which is called as program development life cycle. It is the systematic way to
developing any quality software. A computer program is a set of instructions which a
computer can use to solve a program. Program must be written in a precise way because
computer follows only instructions given to it. To solve a program efficiently, the
programmer follows the following steps referred to as the programming process.
Program design
Coding
Compilation
Documentation
Program design
The second phase of programming process is program design. In this phase, the programmer
must have a proper understanding of the behaviour of the problem to be solved. This
behaviour can be described in terms of the necessary inputs and required outputs. After this
programmer designs a process through different techniques like algorithm or flowchart or
pseudo code which will give the required outputs from the given inputs. Based on the
specification produced by the user, the best programmer designs a program which meets the
best requirements of the user.
Coding
After the successful completion of second phase i.e. selection of algorithm or flowchart, it
must be converted into a form that can be used by computer. So in third phase, the
programmer translates the steps of algorithm or flowchart in a computer program using a
language such as „C‟ and is called coding. Once a program is written in „C‟ i.e. source code is
ready to enter it into computer and store it in a disk file with extension (.C).
Compilation
Compilation is a process of generating machine code from source code. This can be done
using a compiler. The „C‟ compiler takes and process program that can be a complete
program or just a function. „C‟ compiler has in-built pre-processor which is used to process
the source code before being passed to compiler for compilation. Pre-processor directives are
used to tell the pre-processor how to process the source code. It processes the source code
and gives as a result the expanded version of source code. „C‟ compiler takes this expanded
version of source code of the same name and (.obj) extension. The process of translating the
source code into object code may generate some type of errors which are as follow.
Que: what is data flow diagram? What are the advantages and disadvantages of data
flow diagram?
Ans: Data flow diagrams (DFDs) reveal relationships among and between the various
components in a program or system. DFDs are an important technique for modelling a
system‟s high-level detail by showing how input data is transformed to output results through
a sequence of functional transformations. DFDs consist of four major components: entities,
processes, data stores, and data flows. The symbols used to depict how these components
Interact in a system are simple and easy to understand; however, there are several DFD
models to work from, each having its own zymology. DFD syntax does remain constant by
using simple verb and noun constructs. Such a syntactical relationship of DFDs makes them
ideal for object-oriented analysis and parsing functional specifications into precise DFDs for
the systems analyst.
When it comes to conveying how information data flows through systems (and how
that data is transformed in the process), data flow diagrams (DFDs) are the method of choice
over technical descriptions for three principal reasons.
1. DFDs are easier to understand by technical and nontechnical audiences.
2. DFDs can provide a high level system overview, complete with boundaries and
connections to other systems.
3. DFDs can provide a detailed representation of system components.
DFDs help system designers and others during initial analysis stages visualize a current
system or one that may be necessary to meet new requirements. Systems analysts prefer
working with DFDs, particularly when they require a clear understanding of the boundary
between existing systems and postulated systems. DFDs represent the following:
1. External devices sending and receiving data.
2. Processes that change that data.
3. Data flows themselves.
4. Data storage locations.
Data store
Entity
An entity is the source or destination of data. The source in a DFD represents these
entities that are outside the context of the system. Entities either provide data to the
system (referred to as a source) or receive data from it (referred to as a sink). Entities are
often represented as rectangles (a diagonal line across the right-hand corner means that
this entity is represented somewhere else in the DFD). Entities are also referred to as
agents, terminators, or source/sink.
Process
The process is the manipulation or work that transforms data, performing
computations, making decisions (logic flow), or directing data flows based on business
rules. In other words, a process receives input and generates some output. Process names
(simple verbs and dataflow names, such as “Submit Payment” or “Get Invoice”) usually
describe the transformation, which can be performed by people or machines. Processes
can be drawn as circles or a segmented rectangle on a DFD, and include a process name
and process number.
Data Store
A data store is where a process stores data between processes for later retrieval by that
same process or another one. Files and tables are considered data stores. Data store names
(plural) are simple but meaningful, such as “customers,” “orders,” and “products.” Data
stores are usually drawn as a rectangle with the right- hand side missing and labelled by
the name of the data storage area it represents, though different notations do exist.
Data Flow
Data flow is the movement of data between the entity, the process, and the data store.
Data flow portrays the interface between the components of the DFD. The flow of data in
a DFD is named to reflect the nature of the data used (these names should also be unique
within a specific DFD). Data flow is represented by an arrow, where the arrow is
annotated with the data name.
Example
In this example Student and Faculty are the source and destination of information (the
entities), respectively. Register 1, Exam 2, and Graduate 3 are the processes in the program.
Student Record is the data store. Register 1 performs some task on Registration Form from
Student, and the Subject Registered moves to the data store. The Class Rolls information
flows on to Faculty. Graduate 3 obtains Academic Record information from Student Record,
and Degree/Transcript information is moved to Student. Exam2 obtains exam/paper
information from Faculty, and moves the Grades to the Student Record for storage.
Advantage of DFD
As we have seen, the DFD method is an element of object- oriented analysis and is widely
used. Use of DFDs promotes quick and relatively easy project code development. DFDs are
easy to learn with their few-and- simple-to-understand symbols (once you decide on a
particular DFD model). The syntax used for designing DFDs is simple, employing English
nouns or noun- adjective-verb constructs.
Disadvantage of DFD
DFDs for large systems can become cumbersome, difficult to translate and read, and be time
consuming in their construction. Data flow can become confusing to programmers.
Example
A bank uses the following rules to classify the new accounts. Id a depositor‟s age is 21 or
above and if deposit Rs. 100 or more classify the account type as A. If the depositor is under
21 and deposit Rs. 100 or more classify as account B. If the depositor is 21 or over but
deposit below Rs. 100 classify it as Account C. If the depositor is under 21 and deposit is
below Rs. 100 do not open account.
From the above we come to this conclusion which is as the following rules.
Rule 1 If depositor`s age is 21 or above(condition 1)
And If deposit is Rs. 100 or more(condition 2)
Then classify in account as type A(Action 1)
Rule 2 If depositor`s age is under 21(condition 3)
And If deposit is Rs. 100 or more(condition 2 )
Then classify in account as type B(Action 2)
Rule 3 If depositor`s age is 21 or above(condition 1)
And If deposit is below Rs. 100(condition 4)
Then classify in account as type C(Action 3)
Rule 1 If depositor`s age is under 21(condition 3)
And If deposit is below Rs. 100(condition 4)
Then do not open account(Action 4)
These conditions can be written as:
Condition 1 Depositor‟s age ≥ 21
Condition 2 Deposit ≥ Rs 100
Condition 3 Depositor‟s age <21
Condition 4 Deposit < Rs 100
Before writing an algorithm for a problem, one should find out what is/are the inputs to the
algorithm and what is/are expected output after running the algorithm. Now let us take some
exercises to develop an algorithm for some simple problems: While writing algorithms we
will use following symbol for different operations:
Characteristics of an algorithm
Input: There are zero or more values which are externally supplied as input.
Output: At least one value is produced as an input
Definiteness: Each step must be clear and unambiguous. Unambiguous means that
the same step must not be repeated again and again unnecessarily.
Finiteness: If we trace the steps of an algorithm, then for all cases, the algorithm must
terminate after a finite number of steps
Effectiveness: each step must be sufficiently basic that it can in principle be carried
out by a person using only paper and pencil. Each step must be not only definite but
also feasible.
Example 1: Write an algorithm to read two numbers and find their sum.
Step1: Start
Step2: Read\input the first num1.
Step3: Read\input the second num2.
Step4: Sum num1+num2 // calculation of sum
Step5: Print Sum
Step6: End
Step1: Start
Step2: Read radius of a circle.
Step3: area 3.14*radius*radius.
Step4: Print area
Step5: End
Step1: Start
Step2: Read Fahrenheit in f.
Step3: Celsius 5/9*(f-32)
Step4: Print Celsius
Step5: End
Step1: Start
Step2: Read a and b.
Step3: If a>b
Print “a is greater”.
Else
Print “b is greater”.
Step4: End
Step 1: Start
Step 2: Read variables a, b and c.
Step 3: If a>b
If a>c
Print “a is greatest.
Else
Print “c is greatest.
Else
If b>c
Print “b is greatest.
Else
Print “c is greatest.
Step 5: Stop
Advantages of algorithm
1. It is a step-wise representation of a solution to a given problem, which makes it
easy to understand.
2. An algorithm uses a definite procedure.
3. It is not dependent on any programming language, so it is easy to understand for
anyone even without programming knowledge.
4. Every step in an algorithm has its own logical sequence so it is easy to debug.
5. By using algorithm, the problem is broken down into smaller pieces or steps hence,
it is easier for programmer to convert it into an actual program
Disadvantages of algorithm.
1. Writing algorithm takes a long time.
2. An Algorithm is not a computer program, it is rather a concept of how a program
should be.
There are 6 basic symbols commonly used in flowcharting of assembly language Programs:
Terminal, Process, input/output, Decision, Connector and Predefined Process. This is not a
complete list of all the possible flowcharting symbols, it is the ones used most often in the
structure of Assembly language programming
2. Flowchart symbols have an entry point on the top of the symbol with no other entry points.
The exit point for all flowchart symbols is on the bottom except for the Decision symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and one
side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can be
shown as long as it does not exceed 3 symbols.
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt programs or
subroutines) symbol.
1. Complex logic: - Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy.
2. Alterations and Modifications: - If alterations are required the flowchart may
require re-drawing completely.
3. Reproduction: - As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
4. The essentials of what is done can easily be lost in the technical details of how it is
done.
Examples:
Print "passed"
else
Print "failed"
2. Fundamentals of C language
Q: Write a short note on history and features of ‘C’ language.
Or
Q: Discuss History of C.
or
Q: Write features of C language in detail.
Ans. C is a general-purpose, high-level language that was originally developed by Dennis M.
Ritchie to develop the UNIX operating system at Bell Labs. C was originally first
implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis
Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application
programs have been written in C. C has now become a widely used professional language for
various reasons:
Easy to learn
Structured language
It produces efficient programs
It can handle low-level activities
It can be compiled on a variety of computer platforms
Facts about C
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced around the early 1970s.
The language was formalized in 1988 by the American National Standard Institute
(ANSI).
Most of the state-of-the-art software have been implemented using C.
Today's most popular Linux OS and RDBMS MySQL have been written in C.
Today C is the most widely used and popular System Programming Language.
C was initially used for system development work, particularly the programs that make-up
the operating system. C was adopted as a system development language because it produces
code that runs nearly as fast as the code written in assembly language. Some examples of the
use of C might be:
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities
Features of ‘C’
C language is general purpose and high level programming language. The most important
features of „C‟ language are following.
Middle level language: as a middle level language C combines both the advantages of low
level and high level languages. (arrays,pointers etc).
Flexible: „C‟ can be used for a wide variety of application ranging from embedded systems
to commercial data processing techniques.
Clarity: The keyword and library functions available in „C‟ resembles common English
words thus it helps to improve the clarity of the program.
Versatile: „C‟ is very versatile language as it can solve problems in almost every application
area.
Memory management: The various memory management functions available in „C‟ which
helps to save the memory and thus improve the efficiency.
Compact code: Use of operators like ++, --, +=, ==, /=, *= in „C‟ helps to make compact
code. These features were not available in languages like COBOL and BASIC.
Documentation: ‘C’ language allows user to add comments in the program. These
comments improve the readability of a program. Comments are written in general English
and are written using // and /*.
Alphabets
Uppercase letters A-Z
Lowercase letters a-z
Digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Characters
~`!#@%&*()_-+=|\{}[]:;“„<>?./
Certain ASCII characters are unprintable, which means they are not displayed on the screen
or printer. Those characters perform other functions aside from displaying text. Examples are
backspacing, moving to a newline, or ringing a bell. They are used in output statements.
Escape sequence usually consists of a backslash and a letter or a combination of digits. An
escape sequence is considered as a single character but a valid character constant. These are
employed at the time of execution of the program. Execution characters set are always
represented by a backslash (\) followed by a character. Note that each one of character
constants represents one character, although they consist of two characters. These characters
combinations are called as escape sequence.
Identifiers
A „C‟ identifier is a name used to identify a variable, function, or any other user defined
item. An identifier starts with a letter A to Z, a to z, or an underscore „_‟ followed by zero or
more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as
@, $, and % within identifiers. C is a case-sensitive programming language. Thus, Manpower
and manpower are two different identifiers in C. Here are some examples of acceptable
identifiers:
For Example: student-name,
phone_no,
address
Rules for identifiers
Identifier name can include letters, digit and underscore ( _ ) in „C‟.
Identifier name must start with letters only.
Keyword cannot be used as identifiers.
The maximum number of character allowed in an identifier name is compiler
dependent, but the limit imposed by all the compilers provides enough
flexibility to create meaningful identifier name.
Keywords
Keywords are reserved words that have a particular meaning already defined with
compiler. The keyword cannot be used as an identifier. There are 32 keywords reserved by
„C‟ programming language.
Auto double int struct
Break else long switch
Case enum register typedef
Char extern return union
Const float short unsigned
continue for signed void
Default goto sizeof volatile
Do if static while
Integer Constant
An integer constant is an integer values number. It consists of a sequence of digits. An
integer constant can consist of any combination of digits taken from set 0 to 9. If the constant
contains two or more digits, the first digit must be something other than 0.
Character constant
A character constant is single character enclosed in apostrophes i.e. single quotation
marks. It may be an alphabet, digit or special character enclosed in single quotation marks.
Both quotation marks are pointing towards left. The maximum length of a character constant
is 1 character in memory.
String constant
A string constant is a constant that consist of any number of consecutive characters
i.e. a sequence of characters enclosed by double quotation marks. e.g. “Munish kumar”.
Syntax:
float <variable name>;
float num1;
double num2;
long double num3;
Floating Point Data Type Memory Allocation:
Syntax:
char <variable name>;
char ch = „a‟;
A character data type used 1 byte memory.
Void Type:
The void type has no values therefore we cannot declare it as variable as we did in
case of integer and float. The void data type is usually used with function to specify its
type.
Secondary Data type
Secondary data types are those data types which are derived from one or more basic data
types. In „C‟ there are following secondary data types
Array
Array is basically a collection of same data types. Array is a group of same type of
data elements that have been given a common name. Array is used where programmer need
multiple variables of same type, in this situation array is used instead of multiple elements.
Syntax
data_type variable_name[size];
where data_type may be any of the basic data type like int, float or char. variable_name is the
name of array and size is the number of elements in array.
Structure
Sometimes a program requires a data in terms of records. In the form of record it must
require data_type in which different types of data can be clubbed together i.e. int, float, char.
For this type of requirement program need a data type called as structure data type in which
different types of data can be clubbed together. E.g. A student could have name, roll no and
marks etc. Where name is of char and roll no and marks are integer data types.
Syntax
struct structure_name
{
data_type1 var_name1
data_type2 var_name2
.
.
.
data_typeN var_nameN
}
Union
Unions are also the derived data types almost same as structure. They are declared in
the same way as structures. The only difference is that in structures, each variable has the
separate memory allocation for each element but in union variables use the same memory
location. The space in the memory taken by union is equal to the length of the variable that
has the maximum size.
Syntax
union union_name
{
data_type1 var_name1
data_type2 var_name2
.
.
.
data_typeN var_nameN
}
Ans:
1. A variable name can have letters (both uppercase and lowercase letters), digits and
underscore only.
2. The first letter of a variable should be either a letter or an underscore. However, it is
discouraged to start variable name with an underscore. It is because variable name that
starts with an underscore can conflict with system name and may cause error.
3. There is no rule on how long a variable can be. However, only the first 31 characters of a
variable are checked by the compiler. So, the first 31 letters of two variables in a program
should be different.
An assignment "statement" is not really a statement (although it is typically used that way),
but is an expression. The value of the expression is the value that is assigned to the variable.
For example, the expression
i = j = k = 0;
sets all of i, j, and k to zero.
#include<stdio.h>
int main()
{
printf("hello World!");
return 0;
}
Step 3: Save the program using F2 (OR file > Save), remember the extension should be “.c”.
In the below screenshot I have given the name as helloworld.c.
Step 5: Press Ctrl + F9 to Run (or select Run > Run in menu bar) the C program.
Step 6: Alt+F5 to view the output of the program at the output screen.
3. Operators and Expressions
Que: Write a note on C instruction set.
Ans: There are basically three types of instructions in C:
int num;
char c; // Type Declaration
float f;
main()
{
// Statement
}
Example
int num=10, j=23;
float a=1.05, b=1-55+24;
int a, b, c, d;
int a=b=c=d=10;
Integer mode arithmetic statement: This is an arithmetic statement which all operands are
either integer or integer constants.
int i, j, l, m;
i=i+1;
m=i* j +l;
Real Mode Arithmetic Statement: These are arithmetic statement in which all operands are
either real constant or real variable.
float si, roi, p, q ;
si = roi*p*q/100.0;
Mixed mode arithmetic statements: this is an arithmetic statement in which some of the
operands are integer and some of the operands are real.
int a, b, c, num ;
avg = ( a + b+ c + num)/4;
3. Control Instructions in C
The „Control Instructions‟ enable us to specify the order in which instructions in a program
are to be executed. or the control instructions determine the „flow of control‟ in a program.
Sequence Control Instruction: The Sequence control instruction ensures that the
instructions are executed in the same order in which they appear in the program.
Selection or Decision Control Instruction: Decision instructions allow the computer to take
a decision as to which instruction is to be executed next.
Repetition or Loop Control Instruction: The Loop control instruction helps computer to
execute a group of statements repeatedly.
Switch Case.
Arithmetic Operators
The arithmetic operators are used to perform many of familiar mathematical operations( such
as addition, multiplication, subtraction etc) that involves calculation of numeric values
represented by variables, constants etc. They are binary operator that works with integers
numbers and even characters. Following table shows all the arithmetic operators supported by
C language. Assume variable A holds 20 and variable B holds 10 then:
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A - B = 10
∗ Multiplies both operands. A ∗ B = 200
∕ Divides numerator by de-numerator. A∕ B = 2
% Modulus Operator and remainder of after an integer A%B=0
division.
Output
Relational Operators
The relational operators are used to test the relationship between two operands. It does so by
comparing one operands against another and returns either true or false, depending upon the
status of the match. A relational expression that is interpreted by true evaluates to an integer
value 1 and if false it evaluates to an integer value of 0. Relational operators are binary
operators because they perform their operation on two operands. These operators are most
often used within conditional and looping statements such as if, while and for statements.
Following table shows all the relational operators supported by C language. Assume variable
A holds 10 and variable B holds 20, then:
Operator Description Example
== Checks if the values of two operands are equal or not. If yes, then (A == B)
the condition becomes true. is not
true.
!= Checks if the values of two operands are equal or not. If values are (A != B)
not equal then the condition becomes true. is true.
> Checks if the value of left operand is greater than the value of (A > B)
right operand. If yes, then the condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right (A < B)
operand. If yes, then the condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal to the (A >= B)
value of right operand. If yes, then the condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the (A <= B)
value of right operand. If yes, then the condition becomes true. is true.
output
Logical Operators
Logical operators are used to combine one or more relational expression that results in
formation of complex logical expression. Like relational operator, logical operator evaluate
the result of logical expression in term of Boolean values that can only be true (1) or false(0)
according to the result of the logical expression. They are generally used in an expression.
Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then:
Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, (A &&
then the condition becomes true. B) is
false.
! Called Logical NOT Operator. It is used to reverse the logical !(A &&
state of its operand. If a condition is true, then Logical NOT B) is
operator will make it false. true.
Output
Bitwise operators
C provides an extensive bit manipulation operator for programming who want to write
program at machine level. These operators act directly on the bits of their operands rather
than numeral value. They are used for testing bits or shifting them either right to left or left to
right. Bitwise operators are used to manipulate the bits of integral operands such as char,
short, int and long both signed and unsigned form. Bitwise operator works on bits and
performs bit-by-bit operation. The Bitwise operators supported by C language are listed in the
following table. Assume variable A holds 60 and variable B holds 13, then:
~ Binary Ones Complement Operator is unary and has the effect (~A ) = -61
of 'flipping' bits. i.e., 1100
0011 in 2's
complement
form.
<< Binary Left Shift Operator. The left operands value is moved A << 2 =
left by the number of bits specified by the right operand. 240 i.e.,
1111 0000
>> Binary Right Shift Operator. The left operands value is moved A >> 2 = 15
right by the number of bits specified by the right operand. i.e., 0000
1111
Assignment Operators :
The assignment operator is most common binary operator use in C language. It evaluates the
result of right hand side and then assigns the resulting value to a variable on the left hand
side. The right operand can be variable, constant, function call or expression. But in left side
it should be a variable. The following table lists the assignment operators supported by the C
language
Operator Description Example
If the expression contains one operand as double data type and another
operand as some other lower data type then the other operand is also converted
to double and the result will be double.
double operator (float(or)long(or)int(or)short)=>double
If the expression contains long and unsigned integer data types, the unsigned
integer is converted to unsigned long and the result will be unsigned long.
Character and short data are promoted to integer.
Unsigned char and unsigned short are converted to unsigned integer.
Forced Conversion
Forced conversion occurs when we are converting the value of the larger data type to
the value of the smaller data type or smaller data type to the larger data type. For example,
consider the following assignment statement
int a;
float b;
a=5.5;
b=100;
In the first statement a=5.5, a is declared as int so the float value 5.5 cannot be stored in a. In
such a case float is demoted to an int and then its value is stored. hence 5 is stored in a.
In the second statement b=100, since b is a float variable 100 is promoted to
100.000000 and then stored in b.
In general, the value of the expression is promoted or demoted depending on the type of
variable on left hand side of =. Consider the following statement
float x,y,z;
int result;
result=x*y*z/100+32/8-3*1.5;
In the above statement some operands are of int type where as others are floats. During
evaluation of the expression the ints would be promoted to floats and the result of the
expression would be a float. But when this float value is assigned to result, it is again
demoted to an int and then stored in result.
Forced conversion may decrease the precision. Type casting is the preferred method
of forced conversion
Syntax
(type-name) expression;
Example
int n;
float x;
x=(float)n;
The above statement will convert the value of n to a float value before assigning to x. But n is
not altered. Type casting does not change the actual value of the variable but the resultant
value may be put in temporary storage. The cast operator has the same high precedence as
other unary operators. The Typecasting should not be used in some places such as
1. Type cast should not be used to override a const or volatile declaration overriding
these type modifiers can cause the program to fail to run correctly.
2. Type cast should not be used to turn a pointer to one type of structure or data type in
to another.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Que: What are formatted and unformatted statements in c? Support your answer with
suitable example.
Ans: formatted and unformatted statements in c are used for data input and output from
standard input/output devices. „C‟ language includes a number of library functions for data
input and output. These library functions are further divided into formatted and unformatted
statements which are explained below:-
Formatted statements
Formatted input/output statements allow the input to be read from the keyboard or output to
be displayed on the monitor to be formatted as per requirements. It actually deals with a
number of spaces that will be present between two values, when output will be displayed on
the screen or number of places after a decimal point. Following are formatted statements in
„C‟
scanf()
The data can be entered into the computer from standard input device (usually
keyboard) by using a library function scanf(). The scanf() falls under the category of
formatted console I/O statement. The scanf() is used to enter all the data values with
format of that data type.
Syntax
scanf(formatstring, arg1, arg2,. . . . . . ., argN);
Here, formatstring is a string that contains required formatting information. It consists
of one or more character groups where each data group is used for each data item to
be entered.
printf()
The data can be displayed onto the computer by standard onput device (usually
monitor) by using a library function printf(). The print() falls under the category of
formatted console I/O statement. The printf() is used to display the data values or
string with format of that data type.
Syntax
printf(formatstring, arg1, arg2,. . . . . . ., argN);
Here, formatstring is a string that contains required formatting information. It consists
of one or more character groups where each data group is used for each data item to
be displayed.
Program to demonstrate formatted statements.
Output
Unformatted statements
Unformatted I/O statements allow the input to be read from keyboard or output to be
displayed on the monitor without any format specifiers. These statements can be classified
into two categories.
Character handling statements
The character handling statements deals with one character at a time. The character
input functions include getch(), getche(), getchar(). The character output functions
include putch(), putchar()
Output
Documentation section
Pre-processor directives section
Global declaration section
main() program section
{
Declaration part
Executable part
}
Subprogram section
Function_1()
Function_2()
....................
....................
Function_n()
1. Documentation section: Its includes a set of comment lines that improves the readability
of the program so that you and other programmers can understand your program. A
comment is message that exists only for the programmer and is ignored by the compiler
even if it looks like your program code. A good program should include comments that
describe the purpose of the program, author name, date and time of program creation and
other details. The documentation section is optional, however it is recommended.
Comments may appear anywhere in the program in c. It can be two type
3. Global Declaration section: This section includes global declaration that is used to
declare global variables. They are called so because the are accessible to any part of the
program. In others words these variables are visible throughout the program. The global
variables declared before main() functions but after declaring pre-processor directives.
4. main() Program Section: The execution of the program always starts from this part of
the program. This part begins with a function named main(). It is this function from
which the execution of program starts. The body of the function is enclosed in curly
braces ( { and } ). C program may have many function but main is essential and all other
function are called within main program section. It returns the status code to the operating
system.
5. Subprogram Section : It include various user defined functions. These functions are
defined by programmer itself to write one‟s own code. These functions are called by
main() in C program.
Output:-
To include header files(Header files are files with pre defined function
definitions, user defined data types, declarations that can be included.)
To sum up, pre-processing directives occurs before program compilation. So, it can be also
be referred to as pre compiled fragments of code. Some possible actions are the inclusions of
other files in the file being compiled, definitions of symbolic constants and macros and
conditional compilation of program code and conditional execution of pre-processor
directives. All pre-processor directives has begin with the # operator.
If statement
As the word itself is clarifying its meaning, it is used to check a condition and
perform a set of statements according to the result of the condition checked.
The condition following the keyword if includes any relational or logical
expression which always enclose within a pair of parentheses. If condition is
true then block of if statement will executes its statements and if it is false then
flow will go out of if‟s block.
Syntax :
if (condition)
{
...
... // True_Block statements;
...
}
Example:
Output:
In above example user enters the marks and program will tell if one is passed. In if
statement there is a limitation of false condition, which is resolved further by if-else
statement.
If-else statement
If-else statement is used to overcome the limitation of if statement. If statement do
have not another block to execute for false statement. But in if-else statement else
block is used for handling false statements. Else block do not need to specify any
condition. It will automatically executes its block when condition become false.
Syntax :
if (condition)
{
...
... // True_Block statements;
...
}
else
{
...
... // False_Block Statements;
...
}
In the above given syntax "condition" means any relational condition or any mathematical
expression. If the condition given in the brackets (parenthesis) is TRUE then the statements
within the BRACES executed. In case of mathematical expressions every non-zero value (i.e.
+ve or -ve) is considered to be TRUE and zero value is considered as FALSE. The
statements given in BRACES after the "else" part are executed when the condition is false.
Output
First run
Second run
In C programming language the else if ladder is a way of putting multiple ifs together
when multipath decisions are involved. It is a one of the types of decision making and
branching statements. A multipath decision is a chain of if‟s in which the statement
associated with each else is an if. The general form of else if ladder is as follows -
if ( condition 1)
{
statement - 1;
}
else if (condtion 2)
{
statement - 2;
}
else if ( condition n)
{
statement - n;
}
else
{
default statment;
}
This construct is known as the else if ladder. The conditions are evaluated from the
top of the ladder to downwards. As soon as a true condition is found, the statement
associated with it is executed and the control is transferred to the end of else
block(skipping the rest of the ladder). When all the n conditions become false, then
the final else containing the default statement will be executed.
Output:
First Run
Second Run
In nested if else inner block of if/ if-else block will execute only when outer condition
will satisfied. Nested if-else statements are used where a programmer need conditions
within conditions, these situations are handled by nested if-else statement.
Que: Explain various types of loops. Write the differences between while and do-while.
Ans: You may encounter situations when a block of code needs to be executed several
number of times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on. C language provide various
control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. Given below is the general form of a loop statement C language:
While Loop
Syntax
The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}
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, the program control passes to the line immediately
following the loop.
Output:
For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times. For loop has three arguments initialization,
condition and increment / decrement. All three arguments are optional in for loop. A for loop
need only two semi-colons(;;) to execute its body.
Syntax
The syntax of a for loop in C programming language is:
Output:
Do while Loop
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while
loop in C programming checks its condition at the bottom of the loop. A do...while loop is
similar to a while loop, except the fact that it is guaranteed to execute at least one time.
Generally do while loop is used in menu driven programs, where menu has to display without
conditions to be checked.
Syntax
The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}while( condition );
Conditional expression appears at the end of the loop, so the statement(s) in the loop executes
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 executes again. This process repeats until the given
condition becomes false.
Output:
Ans: In programming there are some situations when a programmer wants to skip some code
of block and sometimes we want to continue executing the code of block. In C this is
achieved with the help of jumping statements. The break, goto and continue statements are
known as jump statements. These are used to transfer program control from one point in the
program to another point, at any time. Let's understand how these work?
break statement
This statement terminates the execution of loop or switch in which it appears and transfers
program control to the next statement which is placed immediately after the loop or switch.
The break statement is used inside loop or switch statement. When compiler finds the break
statement inside a loop, compiler will abort the loop and continue to execute statements
followed by loop.
Syntax
The syntax for a break statement in C is as follows:
break;
Example
#include<conio.h>
#include <stdio.h>
Void main ()
{
/* local variable definition */
int a=10;
/* while loop execution */
while(a<20)
{
printf("value of a: %d\n",a);
a++;
if(a>15)
{
/* terminate the loop using break statement */
break;
}
}
getch();
}
output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
continue Statement
The continue statement in C programming works somewhat like the break statement. Instead
of forcing termination, it forces the next iteration of the loop to take place, skipping any code
in between. For the for loop, continue statement causes the conditional test and increment
portions of the loop to execute. For the while and do...while loops, continue statement causes
the program control to pass to the conditional tests.
Syntax
The syntax for a continue statement in C is as follows:
continue;
Example
#include<conio.h>
#include <stdio.h>
void main ()
{
/* local variable definition */
int a=10;
/* do loop execution */
do
{
if( a == 15)
{
/* skip the iteration */
a ++;
continue;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
getch()
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
goto Statement
A goto statement in C programming provides an unconditional jump from the „goto‟ to a
labeled statement in the same function. NOTE: Use of goto statement is highly discouraged
in any programming language because it makes difficult to trace the control flow of a
program, making the program hard to understand and hard to modify. Any program that uses
a goto can be rewritten to avoid them.
Syntax
The syntax for a goto statement in C is as follows:
goto label;
..
.
label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C
program above or below to goto statement.
Example
#include<conio.h>
#include <stdio.h>
void main ()
{
/* local variable definition */
int a=10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
getch();
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Syntax
switch(expression)
{
Case expression 1:
Statement 1;
break;
Case expression 2:
Statement 2;
break;
:
:
Case expression n:
Statement n;
break;
default:
default statement;
}
The expression used in a switch statement must have an integral or character type.
You can have any number of case statements within a switch. Each case is followed
by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will
fall through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.
First Run
Second Run
NOTE: switch case can also be explain/ask in jumping control and decision making
statements.
5. Functions
Que: what is the meaning of functions? Explain user defined functions.
AnsA function is a group of statements that together perform a task. Every C program has at
least one function, which is main(), and all the most trivial programs can define additional
functions. You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division is such that each function
performs a specific task. A function declaration tells the compiler about a function's name,
return type, and parameters. A function definition provides the actual body of the function.
Functions are divided into two types as following.
Library Functions
Library functions are predefined in C compiler. These functions have their predefined task. A
user can not modified these function, one can only call these functions in one‟s code. These
functions can only accessed with their headers files. printf() is a library function with
predefined task of printing string and variables on console.
Defining a Function
The general form of a function definition in C programming language is as follows:
Function Declarations
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately. A function declaration has the
following parts:
return_type function_name( parameter list );
Parameter names are not important in function declaration, only their type is required, so the
following is also a valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and you call
that function in another file. In such case, you should declare the function at the top of the file
calling the function.
Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task. When a program
calls a function, the program control is transferred to the called function. A called function
performs a defined task and when its return statement is executed or when its function-ending
closing brace is reached, it returns the program control back to the main program. To call a
function, you simply need to pass the required parameters along with the function name, and
if the function returns a value, then you can store the returned value.
For example:
maximum= max(10,20);
In above example max() is a function which have two integer arguments and it will return the
maximum number by comparing two numbers. Maximum number will return from function
and will save in variable maximum.
Note:- Return type of the function and variable used for calling function must have same data
type.
We can also use function calling direct in another functions. The above said function max()
can be called directly in printf().
For example:
Printf(“maximum number is = %d”,max(10,20));
Output
Q: differentiate between call by value and call by reference.
or
Q: Explain different methods passing arguments to the functions.
Ans. If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function. Formal
parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit. While calling a function, there are two ways in
which arguments can be passed to a function:
Call by Value
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument. By default, C programming
uses call by value to pass arguments. In general, it means the code within a function cannot
alter the arguments used to call the function.
Call by Reference
The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the
actual argument used in the call. It means the changes made to the parameter affect the
passed argument. To pass a value by reference, argument pointers are passed to the functions
just like any other value. So accordingly, you need to declare the function parameters as
pointer types.
Output
Output
When a recursive function is executed, the recursive function calls are not executed
immediately; rather they are placed on the stack until the termination condition for recursion
is encountered. The function calls are then executed in reverse order, as they are popped of
the stack.
Advantages of Recursion
It makes the program code compact which is easier to write and understand.
It is suitable to be used with data structure such as linked lists, queues, stacks etc.
Recursion is useful if a solution to a problem is in repetitive form.
The compact code in recursion simplifies the compilation as less number of lines
needs to be compiled.
Disadvantages of Recursion
Consumes more storage space as recursive calls automatic variables are stored in
stack.
It is less efficient in comparison to a normal program in case of speed and execution
time.
Special care need to be taken for stopping condition in a recursive function. If
condition is not specified it may result in an infinite recursion.
Note: A recursive function must have if statement somewhere in the function to force the
function to return a value in which recursive call is not being executed, otherwise it may fall
into infinite recursive loop.
Storage Memory
Default value Garbage value
Visibility Visible within block where variable is
declared e.g. if the variable is declared in a
function then it is only visible to that function
Life time It retains its value till control remains in the
block in which the variable is declared. E.g.
if the variable is declared in a function, it will
retain its value till the control is in that
function.
The register storage class is used to define local variables that should be stored in a register
instead of RAM. This means that the variable has a maximum size equal to the register size
(usually one word) and can't have the unary '&' operator applied to it (as it does not have a
memory location). Register are special storage areas within a computer‟s CPU. The actual
arithmetic and logic operations that comprise a program are carried out within these registers.
Normally these operations are carried out by transferring information from computer‟s
memory to these registers, carrying out the indicated operation and then transferring the result
back to the computer‟s memory. This process is repeated many times during the execution of
a program. A programmer can declare register variable within a block by prefixing its
declaration with register storage class specifier.
Syntax:
{
register int miles;
}
The register should only be used for variables that require quick access such as counters.
The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it comes into and goes
out of scope. Therefore, making local variables static allows them to maintain their values
between function calls. The static modifier may also be applied to global variables. When this
is done, it causes that variable's scope to be restricted to the file in which it is declared.
Programmer can declare a static variable using static storage class access specifier.
Syntax:
{
Static int i=1;
}
Unlike auto storage variable they are not created and destroyed each time the function in
which they declared is called, rather they are created once and they retain their value
throughout the life of a program. So the last value stored in the variable when the function is
exited is available within variable to the function, next time it is called. Default value for
static storage class is 0. So if a programmer does not assign initial value to a static variable,
then it automatically set to 0. Static variables are used in situations in which a programmer
wants to retain information between function calls such as number of times the function is
called etc.
Storage Memory
Default value Zero (0)
Visibility Visible within block where variable is
declared (same as auto).
Life time It retains its value between different function
calls i.e. when a function is called for first
time, static variable is created with initial
value zero, and in subsequent calls it retains
its present value.
The extern storage class is used to give a reference of a global variable that is visible to ALL
the program files. When you use 'extern', the variable cannot be initialized; however, it points
the variable name at a storage location that has been previously defined. When you have
multiple files and you define a global variable or function, which will also be used in other
files, then extern will be used in another file to provide the reference of defined variable or
function. Just for understanding, extern is used to declare a global variable or function in
another file. The extern modifier is most commonly used when there are two or more files
sharing the same global variables or functions as explained below.
File A File B
int x; // global variable extern int x;
void main() int func2()
{ {
............................ ......................
............................ ......................
func1(); }
func2();
}
int func1()
{
.............................
.............................
}
From the files shown above , the global variables x declared in file A can be used only
by the function main() and the func1(). However, if programmer wants to use it in file B, one
needs to place the declaration statement extern in x; in file B. This declaration indicates that
global variable x in some another file. This extends the scope of x into file B so that it can be
used by func2().
Storage Memory
Default value Zero (0)
Visibility Global
Life time It retains its value throughout the program so
the life time is as long as the program‟s
execution does not come to an end.
6. Arrays
Que: what is array? Explain its types.
Or
Q. Explain the concepts of Array in detail. Support your answer with suitable example.
Ans: Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type. Instead of declaring
individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.
The concept of array helps a programmer to store group of values under a single name and
refer directly to a particular value. This makes the program very simple and efficient. In C
programming arrays are in two main types.
Here data_type refers to the data type of array elements. arrayName is the name of
array and arraySize is refers to the maximum length of array size.
Same as above here data_type refers to the data type of array elements.
arrayName is the name of array. Difference is rowSize and columnSize instead of
arraySize. rowSize refers the maximum length of row whereas columnSize refers to
the maximum length of column.
Initializing Array
When an array is declared, its elements has values according to the storage class of
the array i.e. 0 value for static and extern and garbage value for auto and register. In „c‟ it is
also possible to initialize the elements of the array at the same place where they are declared
i.e. in the beginning itself.
Example
One dimensional array
int a[]={50,60,70,80,90};
In one dimensional array when it is declare and initialize at same place, then subscript is
optional.
Two dimensional array
int a[2][3]={10,20,30,40,50,60};
In this array there are two rows and three columns, so there are total six elements in the array.
Each row has three elements. First three elements belong to first row and other three belongs
to second row. The problem with this initialization is that it is not appropriate and
understandable. To resolve this problem we have another way to initialize an array.
int a[2][3]={10,20,30},{40,50,60};
The previous case was not clear to understand. But in this case programmer can easily
distinguish elements between rows. Each row is separated by curly braces({}).
or
char greeting[] = "Hello";
There is no need to place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array.
Example:
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main () {
getch();
}
Output
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10
Q: Discuss operations that are performed on arrays in C.
Or
Q: Explain insertion and deletion operation on arrays in C.
Ans:
Insertion operation: Insertion operation is used to insert a new element at specific position
in to array. In order to insert a new element into array we have to create space for new
element. Suppose there are N elements in an array and we want to insert a new element
between first and second element. We have to move last N-1 elements down in order to
create space for the new element.
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int array[100], position, c, n, value;
array[position-1] = value;
getch();
}
Deletion operation: Deletion operation is used to delete an element from specific position in
to array. In order to delete an element from array we have to check whether array contains
any element or not.
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int array[100], position, c, n;
getch();
}
Linear Search: Linear search is also called as sequential search. Linear search is a method
for finding a particular value in a list, which consists of checking every one of its elements,
one at a time and in sequence, until the desired one is found.
Second Run
Binary Search: This searching technique is applicable only for sorted array, but this
searching technique is faster than linear search.
Second Run
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
float a[2][2], b[2][2], c[2][2];
int i, j;
if(j==1)
printf("\n");
}
getch();
}
In this method initial address of the array is passed to the pointer, as we know that all
array elements are stored in contiguous memory location, all other elements can be accessed
with the help of arithmetic operation on pointer.
A pointer is a variable whose value is the address of another variable, i.e., direct address of
the memory location. Like any variable or constant, programmer must declare a pointer
before using it to store any variable address. The general form of a pointer variable
declaration is:
Data_type *var-name;
Here, data_type is the pointer's base type; it must be a valid C data type and varname is the
name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used
for multiplication. However, in this statement, the asterisk is being used to designate a
variable as a pointer.
For example
int i=5;
int *ptr;
ptr=&i;
Advantages of pointers
Sometime it is more convenient or flexible to work with the address of a variable than
the actual variable.
Using pointers, program can access any memory location in the computer‟s memory.
Array and structures can be handled more efficiently with pointers.
Low level system programming can be done through the use of pointers.
It will become impossible to create complex data structures without pointers.
output
Pointer Arithmetic
It may be noted that pointer can also be incremented to an immediately next location of its
type e.g. if the contents of a pointer p of type integer are 1002 then the content of p++ will be
1004 instead of 1003. The reason being that an int is always of 2 bytes size and therefore
stored in two memory locations. The amount of storage taken by various types of data is
tabulated as below:-
Type Amount of storage
character 1 byte
Int 2 bytes
Float 4 bytes
Long 4 bytes
double 8 bytes
Thus a pointer of float type will point to an address of 4 bytes of locations and therefore an
increment to this pointer will increment its contents by 4 locations.
Formula
New value= current address+ i* size_of(data type)
For Example:
int arr[4];
In the above example, arr and &arr[0] points to the address of the first element. &arr[0] is
equivalent to arr Since, the addresses of both are the same, the values of arr and &arr[0] are
also the same.
In C, you can declare an array and can use pointer to alter the data of an array.
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
Example
#include <stdio.h>
#include <math.h>
Void main()
{
int arr [ ][3] = {{11,12,13}, {21,22,23},{31,32,33},{41,42,43},{51,52,53}};
int I , j ;
int *p , (*q) [3], *r ;
p = (int *) arr ;
q = arr;
r = (int *) q ;
printf ( " %u %u %d %d %d %d \n ", p , q , *p , *(r) , *(r+1), *(r+2));
p++ ;
q++ ;
r = (int *) q ;
printf ( " %u %u %d %d %d %d \n ", p , q , *p , *(r) , *(r+1), *(r+2));
}
In above example pointer p and a pointer array q. The first assignment statement is to make
the pointer p points to the array arr. While assigning, declare the type of the variable arr.
Note that variables on both side of this statement should have the same type. Next line is a
similar statement, now with q and arr. Since q is a pointer array, the array can be directly
assigned to it and there is no need for specifying the type of the variable. In the next line the
pointer r points to the pointer array q. Here is what we get from this,
32 21 22 33 44 32 21 22 33 44 11 11 12 13
32 21 22 33 48 32 21 22 33 56 12 21 22 23
Here we see that incrementing p make it just jump through each element of the array, where
as incrementing q, will move it from one row to another row.
Example
#include <stdio.h>
#include <conio.h>
void main () {
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;
p = balance;
getch();
}
Points to Note:
1) Pointer variable data type is same as the type of array.
2) Pointer has been initialized by array 1st element address(subscript 0 for e.g. &val[0]).
3) In the loop the increment operation(p++) is performed on the pointer variable to get the
next location (next element‟s location), this arithmetic is same for all types of arrays (for all
data types double, char, int etc..) even though the bytes consumed by each data type is
different.
4) we can also use p=a where a is an array (or a[ ] )This is because the array name without
braces holds the address of first element of the array. Which means below statement holds
true.
Example
#include <stdio.h>
#include <conio.h>
main() {
clrscr();
int *array[3];
int x = 10, y = 20, z = 30;
int i;
array[0] = &x;
array[1] = &y;
array[2] = &z;
for (i=0; i< 3; i++) {
printf("The value of %d= %d ,address is %u\t \n", i, *(array[i]),
array[i]);
}
getch();
return 0;
}
malloc()
The name malloc stands for "memory allocation". The function malloc() reserves a block of
memory of specified size and return a pointer of type void which can be casted into pointer of
any form.
Syntax of malloc()
ptr=(cast-type*) maloc(byte-size);
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
Ptr=(int*) malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively
and the pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation". The calloc() function is another
alternative to malloc(). Just like malloc() functions it also allocates block of memory run time
but the only difference between malloc() and calloc() is that, malloc() allocates single block
of memory whereas calloc() allocates multiple blocks of memory each of same size and sets
all bytes to zero.
Syntax of calloc()
Ptr=(cast-type*)calloc(n,elements-size);
This statement will allocate contiguous space in memory for an array of n elements. For
example:
Ptr=(float* )calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size
of float, i.e, 4 bytes.
realloc()
realloc() function enables you to change the size of the previously allocated memory by
malloc(), calloc() or by itself. If the previously allocated memory is insufficient or more than
required, you can change the previously allocated memory size using realloc() function.
Syntax of realloc()
ptr=realloc(ptr,newsize);
free()
Memory is limited recourse. Once should allocate exactly the required piece of memory
before one need it, and release as soon as he/she don‟t need it. So that it can be reused.
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its
own. You must explicitly use free() to release the space.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
9. String Manipulation C
Que: Explain String handling functions available in c.
Ans: There are a large number of library functions available in „C‟ that allow to operate on
strings. Using these functions, the string can be compared, copied or concatenated. They all
are included in a header file string.h. String handling functions in „C‟:-
strlen(s)
The strlen(s) function take one argument s which can be string constant or a string
variable. It returns length of the string stored in the array a i.e number of characters in the
string excluding the NULL character („\0‟). If string is empty, it returns zero. If String s[]=
˝Munish˝; the statement,
x=strlen(s);
x will be assigned 6 as returned value from function.
strcpy(s1,s2)
The strcpy() function takes two arguments as string variables(second can be string
constant too) and copied the value of second string to first string variable. If first string
argument has some previous value, this function will replace it with second string argument.
Example: char s2=˝C programing˝;
strcpy(s1,s2);
s1 will have same content as s2 after calling strcpy() function.
strcmp(s1,s2)
The strcmp() function compares the contents of string s1 with the content of the
string s2 by comparing successive corresponding characters, starting with the first character
in each string. This process continues until either the corresponding characters are formed to
be different of the last character in one or both strings is reached. Characters are compared
lexicographically.
strcmp(s1,s2)
This function returns an integer value depending upon the relative order of the two strings. It
returns 0 if both strings are identical. It will return a positive value if first string is greater and
negative value if second string is greater.
strcat(s1,s2)
The strcat() function concatenates two strings together. It takes two strings i.e.
character arrays as arguments of which first arguments s1 is a string variable and the second
argument s2 can be a string variable or string constant. This function appends a copy of s2 to
the end of s1. The first character of s2 overwrites the terminating NULL character(„\0‟) of s1.
The length of the resulting string is strlen(s1) + strlen(s2). In addition string s2 to string s1
this function also returns s1. Its syntax is as follows. Concatenated
strcat(s1,s2)
strlwr(s)
The strlwr() function converts the uppercase letters in a given string s to lowercase. It
takes one argument s which is a string variable. Its takes the following form.
Strlwr(s).
After converting the string into lowercase, it stores the result back in string s and returns
string s.
strupr(s)
The strupr() function converts the lowercase letters in a given string s to uppercase. It
takes one argument s which is a string variable. Its takes the following form.
Strupr(s).
After converting the string into uppercase, it stores the result back in string s and returns
string s.
Output
10. Structures and Unions
Que: Explain in detail structure in ‘C’ language?
Ans: Structure
Structure is a user defined data type , this is used to store different kind of data types in a
single block. Structures are used to represent a record. Suppose you want to keep track of the
information of students. You might want to track the following attributes about each student:
Roll_num
Name
Class
Marks
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new
data type, with more than one member. The format of the struct statement is as follows:
The structure tag is optional and each member definition is a normal variable definition, such
as int i; or float f; or any other valid variable definition. At the end of the structure's
definition, before the final semicolon, you can specify one or more structure variables but it is
optional.
Initializing structure
When a structure variable is declared, its data members are not initialised and therefore
contain undefined values. Similar to simple variables and arrays, the structure variables can
also be initialized. For instance the structure can be declared and initialized as shown below:-
struct student
{
int roll_num;
char name[20];
char clas[10];
int marks;
};
struct student s1={731,”Munish Kumar”,”MCA”,77};
The values are assigned to the members of the structure in order of their appearance i.e. first
value is assigned to the first member, second to second and so on. But the thing which should
remember during assigning the values is that the data type of data members of structure and
values should be same.
Accessing Structure Members
To access any member of a structure, we use the member access operator (.). The member
access operator is coded as a period between the structure variable name and the structure
member that we wish to access. You would use the keyword struct to define variables of
structure type. The following example shows how to use a structure in a program.
Output
struct struct-name
{
datatype var1;
datatype var2;
----------
----------
datatype varN;
};
Example
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct student
{
int rollno;
char name[10];
};
void main()
{
int i;
struct student st[5];
clrscr();
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
getch();
}
Q: Write a note on nested structures in C.
Ans. The C language permits structures to be nested, in which a structure can contain
structure members. A structure may be declared inside another structure. Also, a structure
may be a data member of another structure.
struct date
{
int date;
int month;
int year;
};
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp1;
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp1;
Accessing Nested Members:
Example
#include <stdio.h>
#include <conio.h>
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
struct student_database
{
char name[10];
int roll;
int marks;
}stud1;
struct student_database *ptr;
ptr = &stud1;
#include <stdio.h>
void main()
{
struct student_database
{
char name[10];
int roll;
int marks;
}stud1;
stud1.roll = 10;
stud1.marks = 90;
Roll Number : 10
Marks of Student : 90
Pointer variable is declared and pointer to structure. Whenever we declare pointer variable
,address of the structure variable is assigned to the pointer variable.
Example 2
#include <stdio.h>
void main(int argc, char *argv[])
{
struct student_database {
char name[10];
int roll;
int marks;
}stud1 = {"Pritesh",90,90};
Roll Number : 90
Marks of Student : 90
Example 3
#include <stdio.h>
void main(int argc, char *argv[])
{
struct student_database {
char name[10];
int roll;
int marks;
}stud1 = {"Pritesh",90,90};
Whenever we access the member of the structure using the pointer we use arrow operator to
access the member of structure.
Union
Like structure union are also of derived data type. Both structure and unions are used to
contain members or variables of different types in a single unit. While structures are used to
store different members at different places in memory, a union is used to store different
members at same memory location. Thus unions are used to conserve memory. In union
memory assignment is the largest memory of union whereas in structure, the memory
reserved is the total sum of members to be used by all the members of structure.
Defining a union
To define a union, one must use the union statement. The union statement defines a new data
type, with more than one member same as struct. The format of the union statement is as
follows:
The union tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the union's definition,
before the final semicolon, you can specify one or more union variables but it is optional.
E.g.
Union sample
{
char a;
int b;
float c;
}
In this example union contains three members, each with a different data type. However
programmer can use only one of them at a time. This is because only one location is allocated
for union variables, irrespective of its size.
1004 1005 1008 1007
a
b
c
Object of a union type can be declared either at the same time of union type definition or after
the union type definition in a separate declaration statement. Objects of the union type can be
created after union definition only if the defined union type is named or tagged.
Structure Union
Memory Allocation Members of structure do not A union shares the memory
share memory. So A structure space among its members so
need separate memory space no need to allocate memory to
for all its members i.e. all the all the members. Shared
members have unique storage. memory space is allocated i.e.
equivalent to the size of
member having largest
memory.
Member Access Members of structure can be At a time, only one member of
accessed individually at any union can be accessed.
time.
Keyword To define Structure, ‘struct’ To define Union, ‘union’
keyword is used. keyword is used.
Initialization All members of structure can Only the first member of Union
be initialized. can be initialized.
Size Size of the structure is > to the Size of union is equivalent to
sum of the each member’s size. the size of the member having
largest size.
Syntax struct struct_name union union_name
{ {
structure ele 1; union ele 1;
structure ele 2; union ele 2;
———- ———-
———- ———-
structure ele n; union ele n;
}struct_variable_name; }union_variable_name;
Change in Value Change in the value of one Change in the value of one
member can not affect the member can affect the value of
other in structure. other member.
11. Files in C
Que: Explain different I/O operation on files.
Ans: A file is a named section of storage, usually on disk to hold information. „C‟ views a
file as a continuous sequence of bytes, each of which can be read individually. Each file has a
start and an end. It has a current position that typically defines the number of bytes from the
start. Program can be designed to perform read write operation on a file. But before one
performs any operation on a file, he/she need to open it and once the task is finished file
should be closed.
A text file consists of sequence of characters. Each character line in a text may be
terminated by a newline character in most of the compilers. Each alphanumeric character
stored occupies one byte.
A binary file is a series of bytes exactly as it appears in memory. They are primarily
used for non-textual data, which is used to keep the exact contents of the file. To work with
these files, one has to explicitly open these files in binary mode.
To perform any I/O operation on a file, the following sequence should be followed in a
program.
Declare a file pointer.
Open file through program and assign a file pointer to it
Manipulate contents of the file using file pointer i.e. perform read/ write operations.
Close the file.
Opening Files
You can use the fopen( ) function to create a new file or to open an existing file. This call
will initialize an object of the type FILE, which contains all the information necessary to
control the stream. The prototype of this function call is as follows:
Here, filename is a string literal, which you will use to name your file, and access mode can
have one of the following values:
Mode Description
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is:
The fclose() function returns zero on success, or EOF if there is an error in closing the file.
This function actually flushes any data still pending in the buffer to the file, closes the file,
and releases any memory used for the file. The EOF is a constant defined in the header file
stdio.h. There are various functions provided by C standard library to read and write a file,
character by character, or in the form of a fixed length string.
Writing a File
The function fputc() writes the character value of the argument c to the output stream
referenced by fp. It returns the written character written on success otherwise EOF if there is
an error. You can use the following functions to write a null-terminated string to a stream:
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-
negative value on success, otherwise EOF is returned in case of any error. You can use int
fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file.
Reading a File
Given below is the simplest function to read a single character from a file:
Output
output
output
Output
First run
Second run
Program to find whether a given number is Armstrong or not.
Output
First run
Second run
Program to sort array elements using bubble sort.
Output
Second Run