BCA C Language 2020-21
BCA C Language 2020-21
Name : ……………………………..
Roll No : ……………………………..
1. Machine Language
2. Assembly language
3. High level Language
1. Machine Language
It is a computers natural language, which can be directly understood by the system. The
machine language program is written as strings of 1s and 0s. Every computer can understand
machine language without any translation. It is also called low level programming language. A
machine language instruction normally has two part format. The first part is the operation code
that tells the computer what function to perform, and the second part is operand that tells
where to find or store the data on which the computer has to perform the function.
OPCODE OPERAND
(Operation code) (address/location)
3. Error prone. The programs written in these languages are so prone to frequent errors
that they are very difficult to maintain.
4. Difficult to modify. It is difficult to correct or modify machine language programs.
Checking instructions to locate errors is very difficult and time consuming.
5. Speed of writing, Testing and Debugging is very slow in machine language.
2. Assembly Language
Some examples of assembly language mnemonics and its operation codes are mentioned
below
A sample assembly language program for adding two numbers and storing the result is given
below
1. Easier to understand and use. Due to the use of mnemonic codes instead of numeric
codes for instructions and symbolic names for data locations instead of numeric
address, assembly language programs are easy to understand and use.
2. Easier to locate and correct errors. The detection and correction of errors are easy in
this language due to the use of mnemonics.
3. Easy to modify. It is easier to locate, correct and modify instructions of an assembly
language program than a machine language program.
4. No worry about address. Programmers need not keep track of storage locations of data
and instructions while writing assembly language program.
5. Easily re-locatable. We can change a programs location by changing the pseudo
instructions.
6. Efficiency of machine language. The length of assembly language program is same as
the resulting machine language program. Hence the execution time for the program
would be the same.
5. They do not deal with machine level coding. Rather, they deal with high level coding,
enabling the programmers to write instructions using English words and mathematical
symbols and expressions.
Language Translators
A program is a set of instructions for performing a particular task. A program can be written in
assembly language as well as in high level language. This written program is called source
program. The source program is to be converted to the machine language, which is called an
object program. A translator is required for such translation.
Program translator translates source code of programming language into machine language
instruction code. Programming language translators are classified into
1. Assembler
2. Compiler
3. Interpreter
Assembler
Assembler is a software that translates Assembly Language program into Machine Language. It
is so called because in addition to translating it also “assembles” the machine language
program in main memory of the computer, and makes it ready for execution. The symbolic
language is translated to the machine code in the ratio of one is to one symbolic instructions to
one machine code instructions. Such type of languages are called low level languages.
Input Output
Mnemonic Language Assembler Machine Codes
(Assembly Language)
Compiler
A compiler is a translator program that translates high level language program into its
equivalent machine language program. The entire program will be read by the compiler first
and generates the object code. The compiler translates each high level language instructions
into a set of machine language instructions rather than a single machine language instruction.
Hence, there is a one to many correspondence between the instructions of source program
and the object program. Compilers also detect and indicate syntax errors. Compilers also have
the ability of linking subroutines of the program. Languages such as C, C++ and Java compilers
are employed.
Input Output
High-level language program Compiler Machine language
program
Interpreter
This language translator converts a HLL program into machine language by converting and
executing it line by line. If there is any error in one line, it reports and execution of program is
terminated at the same time. We can resume the execution of the program only after
rectification of the error. Interpreter directly executes the program from its source code. Due
to this, every time the source code should be inputted to the interpreter.
The main advantage of interpreters over compilers is that an interpreter flag syntax error in a
program statement as soon as it interprets the statement. This allows the programmer to make
corrections during program development.
The disadvantage of the interpreter is that they are slower than compilers when running a
finished program.
Input Output
High-level language Interpreter (translates and executes Result of
program statement by statement) Execution
program
Linker
C language provides a very large library, which contains numerous functions. Linker is a
program that combines source code and codes from library. Linking is the process of bringing
together source program and library code.
3. Abstraction
Abstraction means the ability to define and then use complicated structures or operations in
ways that allows programmers to ignore many of the details. The degree of abstraction allowed
by a language directly affects its ease of programming. For example object oriented languages
support high degree of abstraction.
4. Efficiency
A program written in a good programming language enables a computer system to translate it
into machine code efficiently, execute it efficiently, and manage it with less memory space.
5. Structured programming support
A good programming language should have necessary features to allow programmers to write
their programs based on the concepts of structured programming. This property affects the
ease with which a programmer can write, test, and maintain his/her programs.
6. Compactness
In a good programming language, programmers should be able to express the intended
operations concisely without loosing readability. Programmers generally do not like a verbose
language because they need to write too much.
7. Extensibility
A good programming language should also allow extension through simple, natural and elegant
mechanism. Almost all languages provide subprogram definition mechanisms for this purpose.
8. Suitability to its environment
A good programming language must be suitable to its operating environment. For example a
language for real time applications must be interactive in nature. On the other hand a language
for data processing applications like payroll, stores accounting etc. may operate in batch mode.
5. Execution efficiency
The features of a good programming language discussed above often influence the selection
process.
Subprogram
A subprogram is a program written in a manner that a programmer can use it in other
programs whenever needed without rewriting. Other names used for it are subroutine,
subprocedure, and function.
The structure of a subprogram consists a header and body. The subprogram header which is
the first line of a subprogram, provides a name for the subprogram, and it may optionally
specify a list of parameters( also known as arguments). Other programs use the subprogram
name to refer to the subprogram when they want to use it. The parameters are specific
variable names, numeric values, or other data you want the subprogram to use when it
executes the instructions in its body. The subprogram body contains the instructions that
perform the intended task of the subprogram.
1. Algorithm
2. Flowchart
3. Pseudo-code
Algorithm
Step by step method for solving a problem is called algorithm. The algorithm is a very
popular technique used to obtain a solution for a given problem. The algorithm is defined as
‘the finite set of steps, which provide a chain of actions for solving a definite nature of
Classification of Algorithms
The classification of algorithm is based on repetitive steps and on control transfer from one
statement to another.
Algorithms
i. Direct Algorithm : In this type of algorithm, the number of iterations is known in advance. For
example for displaying the numeric numbers from 1 to 10, the loop variable should be
initialized from 1 to 10.
ii. Indirect Algorithm: in this type of algorithm, repetitively steps are executed. Exactly how
many repetitions are to be made is unknown. Example- to find the first three palindrome
numbers.
iii. Deterministic: deterministic algorithm is based on either to follow a ‘yes’ path or ‘no’ path
based on the condition. Example- testing whether number is even or odd.
iv. Non-Deterministic: in this type of algorithm to reach to the solution, we have one of the
multiple paths. Example – to find a day of a week.
v. Random Algorithm: after executing few steps, the control of the program transfers to
another step randomly, which is known as a random algorithm. Example is a random search.
Flowcharts
A flowchart is the pictorial representation of an algorithm. Or a flowchart is a visual
representation of the sequence of steps for solving a problem. It uses different symbols to
denote different types of instructions. The symbols used in a flowchart are
1. Terminal
It is used to denote the beginning (START) and ending (STOP) in the program logic. It is
the first and last symbol in a flowchart. In addition if the program logic has a pause we
also indicate it with a terminal symbol.
Start
Stop
2. Processing
A rectangle is used for processing steps. A processing symbol represents arithmetic and
data movement instructions. It used for data handling, and values are assigned to the
variables in this symbol. There are two flow lines connected with the process symbol.
One line is incoming and the other line goes out.
Z=X+Y X5
P=X*Y AX+Y
3. Decision
Diamond shaped (rhombus) boxes are used to indicate conditions tested. This box shows
branching of control upon conditions. While solving a problem one can take a single, two or
multiple alternatives depending upon the situation.
Single alternative decision: Here more than one flow line can be used depending upon the
condition. It is usually in the form of a ‘yes’ or ‘no’ question, with branching flow line
depending upon the answer.
Entry
Condition ?
True False
Execution of statement(s)
Exit
Two alternative decisions: in two alternative decision on satisfying the condition statements
pertaining to 1 action will be executed, otherwise the other statements for action 2 will be
executed.
Entry
Condition ?
True False
Execution of Execution of
action 1 action 2
Exit
Multiple alternative decision: every decision block has two branches. In case the condition is
satisfied, execution of statements of appropriate blocks take place, otherwise next condition
will be verified. If condition 1 is satisfied then block 1 statements are executed. in the same
way other decision blocks are executed.
Entry
True
Condition 1 Execution of Block 1
False
True
Condition 2 Execution of Block 2
False
True
Condition 3 Execution of Block 3
False
Exit
4. Flow Lines
Flow lines with arrow heads indicate flow of operation, which is the sequence of
execution of instructions.
5. Connector
The connector symbol is used to establish the connection, whenever it is impossible to directly
join two parts in a flowchart. The connector symbols are used to continue a flowchart on to the
next page.
6. Loop Symbol
It looks like hexagon. This symbol if used for implementation of for loops only.
Four flow lines are associated with this symbol. Two lines are used to indicate the sequence of
the program and remaining two are used to show the looping area.
Entry
For J = 1 to 10 by step 2
Exit
7. Input / Output
Parallelograms are used to represent input and output operations. It is used to input
and output the data.
Read X, Y Print X, Y
Delay symbol: Symbol of delay is just like ‘AND’ gate. It is used for adding delay to the process.
Manual input symbol: this is used for assigning the variable values through the keyboard,
whereas in data symbol the values are assigned directly without manual intervention.
Flowcharting Rules
1. First chart the main line of logic and then incorporate detail.
2. Maintain a consistent level of detail for a given flowchart.
3. Do not chart every detail, as the flowchart is only a graphic representation of steps in a
program.
4. Words in the flowchart symbols should be common statements and easy to understand.
5. Be consistent in using names and variables in the flowchart.
6. Go from left to right and top to bottom in constructing flowcharts.
7. Keep the flowchart as simple as possible.
8. If a new flowcharting page is needed, it is recommended that the flowchart be broken
at an input or output point. Moreover properly labeled connectors should be used to
link the portions of the flowchart on different pages.
Advantages of flowchart
1. Better communication
It is easier for a programmer to explain the logic of a program through a flowchart.
2. Efficient Analysis
The program can be analyzed efficiently through the flowchart.
3. Proper program documentation
It means maintaining a complete record of the program and associated documents.
4. Effective coding
Once a flowchart is ready it is easy to write programs using it.
5. Effective Synthesis
If a problem is divided in to different modules and the solution for each module is
represented in flowchart separately, they can finally be placed together to visualize the
overall system design.
Limitations of Flowcharts
1. Flowcharts are very time consuming and laborious to draw with proper symbols and
spacing, especially for large complex algorithms
2. Any changes or modification in the logic of the algorithm usually require a completely
new flowchart
3. There are no standards determining the amount of detail that should be included in a
flowchart.
Pseudocode
Pseudocode is another program-planning tool used for planning program logic. “Pseudo”
means imitation or false and “Code” refers to the instructions written in a programming
language. Pseudocode, therefore, is an imitation of actual computer instructions. These pseudo
instructions are phrases written in a natural language (eg. English, French, German etc.) that a
computer cannot understand. Since the emphasis of pseudocode is on program design, it is
also known as Program Design Language (PDL).
During early days of program development, many programmers developed program logic for
large programs with mazes of branches (jumps from one portion of the program to another)
that altered the sequence of processing operations. Such programs are now referred to as
“spaghetti code” because their program flowcharts appeared more like a plate of spaghetti
than like logical analysis of programming problems. Understanding the logic of such programs
was very difficult for someone other than the developer. Also these programs are very difficult
to modify.
Researchers later proved that it is possible to express any program logic, no matter how
complex, by using only the following three logic (control) structures.
1. Sequence logic
2. Selection logic
3. Iteration (or looping) logic
Writing of programs by using these three basic control structures was termed structured
programming technique. They also helps in reducing program errors and the time spent in
program testing.
Sequence Logic
Sequence logic performs instructions one after another in sequence. Thus for writing
pseudocode instructions for sequence logic, we write the instructions in the order (or
sequence) of their execution. Logic flow of pseudocode is from top to bottom.
Selection Logic
Selection logic, also known as decision logic, makes decisions. It selects a path out of two or
more paths in program logic. We depict selection as an IF … THEN … ELSE, or an IF…THEN, or a
CASE structure.
IF…THEN…ELSE structure means that if the condition is true, then do Process 1, else if the
condition is not true do Process 2.
Example:
IF Condition
THEN Process 1
ELSE Process 2
ENDIF
If we do not want to choose between two processes, and simply want to decide whether to
execute a process or not, then we use IF…THEN structure. IF…THEN structure means that if the
condition is true, then do Process 1, otherwise skip over Process 1.
Example:
IF Condition
THEN Process 1
ENDIF
CASE structure represents multiple way selection logic. It allows choosing from more than two
control paths in a program logic enabling selection of one of any number of statements or
statement groups.
Example:
CASE Type
Case Type 1: Process 1
Case Type 2: Process 2
Case Type n: Process n
ENDCASE
The above CASE statement indicates that if the value of Type is equal to Type-1, execute
Process 1, if it is equal to Type-2, execute Process 2, if it is equal to Type-3, execute Process 3,
and so on.
In case of IF…THEN and IF…THEN…ELSE decision structures, ENDIF indicates their end; and in
case of CASE structure, ENDCASE indicates its end.
In DO…WHILE looping continues as long as the condition is true, and stops when the condition
is not true. Since program logic tests the condition for looping at the beginning of the loop, if
the condition is false when it first encounters the loop, it will not execute the statements in the
loop at all (not even once). On the other hand, in REPEAT…UNTIL, looping continues until the
condition becomes true. That is, program logic repeats execution of statements within the loop
as long as the condition is not true. Since it tests the condition for looping at the end of the
loop, it will execute the statements in the loop at least once.
In both DO…WHILE and REPEAT…UNTIL, the loop must contain a statement, which changes the
condition that controls the loop. if it does not, looping continue without end, becoming an
infinite loop.
REPEAT
Process 1
Process n
UNTIL Condition
Example: Pseudocode to find largest of two numbers
Get numbers a & b
Compare a & b
If a is large max=a
If b is large max=b
Larger number is max
Advantages of Pseudocode
1. As compared to a flowchart, converting a pseudocode to a programming language is
much easier.
2. As compared to a flowchart, it is easier to modify the pseudocode of program logic
when program modifications are necessary.
3. Writing of pseudo code involves less time and effort than drawing an equivalent
flowchart.
Limitations of Pseudocode
1. In case of a pseudocode, a graphic representation of program logic is not available.
2. There are no standard rules to follow in writing pseudocode.
3. As compared to flowchart, beginners often find it more difficult to write pseudocode of
program logic or to follow a program’s logic from its pseudocode.
coded it wrongly as a=b-c; it is an example of logic error because the program will not produce
correct result.
3. Run-time Errors: Errors which occur during program execution (run-time) after successful
compilation are called run-time errors. One of the most common run-time error is division by
zero
4. Semantic Errors: This error occurs when the statements written in the program are not
meaningful to the compiler. (Example: a + b = c;)
Testing a Program
Identifying logic errors in a program is the responsibility of the program development and test
team. The testing procedure involves running the program to process input test data, and
comparing the obtained results with the known correct results. If the results obtained for the test
data do not match with the known correct results, most likely the program contains one or more
logic errors.
In order to test the logic of a program completely, its test data must test each logical function of
the program. The test data selected for testing a program should include:
1. All types of possible valid data.
2. All types of possible invalid data (such as incorrect, incomplete, or inappropriate data). This
is necessary to test the error handling capabilities of the program (how the program reacts
in case of abnormal and unusual input data).
memory and CPU registers at the time when program hangs up. This information called
memory dump or storage dump lists the data and information in their raw form that is their
binary or equivalent hexadecimal or octal form. By doing a proper analysis of this listing,
the programmer can detect the cause of the problem.
If the software is to be sold commercially, instead of releasing it directly in the commercial market
after alpha testing, the team sometimes releases it for additional testing to a selected set of users
such as long time customers, partner agencies, and at times put for download and trial by anyone.
This release version of the software is known as beta version. The users report any bug found in the
software to the company developing the software. This type of testing is known as beta testing.
After beta testing the team fixes the reported bugs if any, and then the company releases the
software to the commercial market.
1. Problem Identification
The given problem is clearly stated with all assumptions and specifying actions to be taken in the event
of any possibility. Details of inputs, processing and results required are clearly identified.
2. Algorithm and Flowcharts
Once the problem is identified, it is necessary to evolve a detailed and precise step-by-step method of
solution. For this algorithm and flowcharts are used.
Algorithm
Step by step method for solving a problem is called algorithm.
Flowchart
A flowchart is the pictorial representation of an algorithm.
4. Translation
The program written in a High Level Language is known as source code. Once the source code is
prepared it should be translated using the concerned language processor. The compiler or interpreter is
used for this purpose. The translated machine language program is called the object code.
5. Debugging
Program errors are known as bugs and the process of detecting and correcting these errors is called
debugging. There are two types of errors – syntax error and logical error. Syntax errors result when the
rules or syntax of the programming language are not followed. A logical error is caused by a wrong or
incorrect program step.
7. Documentation
Documentation is the process of providing sufficient information in a program to understand its
working. A computer program is documented by writing comments in it.
1. Write an Algorithm and draw a Flowchart to find the sum of Two numbers
Step 2: Read A, B
Read A, B
Step 3: SUM = A + B
Print SUM
STOP
2. Write an Algorithm and draw a Flowchart to find the sum and average of 3 numbers
Step 2: Read A, B, C
Read A, B, C
Step 3: SUM = A + B + C
Step 6: Stop
Print SUM,
AVG
STOP
3. Write an Algorithm and draw a Flowchart to find the largest among two numbers
Algorithm Flow Chart
Step 1: Start
START
Step 2: Read A, B
Step 3: IF A > B then go to step 4 else go to step 5
Step 4: Print A Read A, B
Step 5: Print B
Step 6: Stop
Yes No
IF A> B
Print A Print B
STOP
4. Write an algorithm and draw a flowchart to find the largest among 3 numbers.
Algorithm
Step 1: Start
Step 2: Read A, B, C
Step 3: IF A > B then go to step 4 else go to step 5
Step 4: IF A > C then go to step 6 else go to step 7
Step 5: IF B > C then go to step 8 else go to step 7
Step 6: Display A
Step 7: Display C
Step 8: Display B
Step 9: Stop
Flowchart
START
READ A, B, C
No IF A > B Yes
No Yes No Yes
IF B > C IF A > C
STOP
5. Write an algorithm and draw a flowchart to print the odd numbers from 1 to 25
Algorithm
Step 1: Start
Step 2: Let N = 1
Step 3: Print N
Step 4: N = N + 2
Step 5: Check IF N < = 25 Then goto step 3 Else goto step 6
Step 6: Stop
Flowchart
START
N=1
PRINT N
N=N+2
Yes
IF N<= 25
No
STOP
6. Write an algorithm and draw a flowchart to find the sum and average of any 10 numbers
Algorithm
Step 1 : Start
Step 2 : SUM=0, COUNT=1 Flowchart
Step 3 : Read A
Step 4 : SUM = SUM + A START
Step 5 : COUNT = COUNT + 1
Step 6 : If COUNT <= 10 Goto Step 3 Else Goto Step 7
Step 7 : AVG = SUM / 10 S = 0, C = 1
Step 8 : Print SUM, AVG
STEP 9 : Stop Read A
S=S+A
C=C+1
IF c<= 10
AVG = S / 10
Print S,
AVG
STOP
7. Write an algorithm and draw a flowchart to find the smallest among 10 numbers
Algorithm Flowchart
Step 1 : Start
Step 2 : C = 1
Step 3 : Read N Start
Step 4 : SMALL = N
Step 5 : C = C + 1 C=1
Step 6 : Read N
Step 7 :If N < SMALL Then Goto Step 8 Else Goto Step 9
Read N
Step 8 :SMALL = N
Step 9 : C = C + 1
Step 10: If C< =10 Then Goto Step 6 Else Goto Step 11 SMALL= N
Step 11: Print SMALL
Step 12: Stop C = C+1
Read N
If
N<SMALL No
L
Yes
SMALL = N
C=C+1
Yes
If C <= 10
No
Print
SMALL
Stop
8. Write an algorithm and draw a flowchart to find the given number is even or odd
Algorithm
START
Step 1: Start
Step 2: Read A
Step 3: IF A% 2 = 0 then go to step 4 else go to step 5 Read A
Step 4: Print Even
Step 5: Print Odd
Step 6: Stop Yes IF No
A%2=0
STOP
9. Write an algorithm and draw a flowchart to find the sum of first N natural numbers
Step 1 : Start
Step 2 : SUM=0, C=1 Flowchart
Step 3 : Read N
Step 4 : SUM = SUM + C START
Step 5 : C = C+ 1
Step 6 : If C <= N Goto Step 4 Else Goto Step 7
Step 7 : Print SUM SUM = 0, C = 1
STEP 8 : Stop
Read N
SUM = SUM+ C
C=C+1
Yes
IF C<= N
NO
Print SUM
STOP
10. Write an algorithm and draw a flowchart to find the factorial of a number
Step 1 : Start
Step 2 : FACT=1, C=1 Flowchart
Step 3 : Read N
Step 4 : FACT = FACT * C
START
Step 5 : C = C+ 1
Step 6 : If C <= N Goto Step 4 Else Goto Step 7
Step 7 : Print FACT FACT = 1
STEP 8 : Stop C=1
Read N
FACT = FACT * C
C=C+1
IF C<= N Yes
NO
Print FACT
STOP
11. Write an algorithm and draw a flowchart to swap two numbers without using a third variable.
Step 1: Start
Step 2: Declare two variables a & b
Step 3: Addition of a & b and place result in a.
START
Step 4: Subtraction of a & b and place result in b.
Step 5: Subtraction of a & b and place result in a.
Step 6: Print values of a & b. Declare variables &
Step 7: End. assign values to a & b
a=a+b
b=a-b
a=a-b
Print values
of a & b
END
UNIT 2
C LANGUAGE
C language has been developed by Dennis Ritchie at Bell Laboratories, USA, in 1972. In 1967,
Martin Richards developed a language called BCPL ( Basic Combined Programming Language)
and in 1970, Ken Thompson created a language using many features of BPCL and called it B.
Several important concepts of C are drawn from BCPL and B language.
C runs under a number of operating systems including MS DOS and UNIX. The UNIX operating
system was coded almost entirely in C.
In 1978, Brian Kernighan and Dennis Ritchie published the first edition of “The C Programming
Language”. This book, known to C programmers as "K&R", served for many years as an
informal specification of the language. The version of C that it describes is commonly referred
to as K&R C.
C is a general purpose structured programming language. The c is very popular because of its
portability. That is a program written in c can be transferred easily from one computer to
another with minimal changes or none at all. Programs written in c are fast and efficient.
In 1983, the American National Standards Institute (ANSI) appointed a committee to define a
standard for C. In 1989, the standard was ratified and this version of the language is often
referred to as ANSI C, Standard C, or sometimes C89. It was then approved by the International
Standards organization (ISO) in 1990.
There is no single compiler* for c. Many different organizations have written and implemented
c compilers. (Eg:- Turbo c, Borland c)
(* A compiler is a language processor which converts High Level Language programs into
Machine Language Program.)
Features of c language
1. It was developed as a compiled language (uses compiler as its translator). So that c
language programs could be easily ported to other computers equipped with a c
compiler.
2. It supports pointers with pointer operations. This feature allows the programmers to
directly access the memory addresses where variables are stored, and to perform bit
level manipulation of data stored in memory or processor registers.
3. It supports user defined data types for greater flexibility in programming.
4. It supports modular and structured programming concepts. Modularity means breaking
up of complex programs into a series of functions or modules.
5. It is a small and concise language providing only the bare essential features, so that a c
language program can be translated by a language translator into an efficient machine
language code.
6. A large number of compound operators, such as +=, -=, *=, ++, etc. are used to provide
easier and efficient programming.
7. C language provides more accuracy in calculations.
8. C programs are fast and are efficient in memory utilization.
C is a free form language. That is the c compiler does not care, where on the line we begin
typing. C program statements are written in lower case letters. Upper case letters are used
only for symbolic constants. Braces ({ }), group program statements together and mark the
beginning and the end of functions. A proper indentation of braces and statements would
make a program easier to read and debug.
Since c is a free form language we can group statements together on one line.
The program
main()
{
printf(“hello”);
}
However, this style makes the program more difficult to understand and should not be used.
Properly inserted comments help to understand the program logic.
Delimiters
The language pattern of c uses special kind of symbols, which are called delimiters. A delimiter
is a unique character or series of characters that indicates the beginning or end of a specific
statement, string or function body set.
C Tokens
In a c program/ statement the smallest individual units are known as c tokens. C has six types
of tokens and they are identifiers, keywords, constants, strings, special symbols and operators.
C programs are written using these tokens and the syntax of the language.
C Tokens
main
[]
amount {}
Identifiers
They are names given to various program elements such as variables, functions, structure,
union, constant, arrays etc. These are user defined names and consist of a sequence of letters
and digits, with a letter as a first character.
1. An identifier can be composed only of upper and lower case letters, the underscore and
digits.
2. There can be no embedded blanks.
3. An identifier cannot start with a digit or the first character must be a letter.
4. Upper and lower case letters are different.
5. Key words cannot be used as an identifier.
6. The length of an identifier varies from one compiler to another. Some versions permits only a
maximum of 8 characters while some other version permits a maximum of 31 characters (ANSI).
Constants
The value/data that cannot be changed during the execution of the program is called constant.
Constants are classified into the following groups as given in the figure
Numeric Constants
1. Integer constant
Any numeric value without fractional part is called integer constant. An integer constant must
have at least one digit. It may contain either + or – sign to indicate the positive or negative
nature of the number. Integer constant could be either positive or negative or may be zero.
The decimal point, fractional part, or symbols are not permitted. Neither blank spaces nor
commas are permitted.
There are 3 types of integer constants namely decimal, octal and hexadecimal.
i. Decimal integer constant (Base 10) – A sequence of digits with no zeros in the
beginning. It consists of any combination of digits taken from the set 0 to 9
Example:- 124, 78, -20
ii. Octal integer constant (Base 8)
It consists of any combination of digits from the set 0 to 7 with a leading zero.
Example:- 0123, 072
iii. Hexadecimal integer constant (Base 16)
A hexadecimal integer constant must begin with 0X or 0x. It can be followed by any
combination of characters taken from the set of 0 – 9 and A – F. the letters A
through F represent the numbers 10 through 15.
Example:- 0X79, 0xAF
2. Real constant or Floating point constant
Numbers with decimal part is called floating point constants or real constants.
A real number may also be expressed in exponential notation. For example the value 312.78
may be written as 3.1278e2 in exponential notation. e2 means multiply by 102 .
3. Character constant
A character constant is a single character enclosed in single quotes.
Example:- ‘A’ , ’2’, ‘+’
Character constants have integer values that are determined by the computers particular
character set that is the ASCII character set (American Standard Code for Information
Interchange).
Example: Constant ASCII value
‘A’ 65
‘3’ 51
‘a’ 97
C supports certain non-graphical character, which are those that cannot be typed directly from
the keyboard, and they can be represented by using escape sequences (Backslash character
constants) which consists of a backslash ( \ ) followed by one or more characters.
4. String Constant
A string constant is a group of characters enclosed within double quotation mark. The compiler
automatically inserts a null character (\0) at the end of the string constant, which is called the
string terminator.
E.g.:- “MG University”, “2017”, “A”
A character constant (eg:- ‘A’) is not equivalent to a single string constant (eg:- “A”). A single
character string constant does not have an equivalent integer value while a character constant
has an integer value.
Data Types in C
Data types are the means to identify the type of data and associated operations of handling it.
ANSI C supports 3 classes of data types:
1. Primary / Fundamental / Basic Data types
2. Derived data types
3. User defined data types
Integer Types
int, short and long
Integers are whole numbers with a range of values supported by a particular machine. The size
of an integer depends on the computer. If we use a 16 bit word length, the size of the integer
value is limited to the range -32768 to +32767 (that is, -215 to +215 - 1). A signed integer uses
one bit for sign and 15 bit for the magnitude of the number. Similarly a 32 bit word length can
store an integer ranging from -2,147,483,648 to 2,147,483,647.
In order to provide some control over range of numbers and storage space c has 3 classes of
integer storage, namely short int, int and long int, in both signed and unsigned forms. The
short int represents small integer values and requires half the amount of storage as a regular
int number uses. We declare long and unsigned integers to increase the range of values. The
use of qualifier signed on integers is optional because the default declaration assumes a signed
number.
Integer Representation
The signed integer has signs positive or negative. The sign are represented in the computer in the
binary format as 1 for – (minus) and 0 for + (plus) or vice versa. The sign bit is always coded as
leftmost bit.
For example, positive signed numbers are represented in the form called signed magnitude form. In
this form the sign is represented by a binary 0 and the remaining magnitude by equivalent binary
form.
+7 is represented as 0 0000111
The signed negative numbers can be represented in any one of the following form
a. Signed – magnitude form
b. Signed – 1’s complement form
c. Signed – 2’s complement form
In the signed magnitude form the sign of the number is represented as 1 and the magnitude by
equivalent binary form
Example: -7 is represented as 1 000111
In the signed 1’s complement form, the sign of the integer is indicated by 1 and the magnitude in
1’s complement form
Example: -7 is represented as 1 1111000
In the signed 2’s complement form the sign is indicated by 1 and the magnitude by 2’s complement
form
Example: -7 is represented as 1 1111001
Floating point (real) numbers are stored in 32 bits (4 bytes) on all 16 bit and 32 bit machines,
with 6 digits of precision. Floating point numbers are defined in c by the keyword float. When
the accuracy provided by a float number is not sufficient, the type double can be used to
define the number. A double data type number uses 64 bits (8 bytes) giving a precision of 14
digits. To extend the precision further we may use long double which uses 80 bits (10 bytes).
Character Types
A single character can be defined as a character (char) type data. Characters are usually stored
in 8 bits (1 byte). The qualifier signed or unsigned may be explicitly applied to char. While
unsigned char have value between 0 and 255, signed char have values from -128 to 127. The
format specifier for char data type is %c. But when printed using %d specifier prints ASCII
character.
Type Modifiers
The keywords signed, unsigned, short and long are type modifiers. A type modifier changes the
meaning of basic data type and produces a new data type.
Void Types
The void type has no values. This is usually used to specify the type of functions. The type of a
function is said to be void when it does not return any value to the calling function.
VARIABLES
Variables are the names given to storage locations. A variable may take different values at
different times during execution. A variable can be defined in any data type. The size and
nature of data stored in a variable depends of the data type it is declared.
Declaring Variables
The declaration of variables should be done in declaration part of the program. The variable must
be declared before they are used in program. Declaration ensures the following two things:
1) compiler obtains the variable name and 2) it tells the compiler data type of the variable being
declared and helps in allocating the memory.
The variables are associated with two values – l-value which is the address (location value) of the
memory location and r-value which is the content of the location.
2 5
Here lvalue (address) is 1001 and content (r-value) is 25
a
Initializing Variables
Variables declared can be assigned or initialized using assignment operator ‘=’. The declaration
and initialization can also be done in the same line.
Syntax:
Variable_Name = Constant;
Or
Data_Type Variable_Name = constant;
Example:
x=5; where x is an integer variable
int y = 4;
Dynamic Initialization
The initialization of variable at run time is called dynamic initialization. Dynamic refers to the
process during execution.
Example:
void main()
{
int r=2;
float area=3.14*r*r;
clrscr();
printf(“Area=%g”,area);
}
Output
Area=12.56
In the above example area is calculated and assigned to variable area. The expression is solved
at run time and assigned to area at runtime. Hence it is called dynamic initialization.
TYPE CONVERSION
1. Implicit Type conversion (type promotion)
C permits mixing of constants and variables of different types in an expression. In C
automatically ‘lower’ data type is promoted to ‘upper’ data type. This automatic conversion
is known as implicit conversion. For example, data type char or short is converted to int.
In case an expression contains one of the operands as unsigned operands and another non-
unsigned, the later operand is converted to unsigned.
Similarly, in case an expression contains one of the operands as float operands another
non-float, the later operand is converted to float.
Similarly, in case an expression contains one of the operands as double operands another
non-double, the later operand is converted to double.
Example :
short a=5;
long int b=123456;
float c=234.56;
double d=234567.78695;
clrscr();
printf(“%lf”,((a+b)*c)/d);
in the above example the expression ((a+b)*c)/d) gives the result as double float.
here c will be 2, which is not accurate. This is because a/b is an integer expression and
returns 2 only. This problem can be overridden by the following statement.
c = (float)a/b;
the type of a is changed into float explicitly by the user and hence b will automatically
change into the higher type i.e. from int to float. This modification makes the value of c to
2.5, which is accurate.
WRAPPING AROUND
When the value of variable goes beyond its limit, the compiler would not flag any error
message. It just wraps around the value of the variable.
Example:
unsigned u=65537;
printf(“u=%u”,u);
The range of unsigned integer is 0 to 65535. In the above example unsigned integer u=65537.
After reaching the last range 65535, the compiler starts from beginning. The value 65536 refers
to 0 and 65537 refers to 1.
Constant Variable
Volatile Variable
The volatile variables are those variables that can be changed at any time by other external
program or the same program. The syntax is
volatile int d;
Overflow of Data
Problem of data overflow occurs when the value of a variable is either too big or too small for
the data type to hold. Floating point values are rounded off to the number of significant digits
allowed, an overflow normally results in the largest possible real value, whereas an under flow
results in zero.
OPERATORS
Operators are pre-defined symbols that can carry out operations. The participants of an
operation are called operands. Operators are classified into unary operators (contains one
operand), binary operators (contains two operands) and ternary operators (contains three
operands).
Arithmetic operators
The basic arithmetic operator in ‘c’ are
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder of division)
Division of one integer quantity by another is referred to an integer division. This operation
always results in a truncated quotient.
That is if A=10 and B=3 then A/B will be 3 (decimal part truncated).
A real operand may assign values either in decimal or exponential notation. If x and y are float
data types and x=5.0 and y=2.0 then x/y will be 2.5
Suppose C1 and C2 are character type variable and C1=’A’ and C2= ‘B’ then C1+C2 will be 65 +
66 that is 131 because the corresponding ASCII values of A and B are added.
Unary operators
Unary operators operate on a single operand.
Unary +
Unary –
The ++ and - - may be used either as prefix operators (before the variable ie. ++n) or postfix
(after the variable ie. n++). In both cases the effect is to increment n. but the expression ++n
increments n before its value is used, while n++ increments n after its value has been used.
Relational operators
Relational operators are used for comparing the values of variables. These are binary
operators. The result of relational operations is either True or False. True is represented as 1
and false is represented as 0. There are 6 relational operators in c and they are
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
Example:-
M n m<n m>n m <= n m >= n m != n m == n
7 2 0 1 0 1 1 0
4 4 0 0 1 1 0 1
3 5 1 0 1 0 1 0
Logical operators
Logical operators are used with expressions. The result of logical expression will be either 0 or
1. The logical operators used in c are && (and), || (or), ! (not).
When two or more conditions are connected with the logical && operation, the result is true
only if all the conditions are true, otherwise the result is false.
(Example: 5>3 && 5<10)
When two or more conditions are connected with logical || operator, the result is true, when
either of the condition is true or both are true otherwise the result is false.
(Example: 8>5 || 8<2)
Example:-
A B A&&B A||B
F F F F
F T F T
T F F T
T T T T *Where A and B are conditional expressions.
The not (!) operator has the effect of reversing the truth value of the expression to its
immediate right.
(Example: 8!=8)
Example:-
A !A
F T
T F
Assignment operator
This is a binary operator that assigns the right side value to a left side variable. The symbol = is
used as the assignment operator. The general form of assignment statement is
Variable = expression;
Example: a -= 5 means a = a – 5;
n /= 10 means n = n / 10;
Syntax
i. sizeof (data type)
ii. sizeof (variable name)
Example:-
float s;
sizeof(s); gives the value 4
sizeof(int) gives the value 2
Conditional operator ( ? : )
The conditional operator returns a value depending on a condition. It is a ternary operator,
which requires 3 operands to operate upon.
Syntax:
exp1 ? exp2 : exp3;
where exp1, exp2 and exp3 are expressions
exp1 is evaluated first. If it is true, then the expression exp2 is evaluated and becomes the
value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of
the expression.
Example:- result = mark > 50 ? ‘P’ : ‘F’;
if value of mark is greater than 50 then the value ‘P’ is assigned to result else the value ‘F’ is
assigned to result.
Bitwise Operators
Bitwise operators are used to perform operations at binary digit level. Following are the bitwise
operators used in c language
<<
>>
~
&
|
^
5. | bitwise logical or
6. ^ bitwise exclusive or
Special operators
C supports some special operators such as pointer operators and member selection operators.
Pointer operators
& returns the address of a variable
* indirection operator is a pointer to a variable
Member selection operators
. and -> are used to select members of a structure
Operator precedence
The order or priority in which the operations are performed in an expression is called the precedence of
operations. Some of the operators of the same level of precedence are evaluated from left to right or
right to left. This is referred to associativity. The following table shows the list of operators in
descending order of precedence.
Arithmetic Expressions
An arithmetic expression is a combination of variables, constants and operators arranged as
per the syntax of the language.
Example:- a * b – c
3.14* r * r
Evaluation of expressions
Expressions are evaluated using an assignment statement of the form
variable = expression;
When the statement is encountered, the expression is evaluated first and the result then
replaces the previous value of the variable on the left hand side
Example:- x=a*b+c
Structure of a C program
Documentation Section
Link Section
Definition Section
Global Declaration Section
main()
{
Declaration Part;
Executable Part;
Documentation section
The documentation section consists of a set of comment lines giving the name of the program,
the author and other details, which the programmer would like to use later.
Link section
The link section provides instructions to the compiler to link functions from the system library.
Example- #include<stdio.h>
Definition section
There are some variables that are used in more than one function. Such variables are called
global variables and are declared in the global declaration section that is outside of all the
functions. This section also declares all the user defined functions.
main() function
This is a function from which the operating system will start executing the program. Every c
program must have one and only one main function.
Now the function definition starts with an opening brace { and ends with a closing brace }. This
section contains 2 parts, declaration part and executable part.
Declaration Part
The declaration part declares all the variables used in the executable part. All variables that are
used in c program must be declared. Variable declaration includes the type and variable name.
The initialization of variables are also possible with the declaration.
Example:- int a;
float x,y;
int num=10;
Executable Part
The function definition constitutes the statements representing the instructions to be carried
out by the computer. There is at least one statement in the executable part.
All statements in the declaration and executable parts end with a semicolon (;).
The sub program section contains all the user defined functions that are called in the main
function.
All sections except the main function section may be absent when they are not required.
Comments
Comments can be written anywhere in the program but the line should start with /* and end
with */. Anything written in between these symbols is identified as comments and the
compiler ignores them.
UNIT 3
Formatted Functions
With formatted functions, the input or output is formatted as per our requirement. The
readability in easy way is possible in formatted functions. The formatted input/output
functions read and write, respectively, all types of data values. They require format strings to
produce formatted results. The formatted functions return values after execution. The return
value is equal to the number of variables successfully read/written. Using this value, the user
can find out the error that occurred during reading or writing of data.
Streams performs all input and output operations. The streams are nothing but a sequence of
bytes. In input operations, the bytes (data) flow from input device such as keyboard, a disc
drive or network connection to main memory. Similarly, in output operations bytes flow from
main memory to output devices such as monitor, printer, disc drive, network connection.
Unformatted Functions
The unformatted input/output functions work only with character data type. They do not
require format conversion symbol because they work only with character data type. in case,
values of other data types are passed to these functions, they are treated as character data.
FORMATTED FUNCTIONS
1) printf() Statement
The library function printf() is used to print out a message, either on screen or paper. This
function can be used to output any combination of numeric value, single character and strings.
Syntax
printf(“control string”, arg1,arg2,arg3,……………… argn);
The arg1, arg2, ……. Are arguments that represent the individual data items. The arguments
can be written as constants, single variable, array names or expressions. Function references
may also be included.
The control string consists individual or group of characters with one character group for each input
data item. Each character group must begin with a % sign followed by a conversion character which
indicates the type of the corresponding data item. Commonly used format codes are given below.
Character Input Data
%d Decimal integer
%i Integer
%o Octal integer
%ld Long signed integer
%lu Long unsigned integer
%u Unsigned decimal integer
%x Hexadecimal
%c Character
%s Character string
%e,%f,%g Floating point numbers
%lf Double floating point
%% Literal %
Example 1:-
int x=2;
float y=2.2;
char z=’c’;
printf(“%d %f %c”, x,y,z);
Output
2 2.2000 c
Example 2:-
int y=65;
printf(“%c %d”, y,y);
Output
A 65
In the above example %c converts numeric value 65 to its corresponding character A. %d prints
value 65 because y is integer.
Flags are used for output justification, numeric signs, decimal points, trailing zeros. The flag (-)
left justifies the result. If it is not given, the default is right justification. The plus (+) signed
conversion results always starts with a plus (+) or minus (-) sign.
Width specifier sets the minimum field width for an output value. Width can be specified
through a decimal point or using an asterisk (*).
Example 3:-
printf(“\n%.2s”,”abcdef”);
printf(“\n%.3s”,”abcdef”);
printf(“\n%.4s”,”abcdef”);
Output
ab
abc
abcd
Explanation: in the above example width specifiers 2, 3 and 4 are used with format specifier
character %s with each printf() statement. The actual string length is 6 characters, the number
of printed characters is 2, 3 and 4 respectively.
Example 4:-
int x=55, y=33;
printf(“\n %3d”,x-y);
printf(“\n %6d”,x-y);
Output
22
22
Explanation: The results are displayed on different positions on the screen.
Example 5:-
int x=55, y=33;
printf(“\n %*d”,15,x-y);
printf(“\n %*d”,5,x-y);
Output
22
22
Explanation: here * is used with format string. The values 15 and 5 indicate the position from
where printing on screen begins.
Precision specifiers: The precision specifier always starts with a period or a dot in order to
separate it from any preceding width specifiers
Example 6:-
float g=123.456789;
printf(“\n %.1f”,g);
printf(“\n %.2f”,g);
printf(“\n %.3f”,g);
printf(“\n %.4f”,g);
Output
123.5
123.46
123.457
123.4568
Example 7:
Output
2) scanf() Statement
The input data can be entered into the computer from a standard input device by using the library
function scanf(). This function can be used to enter any combination of numerical values, single
characters and strings.
Syntax
scanf(“control string”, arg1, arg2, ……………. argn);
The control string specifies the field format in which data is to be entered and the arguments arg1,
arg2, arg3, ………. specifies the address or locations where the data is stored. Control string and
arguments are separated by commas.
The control string %d specifies that an integer value is to be read from the terminal. The value is
assigned to the variable num.
The scanf() statement requires ‘&’ operator called address operator. The ‘&’ operator indicate the
memory location of the variable, so that the value read would be placed at that location.
Some compilers permit the use of prompt message as a part of the control string in scanf.
Example 3:
void main()
{
int a,b;
float x;
char name[20];
printf(“enter 2 integers:- \n”);
scanf(“%4d %4d”, &a,&b);
printf(“\n entered integers are”);
printf(“\n %4d %4d”,a,b);
printf(“\n”);
printf(“\n enter a real number: \n”);
scanf(“%f”, &x);
printf(“\n entered float number is:”);
printf(“\n%f”, x);
printf(“\n”);
printf(“\n enter a string: \n”);
scanf(“%7s”, name);
printf(“\n entered string is:”);
printf(“\n %7s”, name);
}
Output
enter two integers:
1 2
Entered integers are
1 2
Enter a real number:
12.3
entered float number is:
12.300000
enter a string:
mahatmagandhi
entered string is:
mahatma
UNFORMATTED FUNCTIONS
C has 3 types of I/O functions
i) Character I/O
ii) String I/O
iii) File I/O
2. putchar
This function prints one character on the screen at a time, read by the standard input.
Syntax:
putchar(variable name);
Example:
char c=’S’;
putchar(c);
3. getch()
It is used to read a single character the instant it is typed without waiting for the enter key to
be hit. The character entered is not displayed by the getch() function.
Syntax:
getch();
4. getche()
This function read any alpha numeric character from the standard input device.
Syntax:
getche();
5. putch()
This function prints any alphanumeric character taken by the standard input device.
Syntax:
putch(variable name);
2. puts()
This function prints the string or character array. It is opposite to gets().
Syntax:
puts(str);
3. cgets()
This function reads string from the console. It requires character pointer as an argument.
Syntax:
cgets(char *st);
4. cputs()
This function displays string on the console.
Syntax:
cputs(char *st);
2. exit()
This function terminates the program. It is defined in process.h header file.
Syntax:
exit();
3. sleep()
This function pauses the execution of the program for a given number of seconds. It is defined
in dos.h header file.
Syntax:
sleep(5);
4. system()
This function is used to execute different DOS commands. It returns 0 on success and -1 on
failure.
Syntax:
system(“dir”);
The above command will display the directory.
Control Statements
The control flow statements specify the order in which computations are performed.
1. if statement
2. if – else statement
3. if – else – if ladder statement
4. switch case statement
5. conditional operator statement
6. goto unconditional jump
7. loop statement
Besides, the C also supports other control statements such as continue, break.
The if statement
The if statement is a powerful decision making statement and is used to control the flow of
execution of statements. It is basically a two way decision statement and is used in conjunction
with an expression. The if statement can be implemented in the following forms
1. Simple if statement
2. if …… else statement
3. Nested if….. else statement
4. if ….. else if ladder
Simple if statement
The general form of a simple if statement is
if (test expression)
{
Statement-block;
}
Statement- x;
The statement-block may be a single statement or a group of statements. If the test expression
is true, the statement-block will be executed; otherwise the statement-block will be skipped
and the execution will jump to the statement-x. Remember, when the condition is true both
the statement-block and the statement-x are executed in sequence.
Entry
Test True
expression
?
Statement-block
False
Statement-x
if (test expression)
{
True-block statement(s);
}
else
{
False-block statement(s);
}
statement-x;
if the test expression is true then the true-block statements are executed, otherwise the false-block
statements are executed. In both the cases the control is transferred subsequently to statement-x.
Entry
True-block False-block
statements statements
Statement-x
Example:- ………………….
………………….
if (a > b)
{
printf ( “ a is big”);
}
else
{
printf (“b is big”);
}
…………………..
……………………
if ( test condition-1)
{
if ( test condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
if ( test condition-3)
{
statement-3;
}
else
{
statement-4;
}
}
statement-x
If condition-1 is true, then condition-2 is evaluated and if it is true then statement 1 will be
executed; otherwise statement 2 is executed. If condition-1 is false then condition-3 is
evaluated and if it is true, the statement-3will be executed; otherwise the statement-4 will be
executed.
Entry
Statement-x
57 BPS College Piramadom
Methodology of Programming and C Language
A multipart if is a chain of if’s in which the statement associated with each else is an if. This
construct is known as the if else if ladder. The conditions are evaluated from top to bottom. As
soon as a true condition is found the statement associated with it is executed and the
remaining statements are skipped. When all the n conditions becomes false then the final else
containing the default statement will be executed.
Entry
True False
condition
Statement-3 False
True
condition
Statement-n Default
statement
Statement-x
Mark Class
>=80 distinction
>=60 &<80 first class
>=50 &<60 second class
>=40 &<50 third class
<40 failed
Program
void main ( )
{
int mark;
printf(“enter the mark”);
scanf(“%d”, & mark);
if (mark >= 80)
printf (“distinction”);
else if (mark >= 60)
printf (“first class”);
else if (mark >= 50)
printf (“second class”);
else if (mark >= 40)
1. Switch statement
Switch statement is a multi-way branch statement. Switch statement is used to execute a block
of statements depending on the value of a variable or an expression. It has the following form.
The expression is an integer expression or characters. Value-1, value-2, ……..are constants or constant
expressions and are known as case labels. block-1, block-2, ……….. are statement lists and may contain
zero or more statements. The switch statement tests the value of a given variable or expression against
a list of case values and when a match is found, a block of statements associated with that case is
executed. The break statement at the end of each block signals the end of a particular case. The default
is an optional case. When present, it will be executed if the value of the expression does not match with
any of the case values.
Switch
(variable)
case
Statement 1 Break
constant 0
End of switch
60 BPS College Piramadom
Methodology of Programming and C Language
Example: Program to enter a number between 1 and 7 and print the day of the week.
void main ()
{
int no;
printf (“Enter a number between 1 and 10”);
scanf (“%d”, &no);
switch (no)
{
case 1 : printf (“Sunday”);
break;
case 2 : printf (“Monday”);
break;
case 3 : printf (“Tuesday”);
break;
case 4 : printf (“Wednesday”);
break;
case 5 : printf (“Thursday”);
break;
case 6 : printf (“Friday”);
break;
case 7 : printf (“Saturday”);
break;
default :printf (“Wrong Entry”);
}
getch();
}
switch(y)
{
case 0: printf(“number is even”);
break;
default: printf(“number is odd”);
}
}
}
No two case statements have identical Same condition may be repeated for the
constants in the same switch. number of times.
In switch case statement nested if can be used In nested if statement switch case can be used
The goto statement is an unconditional branching statement. It is used to transfer the control
from one part of the program to another. It has the following form.
goto label;
The label: can be anywhere in the program either before or after the goto label; statement.
Example:
void main()
{
int x;
printf(“enter a number”);
scanf(“%d”,&x);
if(x%2==0)
goto even;
else
goto odd;
even: printf(“even number”);
return;
odd: printf(“odd number”);
}
Looping (Iteration) statements
A loop is defined as a block of statements, which are repeatedly executed for a certain number
of times. The loops are of two types.
i) Counter-controlled repetition: this is also called definite repetition action, because the
number of iterations to be performed is defined in advance in the program itself.
The steps in counter-controlled repetitions include Loop Variable, Initialization and
Incrimination/decrimination.
ii) Sentinel-controlled repetition: this is also called indefinite repetition. One cannot
estimate how many iterations are to be performed. In this type, loop termination
happens on the basis of certain conditions using the decision-making statement.
Depending on the position of the control statement in the loop, a control structure may be
classified either as the Entry controlled loop or as the Exit controlled loop. In the entry
controlled loop, the conditions are tested before the start of the loop execution. If the
conditions are not satisfied, then the body of the loop will not be executed. In the case of an
exit controlled loop, the test is performed at the end of the body of the loop and therefore the
body is executed unconditionally for the first time.
Initialization
No
Test Out of the loop
Condition?
Yes
Statements
Update expression
2. Like the initialization section the update section may also have more than one part
Example 2:- for(n=0, m=10 ; n!=m ; n++ , m--)
3. The test condition may have any compound relation and testing need not be limited only
to the loop control variable
Example 3 :-
sum = 0;
for( i=1; i<= 20 && sum < 100 ; i++)
Example 4 :-
void main()
{
int i,c=0;
for(i=0;i<10; )
{
i++;
printf(“%5d”,i);
}
}
Output
1 2 3 4 5 6 7 8 9 10
Example 5 :-
void main()
{
int i=0;
for( ;i<10; )
{
printf(“%5d”,i);
i=i+2;
}
}
Output
0 2 4 6 8 10
Example 6 :-
void main()
{
char i=97;
for( ; ; )
{
printf(“%5c”,i++);
if(i==107)
goto stop;
}
stop:;
}
Output
a b c d e f g h I j
Nested Loops
A loop may contain another loop in its body. This form of loop is called nested loop. In a nested
loop the inner loop must terminate before the outer loop.
The while loop is an entry controlled loop. In a while loop the loop control variable should be
initialized before the loop begins. The loop control variable should be updated inside the body
of the while. The syntax of the while statement is:-
Here the condition is evaluated first and if it is true then the body of the loop is executed. After
execution of the body the test condition is once again evaluated, and if it is true the body is
executed again. This process continues until the test condition becomes false and the control
is transferred out of the loop.
Entry
Initialize
False
Test
Out of the loop
condition
True
Update
int i= 1;
while (i<=10)
{
printf(“%d \n”,i);
i = i +1;
};
do
{
loop body;
}
while (test condition);
On reaching the do statement the program proceeds to the body of the loop. At the end of the
loop the test condition is evaluated. If it is true the loop body is executed once again. This
process continues as long as the condition is true. When the condition becomes false the loop
will be terminated.
Entry
Body of loop
True
Test
condition
False
Example:
do
{
printf(“enter a number \n”);
scanf(“%d”, &n);
}
while (n > 0);
This segment of program reads a number from the keyboard until a zero or negative number is
entered.
Comparison of the while and do while loop
2. Body statement(s) are executed when Body statement(s) executes even when the
condition is satisfied. condition is false.
3. No brackets for single statement. Brackets are essential even when a single
statement exits.
Break statement
An early exit from a loop can be done by using the break statement. When a break statement is
encountered inside a loop, the loop is immediately exited and the program continues with the
statement immediately following the loop. When the loops are nested, the break would only
exit from the loop containing it, i.e. the break will exit only a single loop.
Example: Program to find the sum of any 10 numbers. If the input number is 0 then the
program will exit.
void main()
{
int no, i, sum=0;
for (i=1 ; i<=10 ; i++)
{
printf(“Enter a number”);
scanf(“%d”, &no);
if (no == 0)
{
break;
}
sum = sum + no;
}
printf(“Sum is %d”, sum);
getch();
}
Continue statement
The continue statement is similar to break statement as both statements skip over a part of the
code. But the continue statement is different from break. Instead of forcing termination, it
forces the next iteration of the loop to take place, after skipping any statements in between.
2. Control passes to the next statement. Control passes at the beginning of the loop.
UNIT 4
Data Structure:
Arrays
An array is a grouping of same type of data items referenced under a common name.
Or it is a collection of consecutive locations referenced by a single variable.
An array is a linear and homogeneous data structure. It is also called a composite data
structure. An array permits homogeneous data. It means that similar types of elements are
stored contiguously in the memory and that too under one variable name. An array can be
declared any standard or custom type.
Use of arrays has definite advantages over using simple variables. For example suppose we
want to prepare the rank list of 100 candidates. It would be inconvenient to use 100 different
variables. This will make the program complex. Furthermore, it would be difficult to process
the data. But if we make use of arrays to solve this problem it will become easy to read, and
process the data.
Advantages
1. It is easy to represent and manipulate array variables.
2. Array uses a compact memory structure.
3. Readability of program will be increased.
Types of Arrays
Arrays are classified into three
I. One Dimensional array (Single Dimensional Array)
II. Two dimensional Array
III. Multi-Dimensional Array
One Dimensional Array
It can store linear set of values. Each element is referenced by only one index (subscript) that
indicates its position. The general form of array declaration is
type arrayname [ size ];
Where type refers to the data type of array such as int, float, double, char and the size
indicates the maximum number of elements that can be stored in the array.
Example: int mark [5 ];
Here mark is the integer array that can hold 5 integer values. The compiler reserves 5 storage
locations as shown below
mark [ 0 ]
mark [ 1 ]
mark [ 2 ]
mark [ 3 ]
mark [ 4 ]
We can initialize the element of arrays when they are declared. The general form is
In the above example all elements are initialized. It is also possible to initialize individual
element by specifying the subscript number in the square bracket following the array name.
number[0]=1;
number[1]=2;
number[2]=3;
Array Terminology
Size : number of elements to store elements in an array is called its size. It is always mentioned
in brackets( [ ] )
Type: type refers to data type. It decides which type of element is stored in the array. It also
instructs the compiler to reserve memory according to data type.
Base: the address of the first element is the base address. The array name itself stores address
of the first element.
Index : the index value is always an integer value. It begins from 0 to onwards depending the
size of the array. For example, n[x], n is array name and x is index.
Range: the index value varies from lower bound to upper bound while writing or reading
elements from an array. For example, in num[100], the range of index is 0 to 99.
Word : it indicates the space required for an element.
CHARACTERISTICS OF AN ARRAY
1. The declaration int a[5] is nothing but creation of five variables of integer types in
memory. Instead of declaring five variables for five values, the programmer can define
them in an array.
2. All the elements of the array share the same name and they are distinguished from one
another with the help of the element number.
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing the
other elements.
Example: int a[5] = {1,4,6,8,9};
If a programmer needs to replace 9 with 10 then the statement a[4]=10; can be used.
Here other four elements are not disturbed.
5. Any element of an array a[ ] can be assigned/equated to another ordinary variable of its
type.
Example : b=a[2];
a[2] = a[3];
6. Array elements are stored in contiguous memory locations.
7. Once the array is declared, its lowest boundary cannot be changed but upper boundary
can be expanded.
Example:
int num[5]={1,2,3,4,5};
num[5]=6;
printf(“num*5+=%d”,num*5+);
Output
num[5]=6
8. An array name itself is a pointer. It does not require ‘*’ operator. The brackets( [ ] )
automatically denote that the variable is a pointer.
9. The amount of memory required for an array depends upon the data type and the
number of elements. The total size in bytes for a single dimensional array is computed
as:
Total bytes = size of data type x size of array
10. The operation such as insertion, deletion of an element can be done with the list but
cannot be done with an array. An element can be deleted, replaced but memory
location remains as it is.
One Dimensional Array and Operations
Frequently performed operations with arrays are:-
i. Traversing
ii. Deletion
iii. Insertion
iv. Searching
v. Merging
vi. Sorting
Traversing
The operation of displaying or listing all elements of an array is called traversing.
Example:
void main()
{
int num[5],j;
Output
clrscr();
Enter 5 elements: 4 2 6 2 1
printf(“enter 5 elements:”);
Elements Address
for(j=0;j<5;j++)
4 65516
scanf(“%d”,&num*j+);
2 65518
printf(“\n Elements Address”);
6 65520
for(j=0;j<5;j++)
2 65522
printf(“\n %d %u”,num*j+,&num*j+);
1 65524
getch();
}
Deletion
This operation involves deleting specified elements from an array.
Example:
void main()
{
int num[20]={0},j,n,p,t;
clrscr();
printf(“enter number of elements:”);
scanf(“%d”,&n);
printf(“enter elements”);
for(j=0;j<n;j++)
scanf(“%d”,&num*j+);
printf(“\n elements are”);
for(j=0;j<n;j++)
Searching
An array element can be searched. The process of seeking specific elements in an array is called
searching.
Example:
void main()
{
int array[100], search, c, n;
printf("Enter the number of elements \n");
scanf("%d",&n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search)
{
printf("%d is present at location %d.\n", search, c+1); Output
enter the number of elements: 4
break;
enter 4 integers : 6 4 7 2
}
enter the number to search : 7
} 7 is present at location 3
if (c == n)
printf("%d is not present in array.\n", search);
getch();
}
Merging
The elements of two arrays are merged into a single one.
i. Elements of one array can be appended to end of the second array
ii. Elements of two arrays can be merged in alternate order.
Example
void main()
{
int j,h=0,k=0;
int x[4] ={1,2,3,4};
int y[4] ={5,6,7,8];
int z[8];
clrscr();
printf(“array 1:”);
for(j=0;j<4;j++)
printf(“%d”,x*j+);
printf(“array 2:”);
for(j=0;j<4;j++)
printf(“%d”,y*j+);
j=0;
while(j<8)
{
if(j%2==0)
z[j]=x[k++]
else
z[j]=y[h++];
j++ Output
} array 1: 1 2 3 4
printf(“\n array 3:”); array 2: 5 6 7 8
for(j=0; j<8; j++) array 3: 1 5 2 6 3 7 4 8
printf(“%d”,z*j+);
getch();
}
Sorting
Arranging elements in a specific order either in ascending or in descending order is known as
sorting.
Example
void main()
{
int num[5],j,k,s=0;
clrscr();
printf(“\n enter five elements:”);
for(j=0; j<5; j++)
{
scanf(“%d”,&num*j+);
s=s+num[j];
}
for (k=0; k<s; k++)
{
for(j=0; j<5; j++) Output
{ Enter five elements: 5 8 9 7 2
if (num[j]==k) 2 5 7 8 9
printf(“%d”,num*j+);
}
}
}
Columns
0 1 2
0
Rows
1
a[1][1]
int a[2][3]={0,0,0,1,1,1};
or
int a[2][3]= { {0,0,0} , {1,1,1}};
Multi-dimensional array
The general form of a multi-dimensional array is
datatype ArrayName[size1] [ size2 ] [size3+……………*size n] ;
The value of the string is its base address, i.e. address of the first character.
Example:
char name* + = ,‘I’,’N’,’D’,’I’,’A’,’\0’-;
Each character of the string occupies 1 byte of memory. The last character is always ‘\0’. It is
not compulsory to write ‘\0’ in string. The compiler automatically puts ‘\0’ at the end of the
character array or a string. The characters of a string are stored in contiguous locations. In the
above example the compiler automatically determines the size of the array.
The scanf() is not capable of reading multiword strings, i.e. it cannot read white spaces. In the
case of character arrays the amphersand(&) is not required before the variable.
1. strlen( )
This function returns the number of characters in a string.
Syntax:
n =strlen (string);
Where n is an integer variable which receives the value of the length of the string.
Example:- int n;
char str1* + = “mgu”;
n = strlen(str1); ------- here n will get 3
2. strcpy( )
This function copies the contents of one string into another.
3. strncpy()
This function copies specified length of characters from the source to destination string. The
strcpy() function copies whole source string to destination string.
Syntax:
strncpy (char *destination, char *source, int n);
Example:
char s1* +=”wonderful”;
char s2* +=”beautiful”;
strncpy(s2,s1,6);
printf(“%s”, s2); it will print wonderful
4. stricmp()
This function compares two strings without regard to case. If the strings are the same it returns
zero otherwise non zero value.
Syntax:
stricmp(char *s1,char *s2)
Example:
#include<string.h>
void main()
{
char sr[10],tar[10];
int diff;
printf(“enter string 1:”);
gets(sr);
printf(“enter string 2:”); Output
gets(tar); Enter string 1:
diff=stricmp(sr,tar); HELLO
if (diff==0) Enter string 2:
puts(“two strings are identical”); hello
else two strings are identical
puts(“two strings are different”);
getche();
}
5. strcmp ( )
This is a function which compares two strings to find out whether they are same or different.
This function discriminates lower case and upper case letters. The two strings are compared
character by character until there is a mismatch or end of one of the strings is reached,
whichever occurs first. If the two strings are identical, the function returns a value 0, otherwise
it returns the numeric difference between the ASCII values of the first non-matching pairs of
characters.
Syntax:
strcmp(string1, string2);
Example:
#include<string.h>
void main()
{
char sr[10],tar[10];
int n,diff;
printf(“enter string 1:”);
gets(sr);
printf(“enter string 2:”);
gets(tar);
printf(“enter length up to which comparison is to be made :”);
scanf(“%d”,&n);
Output
diff=strncmp(sr,tar,n); Enter string 1:
if (diff==0) HELLO
printf(“two strings are identical up to %d characters”,n); Enter string 2:
else HE MAN
puts(“two strings are different”); Enter length up to which comparison is to
getche(); be made: 2
} two strings are identical up to 2 characters
7. strlwr( )
It converts a string to lowercase.
Syntax:
strlwr(char *string);
8. strupr()
It converts a string to upper case.
Syntax:
strupr(char *string);
9. strdup()
This function is used for duplicating a given string at the allocated memory which is pointed by
the pointer variable.
Syntax:
text2=strdup(text1)
Where text1 is string and text2 is a pointer.
Example:
#include<string.h>
void main() Output
{ Enter text: Good Morning
char text1[20],*text2; Original string=Good Morning
printf(“enter text:”); Duplicate string=Good Morning
gets(text1);
text2=strdup(text1);
printf(“Original string=%s \n Duplicate string = %s”,text1,text2);
}
10.strchr()
This function returns the pointer position to the first occurrence of the character in the given
string. strchr() function returns null if character is not found otherwise it returns a pointer to
the first occurrence of the given character.
Syntax:
chp = strchr(string , ch);
Example:
#include<string.h>
void main()
{
char string[30],ch,*chp;
printf(“enter a string:”);
gets(string);
printf(“enter a character to find:”);
ch=getchar();
chp=strchr(string,ch);
Output
if(chp) enter a string: hello
printf(“character is found in string”); enter a character to find: l
else character is found in string
printf(“character is not found in string”);
}
11.strstr()
It finds first occurrence of a given string in another string. This function finds the second string
in the first string. it returns the pointer location from where the second string starts in the first
string. if not found it returns NULL.
Syntax:
strstr(char *string1, char *string2);
Example:
#include<string.h>
void main()
{
char line1[30],line2[30],*chp;
puts(“enter line1:”);
gets(line1);
puts(“enter line2:”);
gets(line2);
chp=strstr(line1,line2); Output
if(chp) enter line1: india is my country
printf(“string is present”); enter line2: india
else string is present
printf(string is not present”);
}
12.strcat( )
This function joins(concatenates) two strings together. That is this function appends the target
string to the source string.
Syntax:
strcat (string1, string2);
13.strncat
This function concatenates the string with another up to the specified length.
Syntax:
strncat(text1,text2,n) where n is the number character to append
Example:
#include<string.h>
void main()
{
char text1[30],text2[10],n;
puts(“enter text1:”);
gets(text1);
puts(“enter text2:”);
Output
gets(text2);
enter text1: MAY I
printf(“enter number of characters to add:”);
enter text2: COME IN
gets(n); enter number of characters to add: 4
strcat(text1,” “); MAY I COME
strncat(text1,text2,n);
printf(“%s”,text1);
}
14.strrev()
It reverses a given string.
Syntax:
strrev( char *s);
Example:
char text*+=”ABCD”;
strrev(text); it will return DCBA
15.strset()
This function replaces every character of a string to a given symbol/character.
Syntax:
strset(char * string, char symbol);
Example:
#include <string.h>
void main()
{
char string[10], symbol;
puts(“enter a string:”); Output
gets(string); enter a string: COLLEGE
puts(“enter a symbol for replacement:”); enter a symbol for replacement: Y
scanf(“%c”,&symbol); YYYYYYY
strset(string,symbol);
printf(“%s”,string);
}
16.strnset()
It is same as strset() function. Here, the specified length is provided.
Syntax:
strnset(char *string, char symbol, int n);
Where n is the number of characters to replace
Example:
char string*+=”ABCDE”;
char symbol=”#”;
strnset(string,symbol,2); it will return ##CDE
17.strspn()
This function returns the position of the string from where the source array is not matching the
target one.
Syntax:
strspn(char *string1, char *string2);
Example:
#include<string.h>
void main()
{
char text1[10],text2[10];
int length;
printf(“enter first string:”); Output
gets(text1); enter first string: GOOD MORNING
printf(“enter second string:”); enter second string: GOOD BYE
gets(text2); after 5 characters there is no match
length=strspn(text1,text2);
printf(“after %d characters there is no match”, length);
}
18.strpbrk()
This function searches the first occurrence of the character in a given string, and then it
displays the string starting from the character.
Syntax:
strpbrk(char *text1, char text2);
Example:
#include<string.h>
void main()
{
char *ptr;
char text1[10],text2[2];
printf(“enter string:”); Output
gets(text1); enter string: INDIA IS GREAT
printf(“enter character:”); enter character: G
gets(text2); string from given character: GREAT
ptr=strpbrk(text1,text2[0]);
printf(“string from given character:”);
puts(ptr);
}
String Conversion Functions
Function Name Description
double atof(const char *s ); Converts the given string to double
int atoi(const char *s ); Converts the given string to int
long atoi(const char *s); Converts the given string to long
double strtod(char *s, char **endptr); Separates char and float data from the given string
long strtol(char *s, char **endptr, int radix); Separates char and long int data from the given string.
POINTERS
A pointer is a variable that stores the address of another variable. The computer’s memory is a
sequential collection of storage cells. Each cell commonly known as a byte, has a number called
address associated with it. Pointer is a special data type in c.
Example:- int a = 3;
a location name
3 value at location
Since memory addresses are simply numbers, they can be assigned to some variables. Such
variables that hold memory addresses are called pointers.
Features of Pointers
1. Pointers are fundamental tool in developing code in c.
2. Pointers save memory space.
3. The pointer assigns the memory and also releases it. Pointers are used to allocate
memory dynamically.
4. Pointers are used with data structures. They are useful for representing two
dimensional and multi-dimensional arrays.
5. Access elements of an array of any data type irrespective of its subscript range.
6. Execution time with pointer is faster because data is manipulated with the address.
The & symbol which is known as address of operator is used to access the address of a variable.
Pointer variables are declared like normal variables except for the addition of unary character
* (asterisk). The syntax is
dataType *ptrvarname;
Example:-
int *iptr; --------- creates an integer pointer
float *fptr; --------- creates a float pointer
char *cptr; --------- creates a character pointer
Two unary operators * and & are used with pointers. The & returns the memory address of its
operand. The operator * returns the value of the variable located at the address following it. So
& is known as address of operator and * is known as value at operator.
Example:-
main( )
{
int i=3;
int *j;
j = &i;
printf (“\n Address of i = %u”, &i);
3 6524
6524 6522
Output
Address of i = 6524
Address of i = 6524
Address of j = 6524
Value of j = 6524
Value of i = 3
Value of i = 3
Value of i = 3
Program to find the sum of two given numbers using pointer variable.
void main( )
{
int a, b, *ptr1, *ptr2;
ptr1 = &a;
ptr2 = &b;
printf (“Enter 2 numbers”);
scanf(“%d%d”, ptr1, ptr2);
printf (“Sum = %d”, *ptr1 + *ptr2);
}
Pointers can also be declared as void types. A void pointer can point any type of variable with
proper type casting. When a pointer is declared as void two bytes are allocated to it.
Void variables cannot be declared because memory is not allocated to them and there is no
place to store address.
Example:
int p;
char c;
void *pt=&p;
void main()
{
*(int *)pt=12;
printf(“p=%d”,p);
pt=&c;
*(char *)pt=’S’;
printf(“c=%c”,c);
}
Output
p=12
c=S
In the above example p and c are variables of type int and char respectively. pt is pointer of
type of void. The pt is initialized with address of integer variable p. The statement *(int *)
pt=12 assigns the integer value 12 to pointer pt i.e. to variable p. the declaration *(int *) tells
the compiler the value assigned is of integer type. Thus the assignment of char type is carried
out.
WILD Pointers
When a pointer points to an unallocated memory location or data value whose memory is de-
allocated, such a pointer is called a wild pointer. The wild pointer generates garbage memory
location and dependent reference. The pointer becomes wild due to the following reasons.
i) Pointer declared but not initialized
ii) Pointer alternation
iii) Accessing the destroyed data
Example:
void main()
{
int k,*x;
for(k=0;k<=2;k++)
printf(“%u”,x*k+);
}
Output
7272 24330 30559
In this program pointer x is not initialized. The successive locations are displayed.
CONSTANT Pointers
The address of the constant pointer cannot be modified.
In the above example, it is not possible to modify the address of the pointer str. The following
operations will generate error message
Example:
void main()
{
int k=10;
int const *pm=&k;
k=40;
/* *pm=50; invalid operation*/
printf(“k=%d”,k);
}
Output
k=40
In the above example the value of k cannot be changed through the constant pointer pm.
Data Type Initial Address Address after Address after Required Bytes
operation ++ operation - -
int i=2 4046 4048 4044 2
char c=’x’ 4053 4054 4052 1
float f=2.2 4058 4062 4054 4
long l=2 4060 4064 4056 4
The name x is defined as a constant pointer pointing to the first element, x[0] and therefore
the value of x is 1000, the location where x[0] is stored. That is,
x = &x[0] = 1000
If we declare p as an integer pointer( int *p) , then we can make the pointer p to point to the
array x by the following assignment
p = x;
This is equivalent to
p = &x[0];
Now we can access every value of x using p++ to move from one element to another. The
relationship between p and x is shown as:
p = &x[0] (=1000)
p + 1= &x[1] (=1002)
p + 2= &x[2] (=1004)
p + 3= &x[3] (=1006)
p + 4= &x[4] (=1008)
Example: program to access elements of an array through different ways using a pointer.
void main()
{
int arr[5]={10,20,30,40,50},p=0;
clrscr();
for(p=0;p<5;p++)
{
printf(“value of arr*%d+=”,p);
printf(“%d |”,arr*p+);
printf(“%d |”,*(arr+p));
printf(“%d |”,*(p+arr));
printf(“%d |”,p*arr+);
printf(“address of arr*%d+=%u\n”,p,&arr*p+);
}
}
Output
value of arr[0]=10 | 10 | 10 | 10 | address of arr[0]=4056
value of arr[1]=20 | 20 | 20 | 20 | address of arr[1]=4058
value of arr[2]=30 | 30 | 30 | 30 | address of arr[2]=4060
value of arr[3]=40 | 40 | 40 | 40 | address of arr[3]=4062
value of arr[4]=50 | 50 | 50 | 50 | address of arr[4]=4064
Explanation
In the above program elements displayed using different syntax
arr[p], *(arr+p), *(p+arr), p[arr]. The results of all of them would be the same.
1. arr[p] – here ‘arr’ refers to the address and ‘p’ refers to the element number.
2. *(arr+p) – the arr+p is the addition of constant with base address of the array. The
*(arr+p) points to the pth element of the array.
3. *(p+arr) – this statement is same as *(arr+p)
4. p[arr] – this is same as arr[p]. here ‘p’ refers the element number and ‘arr’ refers to the
base address. By varying ‘p’ and ‘arr’ the various elements of the array are displayed.
Here the base address of the array is assigned to integer pointer ‘p’. the pointer ,p, is printed
and incremented in the for loop till it prints the entire array elements.
Array of Pointers
An array of pointers is a collection of addresses. That is, addresses of memory locations can be
stored in an array and the array is called array of pointers or pointer array.
Syntax:
dataType *ptrArrayName [size];
Here ptr can contain addresses of 10 locations containing integer data. The expression ptr[0]
returns the first address and *ptr[0] returns the content of that address.
UNIT 5
Functions
Functions in can be defined as a named group of statements that can act on data and return a
value.
main( ) is an example of user defined function. printf( ), scanf( ), sqrt( ), strlen( )………….. are
examples of library functions. Library functions are pre defined set of functions. One can only
use the function but cannot change or modify them. The user need not worry about its source
code, but the results should be provided by the function.
i) Once a function is defined and called, it takes some data from the calling function
and returns a value to the called function.
ii) Whenever a function is called, control passes to the called function and working of
calling function is paused. When the execution of a called function is completed,
control returns back to the calling function and executes the next statement.
iii) The values of the actual arguments passed by the calling function are received by
the formal arguments of the called function.
iv) The function operates on formal arguments and sends back the result to calling
function. The return( ) statement performs this task.
Example:
int abc(int, int, int); Function declaration
void main()
{
int x,y,z;
-----------
abc(x,y,z); Function call
Function Declaration
A function has to be declared in a program before using it. The declaration informs the
compiler the name of the function, return type and the number and type of arguments passed
to the function.
Syntax:- returnType functionName (arg1, arg2, …………….);
Function Definition
The definition of a function consists of the function header and its body. The function header
specifies the type of data returned by the function, name of the function and list of
parameters. The body of a function is a set of statements enclosed in braces.
Syntax :
returnType functionName (argument list)
{
local variable declaration;
statement 1;
statement 2;
.
.
statement n;
return (expression);
}
94 BPS College Piramadom
Methodology of Programming and C Language
It is a comma separated list of variables used to supply data to the function from the caller. A
function can be without any parameters.
The arguments appearing in the function call statement is known as actual arguments. The
arguments in the function definition is called formal arguments. The actual and formal
arguments must match in number, type and order.
Return Statement
The return statement is used to return the control as a value to the called function. This is also
an optional statement. Its absence indicates that no value is being returned to the called
function. exit from the called function to the calling function is done by the use of the return
statement. when the return statement is executed without argument, it always return 1.
The return statement can take any of the following forms.
i) return;
ii) return (expression);
The first statement does not return any value, it returns the program execution control back to
the caller. A function can return only a single value back to the calling function.
A function may use one or more return statements. It is used when we want to return a value
depending upon certain conditions.
Example1:
if(a>b)
return(a);
else
return (b);
Example2:
switch(x)
{
case 1:
return(1);
break;
case 2:
return(1*2);
break;
default:
return(0);
}
Invoking a Function
A function is called (invoked) by providing the name of the function followed by the values of
parameters. A function can be called simply using its name like other c statement, terminated
by a semi colon(;).
Example:- sum(5, 10);
sum(a, b);
Types of Functions
A function, depending on whether arguments are present or not and whether a value is
returned or not, may belong to one of the following categories.
1. Function with no arguments and no return values
2. Functions with arguments and no return values
3. Functions with arguments and one return value
4. Functions with no arguments but return a value
5. Functions that return multiple values
1. Function with no arguments and no return values
When a function has no arguments, it does not receive any data from the calling function.
Similarly when it does not return a value the calling function does not receive any data from
the called function.
Calling function Analysis Called function
void main() abc()
{ {
-------------- No arguments are passed. ------------
-------------- No values are sent back ------------
abc(); ------------
-------------- }
--------------
}
Output
Have a nice day
Function can return more values using call by reference method. The mechanism of sending
back information through arguments is achieved using what are known as the address operator
(&) and indirection operator(*).
Parameter Passing
There are two ways of passing arguments to a function.
Output
Before swap a=5 and b=7
After swap a=7 and b=5
Advantages of Functions
Reduces the length of the program.
Facilitates top down programming approach.
A function can be used to keep away from rewriting the same block of codes which we
are going use two or more locations in a program.
It is easy to locate and separate a faulty function for further study.
Easy to debug the program.
Recursion
Recursion is the property of a function to call itself. When a function calls itself a new copy of
that function is executed every time. Recursive function should always have a stop condition
otherwise the process continues infinitely.
Example:- Program to read a number and find factorial using recursive function
void main()
{
int a, fact;
printf(“Enter a number”);
scanf(“%d”, &a);
fact = rec (a);
printf(“Factorial value = %d”, fact);
getch();
}
rec(int x)
{
int f;
if (x == 1)
return (1);
else
f = x * rec(x-1);
return (f);
}
Types of Recursion
Recursion are of two types.
1. Direct recursion
2. Indirect recursion
When a function calls itself, this type of recursion is direct recursion. In this type, only one
function is involved. In indirect recursions, two function calls each other.
Indirect Recursion
Direct Recursion
In this type, only one function is involved which calls itself until the given condition is true.
scanf(“%d”,&x);
t=trinum(x);
printf(“\n triangular number of %d is %d”,x,t);
}
int trinum(int x)
{
int f=0;
if(x==0) return f;
else f=f+x+trinum(x-1);
return f;
}
Output
enter a number: 4
triangular number of 4 is 10
Explanation:
Triangular of number means that the sum of all the numbers between 1 to entered number. In
the above program, a function trinum() is defined which calls itself. An integer is entered and is
stored in x. in function trinum() the function calls itself and decreases the value of x passed by
one. The return values are added to f. when the value of x becomes zero, the recursive process
ends and the total sum is returned to variable t in function main().
Indirect Recursion
In this type of recursion, two or more functions are involved in the recursion. The indirect
recursion does not make any overhead as direct recursion. When control exits from one
function and enter into another function, the local variables of former function are destroyed.
Explanation: The s is a global variable. The main() function invokes show() function and
show() function invokes main() function. The value of s is incremented and displayed. When
the value of s reaches to 5, the program is terminated.
Advantages of Recursion
1. At most of the times, a problem can be solved without recursion, but in some situations
in programming, it is a must to use recursion
2. The recursion is very flexible in data structure like stacks, queues, linked list and quick
sort.
3. Using recursion the length of the program can be reduced.
Disadvantages of Recursion
1. It requires extra storage space. For every recursive calls, separate memory is allocated
to automatic variables with the same name.
2. If the programmer forgets to specify the exit condition in the recursive function, the
program will execute out of memory.
3. The recursive function is not efficient in execution speed and time
4. If possible, try to solve problem with iteration instead of recursion.
Visibility of a Variable
Visibility of a variable is another property. It defines its scope. The scope is of two types, i.e.
local and global.
Variables declared within a function are called local variables. The scope of such variable is limited
to the function where it is declared. Variables declared outside of all functions (declared at the
beginning of c program, before main function) is called global variable. Global variables are
accessible to all functions in the program. Global variables are also known as an external variable.
Example:
int m;
main()
{
int i;
float balance;
………
………
function1();
}
function1()
{
int i;
float sum;
………………
……………..
}
The variable m which has been declared before the main is called global variable. The variables i,
balance and sum are called local variables because they are declared inside a function. Note that
the variable i has been declared in both the functions. Any change in the value of i in one function
does not affect its value in the other.
1. Automatic Variables
The auto variables refer to automatic variables. The auto variables are defined inside a
function. A variable declared inside a function without storage class name is, by default, an
auto variable. They are automatically created when function is called and automatically
destroyed when the function terminates. The lifetime of such variable is the time during which
the parent function is running. These variables have function scope; that is they are accessible
only within the parent function.
Example:
void main()
{
auto int v=0;
call2();
printf(“v=%d”);
}
void call1()
{
auto int v=20;
printf(“v=%d”,v);
}
call2
Output
{
auto int v=30; V=20
V=30
call1();
V=10
printf(“v=%d”,v);
}
Explanation: In the above program, the variable ‘v’ is declared and initialized in three different
functions. Each function, when called, prints the local values of variable ‘v’.
2. External variables
The extern variables provide access from different files, if a program spreads over many files.
Thus the lifetime is the life of the entire program. The scope of such variable is file scope. The
variable declaration generally appears before main() and use of keyword extern is optional.
Example:
int j=4;
void main()
{
extern int j;
j=j*3;
printf(“j=%d”,j);
fun();
printf(“j=%d”,j); Output
} j=12
Fun() j=144
{
j=j*j;
}
Explanation: in the above program j is declared and initialized with 4. The second declaration
inside main with keyword extern indicates that it is declared already.
3. Static Variables
The static variable may be of internal or external type, depending where it is declared. When a
variable is declared as static its garbage value is removed and initialized to NULL value. A static
variable is initialized only once. It is not destroyed when the function terminates, rather it
holds its value even after the functions termination.
Example:
void main()
{
for( ; ; )
print();
}
print()
{
int static m; Output
m++; m=1
printf(“m=%d”,m); m=2
if(m==3) m=3
exit(1);
}
Explanation: in the above program print function is called. The variable m of print() function is
the static variable. in the first call its value is changed from 0 to 1, in the second call from 1 to
2, and in the third call from 2 to 3.
Example
#include<stdio.h>
#include<conio.h>
static int i;
int main()
{
i=20;
printf(“the value if i is %d”,i);
return 0;
}
Output
the value of i is 20
in the above program, the external variable ‘I’ is accessed within the scope of this program
only. Other files cannot access a static external variable that is defined in another file.
5. Register Variables
The register variables are similar to auto variables except that the register variables provide
faster access, as they are stored inside CPU registers.
Example:
void main()
{
Output
register int m=1;
1 2 3 4 5
for( ; m<=5;m++)
printf(“\t%d”,m);
}
Explanation: in the above program variable ‘m’ is declared and initialized to 1. The for loop
displays values from 1 to 5. The register class variable is used as a loop variable.
Structure
A structure is a collection of one or more variables of different types, grouped together under a
single unit. It is a user defined data type.
The data items enclosed within a structure are known as members and they can be of the same
or different types.
Features of Structure
1. It is possible to copy the contents of all structure elements to another structure variable
of its type using assignment (=) operator.
2. Nesting of structure is possible
3. It is possible to pass structure elements to a function.
4. It is also possible to create structure pointers. For this -> operator is used.
The structure variable can also be created during the declaration of a structure as follows
struct student
{
int roll;
char name[25];
char course[15];
} s1;
Syntax:
structureVar .memberName;
Example:-
s1.roll;
s1.name;
s1.course;
Initialization of structure
Structure can be initialized as:
struct student s1 = ,1,”amit”,”BCA”);
Program to store name, rollno and marks of 3 subjects of a student into a structure and print it.
void main( )
{
struct student
{
int rno;
char name[20];
int m1;
int m2;
int m3;
};
struct student s;
printf(“Enter rollno, name and 3 marks”);
scanf(“%d%s%d%d%d”, &s.rno, s.name, &s.m1, &s.m2, &s.m3);
printf(“Roll No = %d \n”, s.rno);
printf(“Name = %s \n, s.name);
printf(“Mark1 = %d \n”, s.m1);
printf(“Mark2 = %d \n”, s.m2);
printf(“Mark3 = %d \n”, s.m3);
getch();
}
Array of Structures
It is possible to define array of structures, each array element is similar to a variable of that
structure. The syntax for defining an array of structure is
The syntax for accessing a particular member of the structure of an element of the array is
arrayName [subscript] . memberName;
Example:- struct book
{
char name[10];
float price;
};
struct book b[10];
This provides space in memory for 10 structure variables of type book.
Pointer to Structure
We can define pointer to structure. Here, starting address of the member variables can be
accessed. Thus, such pointers are called structure pointers.
Example: struct book
{ char name[25];
char author[25];
int pages;
};
struct book *ptr;
In the above example, *ptr is pointer to structure book. The syntax for using pointer with
member is as given below:
Program to declare pointer to structure and display the contents of the structure
void main()
{
struct book
{
char name[25];
char author[25];
int pages;
};
struct book b1=,“c language”,”ashok n”,672-;
struct book *ptr;
ptr=&b1;
printf(“%s by%s of %d pages”, ptr->name,ptr->author,ptr->pages);
}
Output
c language by ashok n of 672 pages
Explanation: to print structure elements using pointer an arrow operator (->) is used. The
reason is that ptr is not a structure variable but pointer to a structure.
------------
show(&b1);
--------------
--------------
}
show(struct book *b2)
{
---------------
---------------
}
Example: Program to pass address of a structure variable to a user defined function and
display the contents.
struct book
{
char name[25];
char author[25];
int pages;
};
void main()
{
struct book b1=,“c language”,”ashok n”,672-;
show(&b1);
}
show(struct book *b2)
{
printf(“%s by%s of %d pages”, b2->name,b2->author,b2->pages);
}
Output
c language by ashok n of 672 pages
Union
union is a variable, which is similar to the structure. it contains number of members like
structure but it holds only one object at a time.
The syntax for union is identical to that for structures. In structure each member has its own
storage location whereas all the members of union use the same location. This implies that
although a union may contain members of different types it can handle only one member at a
time. A union is declared using the keyword union.
This declares a variable example of the type union sample. The members of example are
referred to as example. Integer and example.real.
If a value is assigned to example.integer then the value is placed in integer format. A union can
contain as many members as desired, of any type, but it allocates only enough memory to hold
the largest member.
Example: write a program to find the size of union and the number of bytes reserved for it.
void main()
{
union result
{
int marks;
char grade;
};
struct res
{
char name[15];
int age;
Output
union result perf;
size of union: 2
}
size of structure: 19
data;
printf(“size of union:%d\n”, sizeof(data.perf));
printf(“size of structure:%d\n”,sizeof(data));
}
Explanation: union contains two variable of data type int and char. The int and char require 2
bytes and 1 byte, respectively, for storage. The union reserves two bytes because int takes
more space than the char type.
The structure res is defined immediately after union, which contains data types char, int and
union variable. the total size of structure is 19, i.e. sum of 15 bytes of char array, two bytes of
int and two bytes of union variable perf.
Now ptr can hold the address of a structure variable of the type student. The element ptr can
be accessed by the expression s1.ptr and the element roll of the structure variable pointed to
by ptr is referenced by s1.ptrroll
Syntax
#define symbolic-name value of constant;
Example:
#define pi 3.14
#define max_val 100
typedef
c supports a feature known as type definition that allows users to define an identifier that
would represent an existing data type. The user-defined data type identifier can later be used
to declare variable.
General form
typedef type identifier;
where type refers to an existing data type and identifier refers to the new name given to the
data type. Typedef cannot create a new data type.
Example
#define h 60
void main()
{
typedef int hours;
hours hrs;
printf(“enter hours:”);
scanf(“%d”,&hrs);
printf(“minutes=%d”,hrs*h);
}
Output
enter hours: 2
minutes = 120
Bit Fields
Bit field provides exact amount of bits required for storage of values. If a variable value is 0 or 1
then a single bit is needed to store it. Similarly if the value is between 0 and 3 then 2 bits are
needed. In the same way if the value is between 0 and 7 then three bits will be sufficient to
hold the variable and so on.
An integer variable uses 2 bytes to hold data. Instead of using complete integer if bits are used,
space of memory can be saved.
For example, to know the information about a vehicle, the following information has to be
stored in memory
1. Petrol vehicle
2. Diesel vehicle
3. Two wheeler vehicle
4. Four wheeler vehicle
5. Old model
6. New model
In order to store the status of the above information, we may need 2 bits for the type of fuel
(petrol or diesel). Three bits for its type as to whether the vehicle is a two wheeler or four
wheeler. Similarly, 3 bits for model of the vehicle. Total bits required for storing the
information would be 8 bits, i.e. 1 byte.
The structure for the above problem would be as follows:
struct vehicle
{
unsigned type: 3;
unsigned fuel: 2;
unsigned model: 3;
};
The colon(:) tells the compiler that bit fields are used in the structure and the number after it
indicates how many bits are required to allot for the field.
Program:
#define petrol 1
#define diesel 2
#define two_wh 3
#define four_wh 4
#define old 5
#define new 6
void main()
{
struct vehicle
{
unsigned type: 3;
unsigned fuel: 2;
unsigned model: 3;
};
struct vehicle v;
v.type=four_wh;
v.fuel=diesel;
v.model=old;
printf(“\n Type of vehicle: %d”, v.type);
printf(“\n Fuel: %d”, v.fuel);
printf(“\n Model: %d”, v.model);
getch();
}
Output
Type of vehicle: 4
Fuel:2
Model:5
Syntax
enum identifier ,value1, value2, …….. value n-;
The identifier can be used as the data type that represents the list of values separated by
commas. The compiler automatically assigns integer digits beginning with 0 to all the
enumeration constants.
Example: enum week {sun,mon,tue,wed,thu,fri,sat};
The above statement creates an enumerated data type week, by which 7 identifiers are
assigned 7 values called ordinal values 0,1,2,3,4,5,6. The number 0 is given to the identifier sun,
1 is given to mon, 2 is given to tue, …………….., and 6 is given to sat. These are the default
ordinal values.
The format specifier for enum is %d and the range is -32768 to +32767
The default ordinal values of the enumerators can be changed by explicitly specifying them for
the identifiers.
Example: enum color {red=5, green, blue=10};
In the above definition, the enumerators red and blue are assigned with the specified values,
whereas green will be assigned the value 6.
The enumerated data type is used to declare variables like any other data types. The following
statement creates a variable day of the type week.
week day;
Internally c compiler treats day as integer and hence 2 bytes of memory will be allocated for it.
Use of enumeration constants, in general makes the program easier to read.
2) if (day==sun) printf(“holiday”);
Example:
void main()
{
enum month
{ jan=1, feb,mar,apr,may,june,july,aug,sep,oct,nov,dec };
printf(“\n Jan = %d”, jan);
printf(“\n Feb = %d”, feb);
printf(“\n Dec = %d”, dec);
}
Output
Jan = 1
Feb = 2
Dec = 12
The instructions and global and static variables are stored in a region known as permanent
storage area and the local variables are stored in another area called stack. The memory space
that is located between these two regions is available for dynamic allocation during execution
of the program. This free memory region is called the heap. The size of the heap keeps
changing when program is executed due to creation and death of variables that are local to
functions and blocks.
Memory Models
The memory model specifies the memory size assigned to each of the different parts or
segments of a program. The memory model directive specifies the size of the memory the
program needs. Based on this directive, the compiler assigns the required amount of memory
to data and code.
Each one of the segments (stack, data and code), in a program, is called a logical segment.
Depending on the model used, segments may be in one or in different physical segments.
There are six types of memory models.
1. Tiny: Tiny model places all data and code in a single segment. Therefore, the total
program file size can occupy no more than 64KB. Programs are executed quickly in this
case.
2. Small: Small model supports one data segment and one code segment. Used when
code under 64KB is and data is under 64KB. Execution speed is same as tiny model.
3. Medium: Medium model supports multiple code and single data segments. Used when
code is over 64KB and data is under 64KB. Fast access to data but slower program
execution.
4. Compact: Compact model supports multiple data segments and a single code segment.
Used when code is under 64KB and data is over 64KB. Slow access to data and quick
code execution.
5. Large: Large model supports multiple code and multiple data segments. Used when
code is over 64KB and data is over 64KB. No single data item can exceed 64KB. There is
slower code execution.
6. Huge: Huge model supports multiple code and multiple data segments. Used when
code is over 64KB and data is over 64KB. Single data item can exceed 64KB. There is
slowest code execution.
1. malloc()
This function is used to allocate memory space in bytes to the variables of different data types.
The function reserves bytes of determined size and returns the base address to pointer
variable. The format of malloc() is:
pnt = (data type*) malloc(given size);
Example:
pnt = ( int * ) malloc(20);
Here, 20 bytes are allocated to pointer variable pnt of type int and base address is returned to
pointer pnt.
Example: program to allocate memory to a pointer variable based on the number of subjects
marks to be entered. Compute average marks.
#include<alloc.h>
void main()
{
int k,*p,j=0,sum=0;
float avg;
puts(“how many subjects marks to be entered:”);
scanf(“%d”,&k);
p=(int *) malloc(k * sizeof(int));
while(j!=k)
{
printf(“subject %d marks=”,j+1);
scanf(“%d”,p+j); Output
j++; how many subjects marks to be entered: 5
} subject 1 marks=88
j=0; subject 2 marks=89
printf(“sum of marks :”); subject 3 marks=90
while(j!=k) subject 4 marks=91
sum=*(p+j++)+sum; subject 5 marks=92
printf(“%d”,sum);
avg=sum/k; sum of marks : 445
printf(“average marks=%f:”,avg); average marks =89.000000
getch();
}
Explanation: the size declared by sizeof function and the number entered (k) are multiplied and
the result obtained is nothing but the number bytes to be allocated to a pointer ‘*p’. The
pointer ,*p, contains the base address. The first ‘while’ loop reads marks of the subjects
through the keyboard. Each time while entering the marks, ‘j’ variables value is added to
pointer ‘*p’, which indicates successive address of its type and entered subjects marks are
stored in the successive locations. This process continues till the value of ‘j’ reaches to ‘k’. Thus
in a single variable by allocating memory, a programmer can store multiple subjects marks. In
the second while loop, sum and average of marks are calculated.
2. calloc()
This function is useful for allocating multiple blocks of memory. It is declared with two
arguments. The prototypes are declared in alloc.h and stdlib.h. the format of calloc is as
follows:
pnt = (int *) calloc(4,2);
The above declaration allocates four blocks of memory; each block containing two bytes. The
base address is stored in the integer pointer. This function is usually used for allocating
memory for array and structure.
#include<alloc.h>
void main()
{
int k,j=0,sum=0;
int *p;
puts(“how many books to be purchased”);
scanf(“%d”,&k);
p = (int *) calloc(k,2);
while(j!=k)
{ Output
printf(“cost of the book (%d)=”,j+1); how many books to be purchase: 4
scanf(“%d”,p+j); cost of the book (1) = 100
sum=sum+*(p+j); cost of the book (2) = 200
j++; cost of the book (3) = 400
} cost of the book (4) = 500
printf(“total cost of books:”); total cost of books: 1200
printf(“%d”,sum);
}
Explanation: in the above program the function calloc() is used to allocate the memory instead
of malloc().
3. free()
The free() function is used to release the memory if not required. Thus the wastage of memory
is prevented. The declaration is as follows:
free(pnt);
The free() function releases the memory occupied by the pointer variable pnt.
Example: Based on the requirement of the number of e-books, write a program to allocate
memory using calloc() and release it using free(). Display the memory locations where cost of
the each e-book is stored and total cost of e-books.
#include<alloc.h>
void main()
{
int j=0,k=5;
int *p;
float sum=0.0;
Explanation: program logic is same as used in the earlier programs where calloc() is used. The
function free() is used for freeing the memory.
4. realloc( )
This function reallocates the main memory. This is needed as and when allocated memory is
different from the required memory. The prototype are declared in alloc.h and stdlib.h. if the
block cannot be reallocated or size==0, realloc() returns NULL. The declaration of function is as
follows:
str = (char*) realloc (str, 30)
In the above declaration, str is a pointer. The realloc() function reallocates the memory
previously allocated by pointer variable str to the new size 30.
Program
#include<alloc.h>
#include<string.h>
void main()
{
char *str;
str = (char *)malloc(6);
str = (“india”);
printf(“str = %s”, str);
str = (char *)realloc(str,30);
strcpy(str, “great researchers of india”);
printf(“now str=%s”,str); Output
free(str); str = india
} now str = great researchers of india
Explanation: In the above program, using malloc() function 6 bytes are allocated to character
pointer str. the character pointer is initialized with string ‘india’. Using realloc() function the
pointer contains 30 bytes. The pointer str is again initialized with ‘ great researchers of india’.
5. coreleft( )
This function returns a measure unused memory. If the memory model declared is tiny, small
or medium, then follow the function declaration as per statement (a). if the memory model
selected is compact, large or huge, follow the declaration (b).
Example:
#include<alloc.h>
void main()
{
clrscr();
printf(“measuer of unused memory = %u”, coreleft( ));
}
Output
measure of unused memory = 56936
Explanation:
In the above program, the coreleft( ) is invoked without any argument. The function displays
unused memory i.e. 56936
Mathematical Functions
Some standard mathematical functions under math.h header file
Function Use Example
sqrt() Finds square root sqrt(25) will return 5
pow() Calculates a value raised to a power pow(x,y) means xy
abs() Returns the absolute value of a number abs(-5) will return 5
log() Finds natural logarithm log(a)
log10() Finds base 10 log log10(b)
floor() Rounded down to the nearest integer floor(1.23)
ceil() Rounded up to the nearest integer ceil(a)
sin() Calculates sin sin(a)
cos() Calculates cosine cos(a)
tan() Calculates tangent tan(a)
Department of Computer Applications | Baselios Poulose Second College Piramadom : 2020– ‘21
SPJ
Model Questions
Short Answer (2 marks)
1. What is algorithm?
2. What are the different types of algorithm?
3. What is a sub program?
4. Differentiate between syntax errors and logic errors.
5. What is testing a program? Why do we need to test a program?
6. What is alpha and beta version of a software?
7. Differentiate between testing and debugging.
8. What do you mean by data type?
9. What is pseudo code?
10. What is an assembler?
11. Differentiate implicit and explicit conversions in c.
12. Give an example for input operator in c.
13. What is a string?
14. What is loop?
15. Write the statement to create a constant in c.
16. What are the logical operators used in c?
17. Distinguish between break and continue statements.
18. What are the parameter passing techniques used in c?
19. What is an expression?
20. How is a variable declared to be a pointer?
21. What is the difference between the type int and unsigned int in c?
22. How do you define a constant in a c program?
23. What is wrong in the following program segment?
for (i = 0; i <10; i++)
, ……………….
………………….
i++;
…………………
}