Mc7102 Notes
Mc7102 Notes
Mc7102 Notes
com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
UNIT 1
INTRODUCTION TO COMPUTER PROBLEM SOLVING
I. Programs and requirements for problem solving
Problem solving can be stated as intricate process requiring much thought, careful
planning, logical precision, persistence and attention to detail. It can be challenging, exciting and
satisfying experience with considerable room for personal creativity and expression.
programming language.
v Program should supply with input data.
v Input data manipulate according to the instructions and produce the output.
v Output represents computer solution to the problem.
Problem
Algorithm
Algorithm:
Algorithm consists of a set of explicit and unambiguous final steps which, when carried
out for a given set of initial conditions, produce the corresponding output and terminate in a
finite time.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
problem.
Example : Telephone Directory Look up Problem:
· A Telephone directory has thousands of names and numbers.
· Searching by name or number from page 1 is lengthy and time consuming
process.
· Probably the directory is sorted by number than name.
· Data structure is linked with algorithm for high performance.
mechanization.
v Problem solving has number of steps to achieve the goal.
can we do”.
v Proverb states that “Sooner your start coding your program the longer it is going
to take”.
3) Use of specific examples:
v Many strategies, while using, we may stuck in some point.
v It is usually much easier to work out the details of a solution to a specific
problem.
v Geometrical or schematic diagrams representing certain aspects of the problem
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Problem: Given 2 positive non zero integers n and m. find GCD of n and m.
Algorithm development:
1. Ordinary Procedure
v Find the common divisors of both n and m.
v Then find the GCD of both in common.
2×2×3=12
· GCD of 60, 24 is 12.
Here step 3 is tedious.
2. Euclid’s Algorithm:
gcd(m, n) = gcd(n, m mod n)
i.e Remainder of division m by n
Step 1: If n=0 return value of m and stop
Else goto step 2
Step 2: Divide m by n and assign remainder to r
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Pseudo code:
While n≠0
r←m mod n
m←n
n←r
return m
Thus, largest integer that divides both numbers evenly is called GCD.
3. Another Method:
Ø The GCD of 2 numbers may be the least of the 2 numbers (or) less than the small
if (t)
Then t is the answer
Else
T=t-1
Decrease by 1
Algorithm:
Step 1: t=min {m,n}
Step 2: Divide m by t
M mod t = 0
Goto step 3
Other
Goto step 4
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Step 3: Divide n by t
If (n mod t = 0)
Return t
Else
Goto step 4
Step 4: t = t-1
Goto step 2
Algorithm work fine when one i/p is zero. Otherwise it is time consuming.
4) Similarities among problems:
v Get the past experience for any current problem
v Start any solving process with specific example.
v Have aware about the similarities of various problems.
v More experience in more tools and techniques helps to solve the problem easily.
v Sometimes previous experience blocks new creativity or better solution.
v Place only cautious reliance on past experience.
v Independently solving the problem sometimes gives better solution.
v Analyzing past problems and experience sometimes leads to dead end.
v Solve a problem after viewing the problem from different angles.
v Analyze the problem by turning a problem upside down, inside out, sideways,
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
3 14 27 31 39 42 55 m
70 74 81 85 93 98
r
Ø Need log2n comparison rather than n comparison.
Ø It is good for searching problems.
problems
v It is technique for solving problems with overlapping sub problems
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
condition.
v These, work with i/p or o/p statements, computable expressions and assignments form the
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Summation problem
i=1
s=a[1]
The solution for n>1 is
i=i+1
s=s+a[i]
i=0; s=0;
while i<n do
begin
i=i+1;
s=s+a[i];
end
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
For i=1 to n do
Begin
.
.
.
end
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
procedures.
v This set of procedures will perform well defined tasks.
Procedure sort
Begin
Writeln(‘sort called’)
end
work.
v Example : To name a variable to store a day means, variable name is day instead of just
d or a.
v A clean definition of all variables and constants at the start of each procedure can makes
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
v The program should properly handle the wrong request i.e proper response should behe
given.
[4] Debugging programs:
v Various test should be done even for a small program to have a error free program.
v Additional information given with output that it can work normal or abnormal situation
if debug thenf
Begin
Writeln(…..)
End
v Error should be handled more effectively which results in a good program.
v Work the program by hand before put in to the system.
v No method for debugging but some steps makes the task easy.
v Example : Binary search procedure
Problem
1. Search value x
2. Array a[1….n]
3. x=44; n=15
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
V. Program Verification
v Software development and debugging need more time and effort.
v Large program need more time and more effort.
v Top down design are useful to make the program readable and understandable.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
v Program correctness can be a matter of life or death in the case of military, space and
medical applications.
v Demonstrating program correctness is more needed that working different input to a
particular problem.
Program Verification:
It refers to a application of mathematical proof techniques to establish that the results
obtained by the execution of a program with arbitrary inputs are in accord with formally defined
output specifications.
Prove the algorithm at the basic level itself or abstract or superficial level.
[1] Computer model for program execution
v A program may have variety of path for termination.
v According to the input path has chosen for execution and terminate.
v A program may transit from one state to another.
v A state transition changes the value of the variable in a current execution path.
v As well as instructions that change the computation state there also other instructions that
variable
v Output assertion: Produce for input data that satisfies the input assertion.
(x=q * y + r) ^ r<y
^ - Logical connectivity “and”
Q - Quotient
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
R - remainder
x divided y
P Q
P à assumption
Q à conclusion
P Q P Q
TrueTrueTrue
TrueFalseFalse
FalseTrueTrue
FalseFalsetrue
v If assumption and conclusion are same then true else if conclusion is true then true.
v Symbolic execution replaces all input data values into symbolic value and all arithmetic
the input assertion with symbolic values substituted for all input variables implies the
output assertion with final symbolic values substituted for all variables. This is called as
Verification condition.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
v A number of intermediate verification conditions between the input and output assertionsinput
are needed.
v Verification conditions are straight line segment, branching segments and loop segment.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
problem.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
In linear search each data is visited and if target achieved the program terminates.
If it does not terminate then occur inefficiency.
Version 1 terminates after visiting complete list of items.
Version 2 terminates once the target is obtained.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Eg Bubble sort
v Due to the nature of input the output condition met early before termination condition
met.
v This will happen when i/p list is in sorted order.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· A algorithm is efficient if its saves computing resources which saves times and money.
[1]Computational complexity:
Computational model that gives the algorithm performance foe specified input
conditions.
· It is a quantitative measurement.
· Performance measured in terms of problem size (n).
· n increases then cost increases.
· Lower end of the scale, also have logarithmic dependence of n.
· Higher end of the scale, also have exponential dependence on n.
Computational cost as a function of problem size for a range of computational
complexities.
Log 2nNNlog2nN2N32n
122484
23
3.3221033.221010>103
6.644102664.4104106>>1025
9.9661039966.0106109>>10250
13.287104132,8771081012>>102500
v One can solve only very small problem with an algorithm that exhibits exponential
behavior.
v Logarithmic dependence on n
If problem n=104, 13 steps needed 13 micro seconds needed.
v Exponential algorithm on n if n=100, Time taken : Earth terminate
v N grows due to comparison or number of times some arithmetic expressions repeated.
for algorithms.
v It is three types.
v Usually O notation is used. O notation can be called “Big O” notation.
v An algorithm in which the dominant mechanism is executed cn2 times for c, a constant
and nà problem size is said to be order n2 complexity. It can be written as O(n2).
v A function g(n) is Of(n) provided there is a constant c, the relation is g(n) ≤ c f(n) holds
v G(n)
for and f(n) can
all value of nbethat
expressed asand
are finite lim:→
positive. : =
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
3n2+6n+3 =3
N2
v The particular algorithm has an asymptotic complexity of O(N2).
v An algorithm with a higher asymptotic complexity has a very small constant of
proportionality and hence for some particular range of n it will give better performance
than an algorithm with lower complexity and a higher proportionality constant.
[3] Worst and average case behavior
v Worst and average case applied to both the time and space complexity of an algorithm.
v Worst complexity:
expected complexity of a given algorithm rather than the worst case behavior.
v The expected complexity gives a measure of the behavior of the algorithm averaged over
Worst case:
Necessary for the algorithm to examine all n values in the list before terminating.
Average case:
A probabilistic average case analysis it is generally assumed that all possible points are
equally likely, i.e the probability that x will be found at position 1 is 1/n and at position 2 is 1/n
and so on.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
v The average search cost is therefore the sum of all possible search costs each multiplied
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
v It is exact only when n is one less than a power of two. Some calculus is needed to evaluate
the sum
v After substituting the sum in average search cost expression, average search cost is got
UNIT II
PROGRAMMING, ALGORITHMS & FLOW CHARTSFLOW
1) Program and programming
· A computer can neither think nor judge on its own.
· A computer independently analyzes a given data and find a solution on its own.
· A program is a set of logically related instructions that is arranged in a sequence and
guides the computer in solving a problem.
· A program is a set of instructions to perform a task.
· Process of writing a program is called Programming.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· If the system is not correctly programmed, it delivers information results that cannot
be used.
· Program acquired by
1. Purchase an existing program – Packaged software
2. Prepare a new program from scratch – Customized software.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
programming languageslanguages.
Important categories of software packages available are
· Database management software
· Spreadsheet software
· Word processing, Desktop publishing and Presentation software.
· Multimedia software
· Data communication software
· Statistical and operational research software
· Categories of a Application software
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Read grade
If(grade>=95)
Then destination
Else
Try to get it
v With if only used one condition checked.
v If else 2 condition checked.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Case(result>=90)
Print ‘a’
Case(result>=80)
Print ‘b’
Case(result>=70)
Print ‘c’
Case(result>=60)
Print ‘d’
Case (result<60)
Print ‘f’
· This has more alternatives. According to the alternatives the structures are chosen.
3. Repitition:
· One or more steps are performed repeatedly under a condition.
· Example: Compute the average of 10 numbers.
Ex 1:
Total=0
Average=0
For 1 to 10
Read number
Total=total+number
End for
Average=total/10
Ex 2:
For 1 to 10
Print “hai”
Ex 3:
Read 10 numbers
While (total<s)do
Read number
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Total=total+number
End do
[2] Analysis:
· Involves identifying the problem
a. inputs
b. Outputs
c. Constraints on the solution
· Determine the required format in which output is displayed.
· Develop a list of problem variables and their relationship.
· It can be expressed as formulas.
· Problem statement-read very carefully
· Underline the phrases in the problem statement that identify input and output.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Compute and display the total cost of apples given the number of pounds of apples purchased
and the cost per pound of apples.
Problem Input: Quantity of apples purchased (in pounds)
Cost per pound of apples (in dollars per pound)
Problem output: Total cost of apples (in dollars)
Formula designed: General formula
Total cost=Unit cost ×Number of units.
· The processing of modeling a problem by extracting the essential variables and their
steps.
· To desk check algorithm, carefully perform each algorithm step and verify the task of
process.
[4]Implementation:-
· Involving in writing the program.
· It converts each algorithm step into one or more statements in a programming language.
Example:-
int x,y;
scanf(“%d”,&x);
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
scanf(“%d”,&y);
X=x+y;
printf(“The Result is %d”,X);
[5]Testing:-
· To test the completed program to verify that it works as desired.
· Don’t rely on one test case.
· Test the program using different set of data for every situation.
[6]Maintenance:-
· Maintaining and updating the program involves modifying the program to resolve
an actual programming language. It uses short phrases to write code for programs before
one actually create it in a specific language.
· An outline of a program, written in a form that can easily be converted into real
programming statements. For example, the pseudocode for finding given number odd or
even.
pseudo code for finding whether a given number is even or odd.
1) Input number 'X' from user
2) Divide the X by 2 and store its remainder As 'R'
3) if R is 0 then print 'X' is an even number
4) if R is not 0 then print 'X' is an odd number.
5) Exit
C Program for finding whether a given number is even or odd.
void main()
{
int x,r;
clrscr();
printf("Enter a number ");
scanf("%d", x);
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
r = x/2;
if (r = 0)
printf("Given number is Even")
else
printf("Given number is Odd.")
getch();
}
Flowchart
Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing
program and explaining program to others.
Symbols Used In Flowchart
Different symbols are used for different states in flowchart, For example: Input/Input/Output and
decision making has different symbols. The table below describes all the symbols that are used in
making flowchart
Symbol Purpose Description
Flow line Used to indicate the flow of logic by connecting
symbols.
Terminal(Stop/Start) Used to represent start and end of flowchart.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Though, flowchart are useful in efficient coding, debugging and analysis of a program, drawing flowchart
in very complicated in case of complex programs and often ignored.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
5) Algorithm
In programming, algorithm is the set of well defined instruction in sequence to solve a
program. An algorithm should always have a clear stopping point.
Qualities of a good algorithm
· Inputs and outputs should be defined precisely.
· Each steps in algorithm should be clear and unambiguous.
· Algorithm should be most effective among many different ways to solve a problem.
· An algorithm shouldn't have computer code. Instead, the algorithm should be written in
such a way that, it can be used in similar programming languages.
Examples Of Algorithms In Programming
Algorithm to add two numbers entered by user.
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Algorithm to find the largest among three different numbers entered by user.
Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Step 5: Stop
Algorithm to find all roots of a quadratic equation ax2+bx+c=0.
Step 1: Start
Step 2: Declare variables a, b, c, D, x1, x2, rp and ip;
Step 3: Calculate discriminant
D←b2-4ac
Step 4: If D≥0
r1←(-b+√D)/2a
r2←(-b-√D)/2a
Display r1 and r2 as roots.
Else
Calculate real part and imaginary part
rp←b/2a
ip←√(-D)/2a
Display rp+j(ip) and rp-j(ip) as roots
Step 5: Stop
An algorithm to find the factorial of a number entered by user.
Step 1: Start
Step 2: Declare variables n,factorial and i.
Step 3: Initialize variables
factorial←1
i←1
Step 4: Read value of n
Step 5: Repeats the steps until i=n
5.1: factorial←factorial*i
5.2: i←i+1
Step 6: Display factorial
Step 7: Stop
An algorithm to check whether a number entered by user is prime or not.
Step 1: Start
Step 2: Declare variables n,i,flag.
Step 3: Initialize variables
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
flag←1
i←2
Step 4: Read n from user.
Step 5: Repeats the steps until i<(n/2)
5.1 If remainder of n÷i equals 0
flag←0
Go to step 6
5.2 i←i+1
Step 6: If flag=0
Display n is not prime
else
Display n is prime
Step 7: Stop
Algorithm to find the Fibonacci series till term≤1000.
Step 1: Start
Step 2: Declare variables first_term,second_term and temp.
Step 3: Initialize variables first_term←0 second_term←1
5.3: first_term←temp
5.4: Display second_term
Step 6: Stop
Algorithm is not the computer code. Algorithm is just the instructions which give clear idea to
you idea to write the computer code.
6) Programming Languages
The different generations of languages
There are currently five generations of computer programming languages. In each generation, the
languages syntax has become easier to understand and more human-readable.
First generation languages (abbreviated as 1GL)
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Represent the very early, primitive computer languages that consisted entirely of 1's and 0's - the
actual language that the computer understands (machine language).
Second generation languages (2GL)
· Represent a step up from the first generation languages.
· Allow for the use of symbolic names instead of just numbers.
· Second generation languages are known as assembly languages.
· Code written in an assembly language is converted into machine language (1GL).
Third generation languages (3GL)
· With the languages introduced by the third generation of computer programming, words
and commands (instead of just symbols and numbers) were being used.
· These languages therefore, had syntax that was much easier to understand.
· Third generation languages are known as "high level languages" and include C, C++,
Java, and Javascript, among others.
Fourth generation languages (4GL)
· The syntax used in 4GL is very close to human language, an improvement from the
previous generation of languages.
· 4GL languages are typically used to access databases and include SQL and ColdFusion,
among others.
Fifth generation languages (5GL)
· Fifth generation languages are currently being used for neural networks.
· A nueral network is a form of artifical intelligence that attempts to imitate how the
human mind works.
· Human makes the computer to think.
Classification of Programming languages
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Imperative Programming
· Control flow in imperative programming is explicit: commands show how the:
compuation takes place, step by step.
· Each step affects the global state of the computation.
result = []
i=0
start:
numPeople = length(people)
if i >= numPeople goto end
p = people[i]
nameLength = length(p.name)
if nameLength <= 5 goto next
upperName = toUpper(p.name)
addToList(result, upperName)
next:
i=i+1
goto start
end:
return sort(result)
Structured Programming
· Structured programming is a kind of imperative programming where the control flow is
defined by nested loops, conditionals, and subroutines, rather than via gotos. Variables
are generally local to blocks (have lexical scope).
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
result = [];
for i = 0; i < length(people); i++ {
p = people[i];
if length(p.name)) > 5 {
addToList(result, toUpper(p.name));
}
}
return sort(result);
· Early languages emphasizing structured programming: Algol 60, PL/I, Algol 68, Pascal,
C, Ada 83, Modula, Modula-2. Structured programming as a discipline is sometimes
though to have been started by a famous letter by Edsger Dijkstra entitled Go to
Statement Considered Harmful.
Object Oriented Programming
· OOP is based on the sending of messages to objects. Objects respond to messages by
performing operations. Messages can have arguments, so "sending messages" looks a lot
like calling subroutines.
· A society of objects, each with their own "local memory" and own set of operations has a
different feel than the "monolithic processor and single shared memory" feel of non
object oriented languages.
result = []
for p in people {
if p.name.length > 5 {
result.add(p.name.toUpper);
}
}
return result.sort;
· The first object oriented language was Simula-67; Smalltalk followed soon after as the
first "pure" object-oriented language. Many languages designed from the 1980s to the
present have been object-oriented, notably C++, CLOS (object system of Common Lisp),
Eiffel, Modula-3, Ada 95, Java, C#, Ruby.
· Declarative Programming
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· Control flow in declarative programming is implicit: the programmer states only what the
result should look like, not how to obtain it.
select upper(name)
from people
where length(name) > 5
order by name
· No loops, no assignments, etc. Whatever engine that interprets this code is just supposed
go get the desired information, and can use whatever approach it wants. (The logic and
relational paradigms are generally declarative as well.)
Functional Programming
let(
f, fun(
people,
if(equals(people, emptylist),
emptylist,
if(greater(length(name(head(people))), 5),
append(to_upper(name(head(people))), f(tail(people))),
f(tail(people))))),
sort(f(people)))
let
fun f [] = []
| f (p :: ps) =
if p.name.length() > 5 then p.name.to_upper()::(f ps)
else (f ps)
in
sort(f(people))
The real power of this paradigm comes from passing functions to functions (and
returning functions from functions).
sort(
filter((λs. s.length() > 5),
map((λp. p.name.to_upper()), people)
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Compiler
· "A compiler translates the high-level source programs into target programs in machine
languages for the specific hardware. Once the target program is generated, the user can
execute the program.
· A compiler reads analyses and translates code into either an object file or a list of error
messages.
A compiler for a language generally has several different stages as it processes the
input.
1. Preprocessing
· During the preprocessing stage, comments, macros, and directives are processed.
Comments are removed from the source file. This greatly simplifies the later stages.
· If the language supports macros, the macros are replaced with the equivalent text.
· For example, C and C++ support macros using the #define directive. So if a macro were
defined for pi as: #define PI 3.1415927
· Any time the preprocessor encountered the word PI, it would replace PI with 3.1415927
and process the resulting text.
· The preprocessor may also replace special strings with other characters. In C and C++,
the preprocessor recognizes the \ character as an escape code, and will replace the escape
sequence with a special character. For example \t is the escape code for a tab, so \t would
be replaced at this stage with a tab character.
2. Lexical analysis
· It is the process of breaking down the source files into key words, constants, identifiers,
operators and other simple tokens. A token is the smallest piece of text that the language
defines.
C tokens:
· C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· Each and every smallest individual units in a C program are known as C tokens.
· C tokens are of six types. They are,
§ Keywords (eg: int, while),
§ Identifiers (eg: main, total),
§ Constants (eg: 10, 20),
§ Strings (eg: “total”, “hello”),
§ Special symbols (eg: (), {}),
§ Operators (eg: +, /,-,*)
3. Syntactical analysis
· It is the process of combining the tokens into well-formed expressions, statements, and
programs.
· Each language has specific rules about the structure of a program--called the grammar or
syntax. Just like English grammar, it specifies how things may be put together. In
English, a simple sentence is: subject, verb, predicate.
· In C or C++ an if statement is: if ( expression ) statement
· The syntactical analysis checks that the syntax is correct, but doesn't enforce that it
makes sense. In English, a subject could be: Pants, the verb: are, the predicate: a kind of
car. This would yield: Pants are a kind of car. Which is a sentence, but doesn't make
much sense.
· In C or C++, a constant can be used in an expression: so the expression:
float x = "This is red"++
· Is syntactically valid, but doesn't make sense because a float number cannot have
string assigned to it, and a string cannot be incremented.
4. Semantic analysis
· It is the process of examining the types and values of the statements used to make sure
they make sense.
· During the semantic analysis, the types, values, and other required information about
statements are recorded, checked, and transformed as appropriate to make sure the
program makes sense.
· For C/C++ in the line: float x = "This is red"++
o The semantic analysis would reveal the types do not match and cannot be made to
match, so the statement would be rejected and an error reported.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
oThe semantically analysis would reveal that 5 is an integer, and 3.0 is a double,
and also that the rules for the language allow 5 to be converted to a double, so the
addition could be done, so the expression would then be transformed to a double
and the addition performed. Then, the compiler would recognize y as a float, and
perform another conversion from the double 8.0 to a float and process the
assignment.
5. Intermediate code generation
· Depending on the compiler, this step may be skipped, and instead the program may be
translated directly into the target language (usually machine object code). If this step is
implemented, the compiler designers also design a machine independent language of their
own that is close to machine language and easily translated into machine language for
any number of different computers.
· The purpose of this step is to allow the compiler writers to support different target
computers and different languages with a minimum of effort.
· The part of the compiler which deals with processing the source files, analyzing the
language and generating the intermediate code is called the front end, while the process
of optimizing and converting the intermediate code into the target language is called the
back end.
6. Code optimization
· During this process the code generated is analyzed and improved for efficiency. The
compiler analyzes the code to see if improvements can be made to the intermediate code
that couldn't be made earlier.
· For example, some languages like Pascal do not allow pointers, while all machine
languages do. When accessing arrays, it is more efficient to use pointers, so the code
optimizer may detect this case and internally use pointers.
7. Code generation
· Finally, after the intermediate code has been generated and optimized, the compiler will
generate code for the specific target language. Almost always this is machine code for a
particular target machine.
· Also, it us usually not the final machine code, but is instead object code, which contains
all the instructions, but not all of the final memory addresses have been determined.
· A subsequent program, called a linker is used to combine several different object code
files into the final executable program.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Interpreter
· An Interpreter reads, and translates code line by line.r
· A linker combines one or more object files and possible some library code into some
executable, some library or a list of error messages.
· A loader reads the executable code into memory does some address translation and tries
to run the program resulting in a running program or an error message (or both).
· During program execution, constructs and statements are executed in a prescribed order.,
· Execution in computer and software engineering is the process by which a computer or a
virtual machine performs the instructions of a computer program. The instructions in the.
program trigger sequences of simple actions on the executing machine. Those actions
produce effects according to the semantics of the instructions in the program.
· Programs for a computer may execute in a batch process without human interaction, or a
user may type commands in an interactive session of an interpreter. In this case the.
"commands" are simply programs, whwhose execution is chained together.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
UNIT III
Introduction to C
C is a general-purpose high level language that was originally developed by Dennis Ritchiepurpose
for the Unix operating system. It was first implemented on the Digital Equipment Corporation
PDP-11 computer in 1972.
The Unix operating system and virtually all Unix applications are written in the C language. Cystem
has now become a widely used professional language for various reasons.
· Easy to learn
· Structured language
· It produces efficient programs.
· It can handle low-level activities.level
· It can be compiled on a variety of computers.
Facts about C
· C was invented to write an operating system called UNIX.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Identifiers are names given to C entities, such as variables, functions, structures etc. Identifier
is created to give unique name to C entities to identify it during the execution of program. For
example:
int money;
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
int mango_tree;
Identifier names must be a sequence of letters and digits and must begin with a letter.
· The underscore character (_) is also permitted in identifiers. It is usually as a link
between two words in long identifiers.
· Names should not be the same as a keyword.
· C is a case sensitive (i.e. upper and lower case letters are treated differently). Thus the
names price, Price and PRICE denote different identifier.
Valid examples are:
City, Age, basic_pay, result, date_of_birth, Mark, num1, num2
The following identifiers are invalid:
Keywords are the reserved words used in programming. Each keywords has fixed meaning
and that cannot be changed by user. For example:
int money;
Here, int is a keyword that indicates, 'money' is of type integer.
As, C programming is case sensitive, all keywords must be written in lowercase. Here is the
list of all keywords predefined by ASCII C.
Keywords in C Language
do if static while
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
3. VARIABLES
Variables are memory location in computer's memory to store data. To indicate the memory
location, each variable should be given a unique name called identifier. Variable names are just
the symbolic representation of a memory location. Examples of variable name: sum, car_no,
count etc.
int num;
Here, num is a variable of integer type.
In C, variable (data) should be declared before it can be used in program. Data types are the
keywords, which are used for assigning a type to a variable.
Data types in C
· Fundamental Data Types
o Integer types
o Floating Type
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
o Character types
· Derived Data Types
o Arrays
o Pointers
o Structures
o Enumeration
Syntax for declaration of a variable
data_type variable_name;
i. Integer data types
Keyword int is used for declaring the variable with integer type. For example:
int var1;
ii. Floating types
Variables of floating types can hold real values(numbers) such as: 2.34, -9.382 etc. Keywords
either float or double is used for declaring floating type variable. For example:
float var2;
double var3;
Here, both var2 and var3 are floating type variables.
In C, floating values can be represented in exponential form as well. For example:
float var3=22.442e2
iii. Character types
Keyword char is used for declaring the variable of character type. For example:
char var4='h';
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Type Length
Range
unsigned char 8 bits 0 to 255
char (or ) signed char 8 bits -128 to 127
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
5. CONSTANTS
Constants refer to fixed values that do not change during the execution of a program. Figure
below shows the various types of constants available in C:
Constants
Numeric Character
constant constant
Integer constants
Integer constants are the numeric constants(constant associated with number) without any
fractional part or exponential part. There are three types of integer constants in C language:
decimal constant(base 10), octal constant(base 8) and hexadecimal constant(base 16) .
Decimal digits: 0 1 2 3 4 5 6 7 8 9
Octal digits: 0 1 2 3 4 5 6 7
Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.
For example:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
Floating-point constants
Floating point constants are the numeric constants that has either fractional form or exponent
form. For example:
-2.0
0.0000234
-0.22E-5
Note:Here, E-5 represents 10 -5 . Thus, -0.22E-5 = -0.0000022 .
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Character constants
Character constants are the constant which use single quotation around characters. For
example: 'a', 'l', 'm', 'F' etc.
Escape Sequences
Sometimes, it is necessary to use newline(enter), tab, quotation mark etc. in the program
which either cannot be typed or has special meaning in C programming. In such cases, escape
sequence are used. For example: \n is used for newline. The backslash( \ ) causes "escape" from
the normal way the characters are interpreted by the compiler.
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? Question mark
\0 Null character
String constants
String constants are the constants which are enclosed in a pair of double-quote marks. For
example:
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Enumeration constants
Keyword enum is used to declare enumeration types. For example:
Here, the variable name is color and yellow, green, black and white are the enumeration
constants having value 0, 1, 2 and 3 respectively by default.
6. INPUT AND OUTPUT FUNCTIONS
ANSI standard has defined many library functions for input and output in C language.
Functions printf() and scanf() are the most commonly used to display out and take input
respectively. Let us consider an example:
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
to paste the code from the header file when necessary. When compiler encounters printf()
function and doesn't find stdio.h header file, compiler shows error.
· Code return 0; indicates the end of program. You can ignore this statement but, it is good
Input
Format Type of
Specifier Argument
%c Character Reads a single character
%d or %i Integer Reads a decimal integer
%e or %E or Floating point Reads a floating point value
%f or %g or
%G
%hd or %hi Short integer Reads decimal short integer
%hu Short integer Reads decimal unsigned short integer
%ld or %li Long integer Reads decimal long integer
%le or %lf or Double Reads signed double
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
%lg
%Le or %Lf or Long double Reads signed long double
%Lg
%lo Long integer Reads an octal long integer
%lu Long integer Reads decimal unsigned long integer
%lx Long integer Reads hexadecimal long integer
%o Octal integer Reads an unsigned octal integer
%s Sequence of Reads a string
characters
%u Integer Reads an unsigned decimal integer
%x or %X Hexadecimal Reads a unsigned hexadecimal integer
integer
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
getche(): reads a single character from the keyboard and echoes it to the current text
window, using direct video or BIOS
gets(): reads characters from the standard input stream until an end-of-line or character
or character sequence is seen, or until the end of file, whichever comes first.
putchar() : The C library function int putchar(int char) writes a character (an unsigned
char) specified by the argument char to stdout.
puts() The C library function int puts(const char *str) writes a string to stdout up to but
not including the null character. A newline character is appended to the output.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operator
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Comma operator
9. sizeof operator
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Arithmetic Operators:
Meaning
Operator
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division or remainder after division
Relational Operators
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Logical Operators
Meaning
Operator
&& Logical AND
|| Logical OR
! Logical NOT
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Initialization is the process assigning a value to a variable during variable declaradeclaration. (eg)
int i=0;
Statement : Every line in a program. Eg. Int a,b;
Expression: The expression may consist of a single entity, such as a constant or variable, or it
may consist of some combination of such entities, interconnected by one or more operators..
C=a+b;
Lvalues means address of the variable
Rvalues means value of the variable.
9. TYPEDEF
C automatically converts any intermediated values to the proper type so that the
expression can be evaluated without losing any significance. This automatic conversion isautomatic
known implicit type conversion
Type casting is a way to convert a variable from one data type to another data type. For
example, if you want to store a long va into a simple integer then one can type cast long tovalue
int. One can convert values from one type to another explicitly using the cast operator as
follows:
(type_name) expression
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Consider the following example where the cast operator causes the division of one integer
variable by another to be performed as a floating-point operation:
#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %f\n", mean );}
10. CONTROL STATEMENTS
Types
1. Sequential control structure
2. Selective control structure
3. Iterative control structure
Sequential Control Structure
The normal flow of control of all programs is sequential. In sequential structure, a sequence
of programs statements are executed one after another in the order in which they are placed. Both
selection and repetition statements allow allow the programmer to alter the normal sequential
flow of control.
Sequential programming can also be called linear programming. The sequential programs
are non-modular in nature. That is, reusability of code is not possible. Thus, they are difficult to
maintain and understand. Examples of sequence control structure statements are, the program
will have statements that are placed sequentially and there is no decision involved in the process.
Also, the program does not require a specific task to be repeated over and over again.
Selective Control Structure (or) Decision Control Structure
The selective structure allows the usual sequential order of execution to be modified. It
consists of a test for a condition followed by alternative paths that the program can follow. The
program selects one of the alternative paths depending upon the result of the test for condition.
Examples of selective control structures statements are :
1. Simple if statement
2. if . . . else statement
3. Nested if . . . else statement
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
4. else if ladder
5. switch . . . case . . .default statement
Iterative Control Structure (or) Loop Control Structure
The iterative structure provides the ability to go back and repeat a set of statements.
Iterative structure is otherwise referred to as repetitive structure. Examples of iterative control
structure statements are :
1. while statement
2. do . . . while statement
3. for statement
if STATEMENTS
C allows decisions to be made by evaluating a given expression as true or false. Such an
expression involves the relational and logical operators. Depending on the outcome of the
decision, program execution proceeds in one direction or another. The C statement that enables
these tests to be made is called the if statements.
The if statements may be implemented in different forms depending on the complexity of
conditions to be tested. They are :
1. Simple if statement
2. if . . . else statement
3. Nested if . . . else statement
4. else if ladder
5. The if, if...else and nested if...else statement are used to make one-time decisions
in C Programming, that is, to execute some code/s and ignore some code/s
depending upon the test expression.
Simple if statement
if (test expression) {
statement/s to be executed if test expression is true;
}
The if statement checks whether the text expression inside parenthesis ( ) is true or not. If the test
expression is true, statement/s inside the body of if statement is executed but if test is false,
statement/s inside body of if is ignored.
Example 1: C if statement
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Write a C program to print the number entered by user only if the number entered is
negative.
#include <stdio.h>
int main(){
int num;
printf("Enter a number to check.\n");
scanf("%d",&num);
if(num<0) { /* checking whether number is less than 0 or not. */
printf("Number = %d\n",num);
}
/*If test condition is true, statement above will be executed, otherwise it will not be executed */
printf("The if statement in C programming is easy.");
return 0;
}
Output 1
Enter a number to check.
-2
Number = -2
The if statement in C programming is easy.
When user enters -2 then, the test expression (num<0) becomes true. Hence, Number = -2 is
displayed in the screen.
Output 2
Enter a number to check.
5
The if statement in C programming is easy.
When the user enters 5 then, the test expression (num<0) becomes false. So, the statement/s
inside body of if is skipped and only the statement below it is executed.
C if...else statement
The if...else statement is used if the programmer wants to execute some statement/s when the test
expression is true and execute some other statement/s if the test expression is false.
Syntax of if...else
if (test expression) {
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
expression.
Syntax of nested if...else statement.
if (test expression1){
statement/s to be executed if test expression1 is true;
}
else if(test expression2) {
statement/s to be executed if test expression1 is false and 2 is true;
}
else if (test expression 3) {
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Result: 5 > 3
Output 2
Enter two integers to check.
-4
-4
Result: -4 = -4
switch STATEMENT
Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. If a programmer has to choose one block of statement among
many alternatives, nested if...else can be used but, this makes programming logic complex. This
type of problem can be handled in C programming using switch statement.
Syntax of switch...case
switch (n) {
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
The value of n is either an integer or a character in above syntax. If the value of n matches
constant in case, the relevant codes are executed and control moves out of the switch statement.
If the n doesn't matches any of the constant in case, then the default codes are executed and
control moves out of switch statement.
Example of switch...case statement
Write a program that asks user an arithmetic operator('+','-','*' or '/') and two
operands and perform the corresponding calculation on the operands.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
goto STATEMENT
The goto statement is used to alter the normal sequence of program execution by
unconditionally transferring control to some part of the program. The syntax is :
goto label :
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Where label is an identifier used to label the target statement to which the control would
be transferred. Control may be transferred to any other statement within the current function. The
target function must be labeled followed by a colon. The syntax is :
label : statement ;
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump; /* control of the program moves to label jump */
sum=sum+num;
}
jump:
average=sum/(i-1);
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
printf("Average: %.2f",average);
return 0;
}
Output
Maximum no. of inputs: 4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average: 7.07
Though goto statement is included in ANSI standard of C, use of goto statement should be
reduced as much as possible in a program.
Reasons to avoid goto statement
Though, using goto statement give power to jump to any part of program, using goto
statement makes the logic of the program complex and tangled. In modern programming, goto
statement is considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C program with the use of break and
continue statements. In fact, any program in C programming can be perfectly written without the
use of goto statement. All programmer should try to avoid goto statement as possible as they can.
C programming loops
Loops causes program to execute the certain block of code repeatedly until some
conditions are satisfied, i.e., loops are used in performing repetitive work in programming.
Suppose you want to execute some code/s 10 times. You can perform it by writing that
code/s only one time and repeat the execution 10 times using loop.
There are 3 types of loops in C programming:
1. for loop
2. while loop
3. do...while loop
for loop
Loops cause program to execute the certain block of code repeatedly until test condition
is false. Loops are used in performing repetitive task in programming.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
#include <stdio.h>
int main(){
int n, count, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */
}
printf("Sum=%d",sum);
return 0;
}
Output
Enter the value of n.
19
Sum=190
In this program, the user is asked to enter the value of n. Suppose you entered 19 then,
count is initialized to 1 at first. Then, the test expression in the for loop,i.e., (count<= n)
becomes true. So, the code in the body of for loop is executed which makes sum to 1. Then, the
expression ++count is executed and again the test expression is checked, which becomes true.
Again, the body of for loop is executed which makes sum to 3 and this process continues. When
count is 20, the test condition becomes false and the for loop is terminated.
while loop
The while loop checks whether the test expression is true or not. If it is true, code/s
inside the body of while loop is executed,that is, code/s inside the braces { } are executed. Then
again the test expression is checked whether test expression is true or not. This process continues
until the test expression becomes false.
Syntax of while loop
while (test expression) {
statement/s to be executed. }
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
do...while loop
In C, do...while loop is very similar to while loop. Only difference between these two
loops is that, in while loops, test expression is checked at first but, in do...while loop code is
executed at first then the condition is checked. So, the code are executed at least once in
do...while loops.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
{
printf("Enter a number\n");
scanf("%d",&num);
sum+=num;
}
while(num!=0);
printf("sum=%d",sum);
return 0;
}
Output
Enter a number
3
Enter a number
-2
Enter a number
0
sum=1
In this C program, user is asked a number and it is added with sum. Then, only the test
condition in the do...while loop is checked. If the test condition is true,i.e, num is not equal to 0,
the body of do...while loop is again executed until num equals to zero.
break; and continue
There are two statements built in C programming, break; and continue; to alter the
normal flow of a program. Loops perform a set of repetitive task until text expression becomes
false but it is sometimes desirable to skip some statement/s inside loop or terminate the loop
immediately without checking the test expression. In such cases, break and continue statements
are used. The break; statement is also used in switch statement to exit switch statement.
i. break Statement
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
break;
The break statement can be used in terminating all three loops for, while and do...whilent
loops.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
user. But, if the input is negative, display the average(excluding the average of
negative input) and end the program.
/* C program to demonstrate the working of break statement by terminating a loop, if
user inputs negative number*/
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break; //for loop breaks if num<0.0
sum=sum+num;
}
average=sum/(i-1);
printf("Average=%.2f",average);
return 0;
}
Output
Maximum no. of inputs
4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average=7.07
In this program, when the user inputs number less than zero, the loop is terminated using
break statement with executing the statement below it i.e., without executing sum=sum+num.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
It is sometimes desirable
to skip some statements inside the
loop. In such cases, continue
statements are used.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
int i,num,product;
for(i=1,product=1;i<=4;++i){
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
continue; / *In this program, when num equals to zero, it skips the statement
product*=num and continue the loop. */
product*=num;
}
printf("product=%d",product);
return 0;
}
Output
Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
product=-30
Typedef
C automatically converts any intermediated values to the proper type so that the
expression can be evaluated without losing any significance. This automatic conversion is
known implicit type conversion
Type casting is a way to convert a variable from one data type to another data type. For
example, if you want to store a long value into a simple integer then you can type cast long to
int. You can convert values from one type to another explicitly using the cast operator as
follows:
(type_name) expression
Consider the following example where the cast operator causes the division of one integer
variable by another to be performed as a floating-point operation:
#include <stdio.h>
main()
{
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
1. ARRAYS
· C programming language provides a data structure called the array, which can store a
100 variables individually but, this process is rather tedious and impracticable. This type of
problem can be handled in C programming using arrays.
An array is a sequence of data item of homogeneous value (same type).
· Arrays are of two types:
i. One-dimensional arrays
ii. Multidimensional arrays
Declaration of one-dimensional array
· To declare an array in C, a programmer specifies the type of the elements and the number
int age[5];
Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of
array age. All element in an array are of the same type (int, in this case).
Array elements
· Size of array defines the number of elements in an array. Each element of array can be
accessed and used by user according to the need of program. For example:
int age[5];
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
int age[5]={2,4,34,3,4};
It is not necessary to define the size of arrays during initialization.
int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array by calculating the number of elements of
an array.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
scanf("%d",&marks[i]);
sum+=marks[i];
}
printf("Sum= %d",sum);
return 0;
}
Output
Enter number of students: 3
Enter marks of student1: 12
Enter marks of student2: 31
Enter marks of student3: 2
sum=45
2. MULTIDIMENSIONAL ARRARRAYS
· C programming language allows programmer to create arrays of arrays known as
multidimensional arrays.
· Example: float a[2][6];
o Here, a is an array of two dimension, which is an example of multidimensional
array. This array has 2 rows and 6 columns
o For better understanding of multidimensional arrays, array element of aboveelements
example can be think of as below:
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
OR
int c[2][3]={1,3,0,-1,5,9};
Example:
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
Initialization Of three-dimensional Array
double cprogram[3][2][4]={
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
}
printf("\nSum Of Matrix:");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("%.1f\t",c[i][j]);
if(j==1) /* To display matrix sum in order. */
printf("\n");
}
return 0;
}
Ouput
Enter the elements of 1st matrix
Enter a11: 2;
Enter a12: 0.5;
Enter a21: -1.1;
Enter a22: 2;
Enter the elements of 2nd matrix
Enter b11: 0.2;
Enter b12: 0;
Enter b21: 0.23;
Enter b22: 23;
Sum Of Matrix:
2.2 0.5
-0.9 25.0
3. STRING
· In C programming, array of character are called strings. A string is terminated by null
character /0.
· Example: "c string tutorial"
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· Example
Program
#include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', ''\0'};
printf("Greeting message: %s\n", greeting );n",
return 0;
}
Output
Greeting message: Hello
C supports a wide range of functions that manipulate nullnull-terminated strings:
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
#include <stdio.h>
#include <string.h>
int main ()
char str3[12];
int len ;
strcpy(str3, str1);
len = strlen(str1);
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
return 0;
Output
strlen(str1) : 10
4. ARRAYS OF STRINGS
· An array of strings is a special form of a two-dimensional array.
· The size of the left index determines the number of strings.
· The size of the right index specifies the maximum length of each string.
For example, the following declares an array of 30 strings, each having a maximum
length of 80 characters (with one extra character for the null terminator):
char string_array[30][81];
· For accessing an individual string, one simply specifies only the left index:
firstString = string_array[0];
sixthString = string_array[5];
· The following example calls the gets() function with the third string in the array:
gets(string_array[2]);
This program accepts lines of text entered at the keyboard and redisplays them after a blank line
is entered.
// includes go here
int main()
{
int t, i;
char text[100][80];
for(t=0; t<100; t++) {
cout << t << “: “;
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
gets(text[t]);
if(!text[t][0]) break; // quit on blank line
}
for(i=0; i<t; i++) // redisplay the strings
cout << text[i] << ‘\n’;
return(0);}
An Example Using String Arrays
Arrays of strings are commonly used for handling tables ofvinformation.
One such application would be an employee database that stores
• the name
• telephone number
• hours worked per pay period, and
• hourly wage.
These data we could store in arrays:
char name[20][80]; // employee names
int phone[20]; // phone numbers
float hours[20]; // hours worked
float wage[20]; // wage
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· Here, 65454, 65464, 65474, etc. are the base addresses of successive names.of
· Even though 10 bytes are reserved for storing the name “akshay”, it occupies only 7
bytes. Thus, 3 bytes go waste.
· ‘Array of pointers’ used to avoid wastage.
7. FUNCTION
· In programming, a function is a segment that groups code to perform a specific task.orm
· A function is a self-contained block of statements that performs a specified task. Thecontained
specified task is repeated each time that the program calls the function.
· Functions break large computing tasks into smaller ones. They work togeth totogether
accomplish the goal of the whole program.
· Every program must contain one function named main() where the program always
begin execution.
· The function name is an identifier and should be unique.
Types of C functions
Basically, there are two types of functions in C on basis of whether it is defined by user or not.
· Library function
· User defined function
i. Library function
Library functions are the in-built function in C programming system. For example:built
main()
- The execution of every C program starts from this main() function.
printf()
- prinf() is used for displaying output in C.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
scanf()
- scanf() is used for taking input in C.
ii. User defined function
· C allows programmer to define their own function according to their requirement.
These types of functions are known as userreuser-defined functions.
· Example: Suppose, a programmer wants to find factorial of a number and check,
whether it is prime or not in same program. Then, he/she can create two separate user-user
defined functions in that program: one for finding factorial and other for checkingfactorial
whether it is prime or not.
Working of user-defined function in C Programmingdefined
· Every C program begins from main() and program starts executing the codes insidevery
main() function.
· When the control of program reaches to function_name() inside main() function. Thefunction_name()
control of program jumps to void function_name() and executes the codes inside it.
· When all the codes inside that user defined function are executed, control of the programuser-defined
jumps to the statement just after function_name() from where it is called.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
8. TYPES OF FUNCTIONS
For better understanding of arguments and return type in functions, user defined functionsuser-defined
can be categorized as:
1. Function with no arguments and no return values
2. Function with arguments but no return values
3. Function with arguments and return values
Passing arguments to functions
· In programming, argument(parameter) refers to data this is passed to
function(function definition) while calling function.
· In above example two variable, num1 and num2 are passed to function during
function call and these arguments are accepted by arguments a and b in function
definition.
· Arguments that are passed in function call and argument s that are accepted inarguments
function definition should have same data type. For example:
· If argument num1 was of int type and num2 was of float type then, argument
variable a should be of type int and b should be of type float,i.e., type of
argument during function call and function definition should be same.tion
· A function can be called with or without an argument.
· Calling a Function :
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
return 0;
}
void prime(){
/* There is no return value to calling function main(). Hence, return type of prime() is void */
int num,i,flag=0;
printf("Enter positive integer enter to check:\n");
scanf("%d",&num);
for(i=2;i<=num/2;++i){
if(num%i==0){
flag=1;
}
}
if (flag==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
}
Expected output
Enter positive integer enter to check 5
5 is prime
ii. Function With Arguments But No Return Values
· The function receives data from the calling function.
· The main() function will not have any control over the way the functions receive
input data.
· User can read data from the input terminal and pass it to the called function.
#include <stdio.h>
void prime(int);
int main(){
int n=5;
// printf("Enter positive integer enter to check:\n");
// scanf("%d",&n);
prime(n); //No argument is passed to prime().
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
return 0;
}
void prime(int n){
/* There is no return value to calling function main(). Hence, return type of prime() is void */
int num=n,i,flag=0;
for(i=2;i<=num/2;++i){
if(num%i==0){
flag=1;
}
}
if (flag==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
}
Expected output
Enter positive integer enter to check 5
5 is prime
9. FUNCTION PROTOTYPES
· Any C function returns n integer value by default.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· If a function should return a value other than an int, then it is necessary to mention the
calling function in the called function, which is called as the function prototype.
· Function prototype are usually written at the beginning of the program explicitly
before all user defined functions including the main() function. The syntax is :
return_type function_name(dt1 arg1, dt2 arg2, . . . dtn argn) ;
o Where return_type represents the data type of the value that is returned by
the function and dt1, dt2, . . . dtn represents the data type of the arguments
arg1, arg2, . . . argn.
o The data types of the actual arguments must confirm to the data types of
the arguments with the prototype. For example :
long fact(long num) ;
o Here fact is the name of the function, long before the function name fact
indicates that the function returns a value of type long. num inside the
parenthesis is the parameter passed to the called function. long before the
num indicates that it is of type long.
i. automatic
ii. external
iii. static
iv. register
Automatic storage class
Keyword for automatic variable is auto
· Variables declared inside the function body are automatic by default. These variable
are also known as local variables as they are local to the function and doesn't have
meaning outside that function
· Variable inside a function is automatic by default, keyword auto are rarely used.
· Example
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
void main()
{
auto mum = 20 ;
{
auto num = 60 ;
printf("nNum : %d",num);
}
printf("nNum : %d",num);
}
Output :
Num : 60
Num : 20
External storage class
· External variable can be accessed by any function. They are also known as global
declared in file 1 and that variable is used in file 2 then, compiler will show error.
· To solve this problem, keyword extern is used in file 2 to indicate that, the variable
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
printf("nNum : %d",num);
}
Output :
Num : 75
Num : 75
Register Storage Class
Keywords to declare register variable register
Example of register variable
register int a;
· Register variables are similar to automatic variable and exists inside that particular
function only.
· If the compiler encounters register variable, it tries to store variable in
program, variables that are used in loops and function parameters are declared register
variables.
· Since, there are limited number of register in processor and if it couldn't store the
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· During first function call, it will display 0. Then, during second function call, variable
0 0 0
11. RECURSION
· In C it is possible for the functions to call itself.
· Recursion is a process by which a function calls itself repeatedly until some specified
immediately, they are placed on a Stack (Last In First Out) until the condition that
terminates the recursive function.
· The function calls are then executed in reverse order as they are popped off the stack.
· Recursive functions can be effectively used in applications in which the solution to a
problem can be expressed in terms of successively applying the same solution to the
subsets of the problem.
· Simple example
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Infinite recursion occurs if the recursion step An infinite loop occurs with iteration if
does not reduce the problem in a manner that the loop-condition test never becomes
converges on some condition.(base case) false
Recursion terminates when a base case is Iteration terminates when the loop-
recognized condition fails
Recursion is usually slower then iteration due Iteration does not use stack so it's faster
to overhead of maintaining stack than recursion
Recursion uses more memory than iteration Iteration consume less memory
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Infinite recursion can crash the system infinite looping uses CPU
cycles repeatedly
12. POINTERS
· Pointer is a variable that holds a memory address, usually the location of another variable
in memory. The pointers are one of C’s most useful and strongest features.
· C Pointer is a variable that stores/points the address of another variable. C Pointer is used
to allocate memory dynamically i.e. at run time. The pointer variable might be belonging
to any of the data type such as int, float, char, double, short etc.
Syntax : data_type *var_name;
Example : int *p; char *p;
· Where, * is used to denote that “p” is pointer variable and not a normal variable.
· Here, p is the name of a variable that stores the value 10 and is stored in memory in the
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
just an address, if it is not initialized, it may randomly point to some location in memory.
· The ampersand (&) symbol, also called address operator, is applied to a variable to refer
The syntax is :
ptr_variable = &variable ;
· Here, the address of the variable is assigned to ptr_variable as its value.
· example :
ptr = &price ;
· Will cause ptr to point to price i.e., ptr now contain the address of price.
· A pointer variable can be initialized in its declaration itself.
For example :
int price, *ptr = &price ;
Is also valid.
ACCESSING A VARIABLE THROUGH ITS POINTER
· Accessing the value of the variable using pointer is done by using unary operator *
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
o Third line assigns the address of price to the pointer variable ptr.
o The fourth line contains the indirection operator *.
· When the operator * is placed before a pointer variable in an expression (on the right
hand side of the equal sign), the pointer returns the value of the variable of which the
pointer value is the address.
· *ptr returns the value of the variable price, because ptr is the address of price. The * can
#include<conio.h>
void main() {
int numArray[10];
int i, sum = 0;
int *ptr;
printf("\nEnter 10 elements : ");
for (i = 0; i < 10; i++)
scanf("%d", &numArray[i]);
ptr = numArray; /* a=&a[0] */
for (i = 0; i < 10; i++) {
sum = sum + *ptr;
ptr++;
}
printf("The sum of array elements : %d", sum);
}
Output:
Enter 10 elements : 11 12 13 14 15 16 17 18 19 20
The sum of array elements is 155
pointer variable can take different addresses as value whereas, in case of array it is fixed.
This can be demonstrated by an example:
#include <stdio.h>
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
int main(){
char c[4];
int i;
for(i=0;i<4;++i){
printf("Address of c[%d]=%x\n",i,&c[i]);
}
return 0;
}
Address of c[0]=28ff44
Address of c[1]=28ff45
Address of c[2]=28ff46
Address of c[3]=28ff47
· Notice, that there is equal difference (difference of 1 byte) between any two consecutive
elements of array.
Relation between Arrays and Pointers
· Consider an array:
int arr[4];
· In arrays of C programming, name of the array always points to the first element of an
array. Here, address of first element of an array is &arr[0]. Also, arr represents the
address of the pointer where it is pointing. Hence, &arr[0] is equivalent to arr.
· Also, value inside the address &arr[0] and address arr are equal. Value in address &arr[0]
is arr[0] and value in address arr is *arr. Hence, arr[0] is equivalent to *arr.
· Similarly,
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
//Program to find the sum of six numbers with arrays and pointers.
#include <stdio.h>
int main(){
int i,class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i){
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
return 0;
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum=21
of value.
Program to swap two number using call by reference.
/* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *a,int *b);
int main(){
int num1=5,num2=10;
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
o The address of memory location num1 and num2 are passed to function and the
pointers *a and *b accept those values. So, the pointer a and b points to address of
num1 and num2 respectively.
o When, the value of pointer are changed, the value in memory location also
changed correspondingly. Hence, change made to *a and *b was reflected in
num1 and num2 in main function.
o This technique is known as call by reference in C programming.
than required.
· Dynamic memory allocation allows a program to obtain more memory space, while
dynamically, there are 4 library functions under "stdlib.h" for dynamic memory
allocation.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
calloc() Allocates space for an array elements, initializes to zero and then returns a pointer
to memory
malloc()
· The name malloc stands for "memory allocation". The function malloc() reserves a block
of memory of specified size and return a pointer of type void which can be casted into
pointer of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
o Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area
of memory with size of byte size. If the space is insufficient, allocation fails and
returns NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
o This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.
calloc()
· The name calloc stands for "contiguous allocation". The only difference between malloc()
and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates
multiple blocks of memory each of same size and sets all bytes to zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
o This statement will allocate contiguous space in memory for an array of n
elements. For example:
ptr=(float*)calloc(25,sizeof(float));
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
}
A C program to find sum of n elements entered by user. To perform this program,
allocate memory dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
realloc()
· If the previously allocated memory is insufficient or more than sufficient. Then, you can
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
#include <stdlib.h>
int main(){
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
return 0;}
Source Code to Find Largest Element Using Dynamic Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main(){
int i,n;
float *data;
printf("Enter total number of elements(1 to 100): ");
scanf("%d",&n);
data=(float*)calloc(n,sizeof(float)); /* Allocates the memory for 'n' elements */
if(data==NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}
printf("\n");
for(i=0;i<n;++i) /* Stores number entered by user. */
{
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
UNIT V
1. STRUCTURE
· Structure is the collection of variables of different types under a single name for better
handling.
· Arrays allow defining type of variables that can hold several data items of the same kind but
structure allows combining data items of different kinds.
Structure Definition in C
Keyword struct is used for creating a structure.
Syntax of structure
struct structure_name
{
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
data_type member1;
data_type member2;
.
.
data_type memeber;
};
Example to create the structure for a person as mentioned above as:
struct person
{
char name[50];
int cit_no;
float salary;
};
This declaration above creates the derived data type struct person.
Structure variable declaration
When a structure is defined, it creates a user-defined type but, no storage is allocated. For
the above structure of person, variable can be declared as:
struct person
{
char name[50];
int cit_no;
float salary;
};
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
float salary;
}p1 ,p2 ,p[20];
In both cases, 2 variables p1, p2 and array p having 20 elements of type struct person
are created.
Accessing members of a structure
· There are two types of operators used for accessing members of a structure.
i. Member operator(.)
· Any member of a structure can be accessed as: structure_variable_name.member_name
· Suppose, we want to access salary for variable p2. Then, it can be accessed as:
p2.salary
· Example:
#include<stdio.h>
struct Vehicle
{
int wheels;
char vname[20];
char color[10];
}v1 = {4,"Nano","Red"};
int main()
{
printf("Vehicle No of Wheels : %d",v1.wheels);
printf("Vehicle Name : %s",v1.vname);
printf("Vehicle Color : %s",v1.color);
return(0);
}
Output :
Vehicle No of Wheels : 4
Vehicle Name : Nano
Vehicle Color : Red
ii. Structure pointer operator(->)
#include<stdio.h>
#include<malloc.h>
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
struct emp {
int eid;
char name[10];
}*ptr;
int main() {
int i;
printf("Enter the Employee Details : ");
ptr = (struct emp *) malloc(sizeof(struct emp));
printf("\nEnter the Employee ID : ");
scanf("%d", &ptr->eid);
printf("\nEnter the Employee Name : ");
scanf("%s", ptr->name);
printf("\nEmployee Details are : ");
printf("\nRoll Number : %d", ptr->eid);
printf("\nEmployee Name : %s", ptr->name);
return (0);
}
Output :
Enter the Employee Details :
Enter the Employee ID : 1
Enter the Employee Name : Pritesh
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
char sname[10];
int mar;
};
void main()
{ struct stu s[10];
int n,i;
clrscr();
printf("\n how many records");
scanf("%d",&n);
printf("\n enter the records");
for(i=0;i<n;i++)
scanf("%d%s%d",&s[i].stuno,s[i].sname,&s[i].mar);
printf("\n entered records are");
for(i=0;i<n;i++)
printf("\n %d\n %s\n %d",s[i].stuno,s[i].sname,s[i].mar);
getch();
}
Keyword typedef while using structure
· Programmer generally uses typedef while using structure in C language. For example:
typedef struct complex{
int imag;
float real;
}comp;
Inside main:
comp c1,c2;
· Here, typedef keyword is used in creating a type comp(which is of type as struct
complex). Then, two structure variables c1 and c2 are created by this comp type.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
int a;
float b;
};
int main(){
struct name *ptr,p;
ptr=&p; /* Referencing pointer to memory address of p */
printf("Enter integer: ");
scanf("%d",&(*ptr).a);
printf("Enter number: ");
scanf("%f",&(*ptr).b);
printf("Displaying: ");
printf("%d%f",(*ptr).a,(*ptr).b);
return 0;
}
· In this example, the pointer variable of type struct name is referenced to the address of p.
Then, only the structure member through pointer can can accessed.
· Structure pointer member can also be accessed using -> operator.
(*ptr).a is same as ptr->a
(*ptr).b is same as ptr->b
Accessing structure member through pointer using dynamic memory allocation
· To access structure member using pointers, memory can be allocated dynamically using
malloc() function defined under "stdlib.h" header file.
· Syntax to use malloc()
ptr=(cast-type*)malloc(byte-size)
Example to use structure's member through pointer using malloc() function.
#include <stdio.h>
#include<stdlib.h>
struct name {
int a;
float b;
char c[30];
};
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
int main(){
struct name *ptr;
int i,n;
printf("Enter n: ");
scanf("%d",&n);
ptr=(struct name*)malloc(n*sizeof(struct name));
/* Above statement allocates the memory for n structures with pointer ptr pointing to base
address */
for(i=0;i<n;++i){
printf("Enter string, integer and floating number respectively:\n");
scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b);
}
printf("Displaying Infromation:\n");
for(i=0;i<n;++i)
printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);
return 0;
}
Output
Enter n: 2
Enter string, integer and floating number respectively:
Programming
2
3.2
Enter string, integer and floating number respectively:
Structure
6
2.3
Displaying Information
Programming 2 3.20
Structure 6 2.30
In C, structure can be passed to functions by two methods:
· Passing by value (passing actual value as argument)
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Output
Name: Kevin Amla
Roll: 149
ii. Passing structure by reference
· The address location of structure variable is passed to function while passing it by
reference.
· If structure is passed by reference, change made in structure variable in function
definition reflects in original structure variable in the calling function.
· Example: C program to add two distances(feet-inch system) entered by user. To
solve this program, make a structure. Pass two structure variable (containing
distance in feet and inch) to add function by reference and display the result in
main function without returning it.
#include <stdio.h>
struct distance{
int feet;
float inch;
};
void Add(struct distance d1,struct distance d2, struct distance *d3);
int main()
{
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d",&dist1.feet);
printf("Enter inch: ");
scanf("%f",&dist1.inch);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d",&dist2.feet);
printf("Enter inch: ");
scanf("%f",&dist2.inch);
Add(dist1, dist2, &dist3);
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
/*passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by
reference */
printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch);
return 0;
}
void Add(struct distance d1,struct distance d2, struct distance *d3)
{
/* Adding distances d1 and d2 and storing it in d3 */
d3->feet=d1.feet+d2.feet;
d3->inch=d1.inch+d2.inch;
if (d3->inch>=12) { /* if inch is greater or equal to 12, converting it to feet. */
d3->inch-=12;
++d3->feet;
}
}
Output
First distance
Enter feet: 12
Enter inch: 6.8
Second distance
Enter feet: 5
Enter inch: 7.5
Sum of distances = 18'-2.3"
Explanation
· In this program, structure variables dist1 and dist2 are passed by value (because value of
dist1 and dist2 does not need to be displayed in main function) and dist3 is passed by
reference ,i.e, address of dist3 (&dist3) is passed as an argument.
· Thus, the structure pointer variable d3 points to the address of dist3. If any change is
made in d3 variable, effect of it is seed in dist3 variable in main function.
· Unions are quite similar to the structures in C. Union is also a derived type as structure.
Union can be defined in same manner as structures just the keyword used in defining
union in union where keyword used in defining structure was struct.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
union car{
char name[50];
int price;
};
Union variables can be created in similar manner as structure variable.
union car{
char name[50];
int price;
}c1, c2, *c3;
OR;
union car{
char name[50];
int price;
};
-------Inside Function-----------
union car c1, c2, *c3;
· In both cases, union variables c1, c2 and union pointer variable c3 of type union car is
created.
· Accessing members of an union
· The member of unions can be accessed in similar manner as that structure. Suppose, we
you want to access price for union variable c1 in above example, it can be accessed as
c1.price. If you want to access price for union pointer variable c3, it can be accessed as
(*c3).price or as c3->price.
Source Code to Store Information of 10 students Using Structure
#include <stdio.h>
struct student{
char name[50];
int roll;
float marks;
};
int main(){
struct student s[10];
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
int i;
printf("Enter information of students:\n");
for(i=0;i<10;++i)
{
s[i].roll=i+1;
printf("\nFor roll number %d\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}
printf("Displaying information of students:\n\n");
for(i=0;i<10;++i)
{
printf("\nInformation for roll number %d:\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
}
return 0;
}
Output
Enter information of students:
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
.
.
.
Displaying information of students:
2. Union
· C Union is also like structure, i.e. collection of different data types which are grouped
together. Each element in a union is called member.
· Union and structure in C are same in concepts, except allocating memory for their
members.
· Structure allocates storage space for all its members separately.
· Union allocates one common storage space for all its members
· One can access only one member of union at a time. We can’t access all member
values at the same time in union. But, structure can access all member values at the
same time. Union allocates one common storage space for all its members.
Whereas Structure allocates storage space for all its members separately.
· Many union variables can be created in a program and memory will be allocated for each
union variable separately.
· Below table will help you how to form a C union, declare a union, initializing and
accessing the members of the union.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Initializing union student report = {100, union student rep = {100, “Mani”,
union variable “Mani”, 99.5}; 99.5};report = &rep;
Structure Union
1.The keyword struct is used to define a 1. The keyword union is used to define a
structure union.
2. When a variable is associated with a 2. When a variable is associated with a union,
structure, the compiler allocates the memory the compiler allocates the memory by
for each member. The size of structure is considering the size of the largest memory. So,
greater than or equal to the sum of sizes of its size of union is equal to the size of largest
members. The smaller members may end with member.
unused slack bytes.
3. Each member within a structure is 3. Memory allocated is common for all
assigned unique storage area of location. members of union.
4. The address of each member will be in 4. The address is same for all the members of a
ascending order This indicates that memory for union. This indicates that every member begins
each member will start at different offset at the same offset value.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
values.
5 Altering the value of a member will not 5. Altering the value of any of the member will
affect other members of the structure. alter other member values.
6. Individual member can be accessed at a 6. Only one member can be accessed at a
time time.
7. Several members of a structure can 7. Only the first member of a union can be
initialize at once. initialized
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· But, the memory required to store a union variable is the memory required for largestut,
element of a union.
Example :structure and union :all members of structure can be accessed at any time. But, onlyall
one member of union can be accessed at a time in case of union and other members will contain
garbage value.
#include <stdio.h>
union job {
char name[32];
float salary;
int worker_no;
}u;
int main(){
printf("Enter name:\n");
scanf("%s",&u.name);
printf("Enter salary: \n");
scanf("%f",&u.salary);
printf("Displaying\nName :%s\n",u.name);n",u.name);
printf("Salary: %.1f",u.salary);
return 0;
}
Output
Enter name
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Hillary
Enter salary
1234.23
Displaying
Name: f%Bary
Salary: 1234.2
Note: You may get different garbage value of name.
· Initially, Hillary will be stored in u.name and other members of union will contain
garbage value. But when user enters value of salary, 1234.23 will be stored in u.salary
and other members will contain garbage value. Thus in output, salary is printed
accurately but, name displays some random string.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
enum boolean{
false;
true;
};
enum boolean check;
· Here, a variable check is declared which is of type enum boolean.
Example1 of enumerated type
#include <stdio.h>
enum week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main(){
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}
Output
4 day
Example2 of enumerated type
#include< stdio.h>
void main()
{
int i;
enum month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,DEC};
clrscr();
for(i=JAN;i<=DEC;i++)
printf("\n%d",i);
}
Output
01234567891011
4. File Management in C
In C programming, file is a place on disk where a group of related data is stored.
Importance of files .
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
When the program is terminated, the entire data is lost in C programming. If you want to
keep large volume of data, it is time consuming to enter the entire data. But, if file is created, this
information can be accessed using few commands.
There are large numbers of functions to handle file I/O in C language.
High level file I/O functions can be categorized as:
i. Text file
ii. Binary file
File Operations
i. Creating a new file
ii. Opening an existing file
iii. Reading from and writing information to a file
iv. Closing a file
Working with file
While working with file, you need to declare a pointer of type file. This declaration is
needed for communication between file and program.
FILE *ptr;
Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file
in standard I/O is:
ptr=fopen("fileopen","mode")
For Example:
fopen("E:\\cprogram\program.txt","w");
/* --------------------------------------------------------- */
E:\\cprogram\program.txt is the location to create file.
"w" represents the mode for writing.
/* --------------------------------------------------------- */
Here, the program.txt file is opened for writing mode.
r Open for reading. If the file does not exist, fopen() returns NULL.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Open for both reading and If the file exists, its contents are overwritten. If the file
w+
writing. does not exist, it will be created.
Closing a File: The file should be closed after reading/writing of a file. Closing a file is
performed using library function fclose().
fclose(ptr); //ptr is the file pointer associated with file to be closed.
The Functions fprintf() and fscanf() functions.
The functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only
difference while using fprintf() and fscanf() is that, the first argument is a pointer to the structure
FILE
Writing to a file
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}
Output:
· This program takes the number from user and stores in file.
· After compile and run this program, a text file program.txt created in C drive of the
computer. Similarly, fscanf() can be used to read data from file.
Reading from file
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}
If you have run program above to write in file successfully, you can get the integer back
entered in that program using this program.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
Binary Files
Depending upon the way file is opened for processing, a file is classified into text file and
binary file.
If a large amount of numerical data it to be stored, text mode will be insufficient. In such
case binary file is used.
Working of binary files is similar to text files with few differences in opening modes,
reading from file and writing to file.
Opening modes of binary files
Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+. The only difference
between opening modes of text and binary files is that, b is appended to indicate that, it is binary
file.
Reading and writing of a binary file.
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
Function fwrite() takes four arguments, address of data to be written in disk, size of data
to be written in disk, number of such type of data and pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Function fread() also take 4 arguments similar to fwrite() function as above.
The following example shows the usage of fread() and fwrite() functions.
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char c[] = "Welcome to FXEC";
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
char buffer[20];
/* Open file for both reading and writing */
fp = fopen("file.txt", "w+");
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· If we want to store data in a file into the secondary memory, we must specify certain
things about the file to the operating system. They include the fielname, data structure,
purpose.
· The general format of the function used for opening a file is
FILE *fp;
fp=fopen(“filename”,”mode”);
· The first statement declares the variable fp as a pointer to the data type FILE. As stated
earlier, File is a structure that is defined in the I/O Library. The second statement
opens the file named filename and assigns an identifier to the FILE type pointer fp.
This pointer, which contains all the information about the file, is subsequently used as
a communication link between the system and the program.
· The second statement also specifies the purpose of opening the file. The mode does
this job.
· In these statements the p1 and p2 are created and assigned to open the files data and
results respectively the file data is opened for reading and result is opened for writing.
· In case the results file already exists, its contents are deleted and the files are opened
as a new file. If data file does not exist error will occur.
Closing a file:
· The input output library supports the function to close a file; it is in the following
format.
fclose(file_pointer);
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· A file must be closed as soon as all operations on it have been completed. This would
….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
….
…
fclose(p1);
fclose(p2)
· The above program opens two files and closes them after all operations on them are
completed, once a file is closed its file pointer can be reversed on other file.
· The getc and putc functions are analogous to getchar and putchar functions and handle
one character at a time. The putc function writes the character contained in character
variable c to the file associated with the pointer fp1. ex putc(c,fp1); similarly getc
function is used to read a character from a file that has been open in read mode.
c=getc(fp2).
· The program shown below displays use of a file operations. The data enter through the
keyboard and the program writes it. Character by character, to the file input. The end
of the data is indicated by entering an EOF character, which is control-z. the file input
is closed at this signal.
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
printf(“\nData output\n”);
f1=fopen(“INPUT”,”r”); /*Reopen the file input*/
while((c=getc(f1))!=EOF)
printf(“%c”,c);
fclose(f1);
}
The getw and putw functions:
· These are integer-oriented functions. They are similar to get c and putc functions and
are used to read and write integer values. These functions would be usefull when we
deal with only integer data. The general forms of getw and putw are:
putw(integer,fp);
getw(fp);
/*Example program for using getw and putw functions*/
#include< stdio.h >
main()
{
FILE *f1,*f2,*f3;
int number I;
printf(“Contents of the data file\n\n”);
f1=fopen(“DATA”,”W”);
for(I=1;I< 30;I++)
{
scanf(“%d”,&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen(“DATA”,”r”);
f2=fopen(“ODD”,”w”);
f3=fopen(“EVEN”,”w”);
while((number=getw(f1))!=EOF)/* Read from data file*/
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
{
if(number%2==0)
putw(number,f3);/*Write to even file*/
else
putw(number,f2);/*write to odd file*/
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“\n\nContents of the odd file\n\n”);
while(number=getw(f2))!=EOF)
printf(“%d%d”,number);
printf(“\n\nContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
}
6. File access:
One can access the data stored in the file in two ways.
· Sequentially: Data accessed serially. To access the forty fourth record then first forty
three records read one after the other to reach forty four records.
· Randomly: In random access, data can be accessed and processed directly. There is no
need to read each record sequentially. To access a particular record random access takes
less time than the sequential access.
Random access to files:
· Random access means we can move to any part of a file and read or write data from it
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
fseek( ) Function
ftell ( ) Function
i. fseek function:
· This function is used for setting the file position pointer at the specified bytes. fseek is a
function belonging to the ANCI C standard Library and included in the file stdio.h.
· Its purpose is to change the file position indicator for the specified stream.
Argument meaning:
o stream_pointer is a pointer to the stream FILE structure of which the
position indicator should be changed;
o offset is a long integer which specifies the number of bytes from origin
where the position indicator should be placed;
o origin is an integer which specifies the origin position. It can be:
Constant Description
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Parameters
· stream -- This is the pointer to a FILE object that identifies the stream.
Return Value
· This function returns the current value of the position indicator. If an error occurs, -1L is
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
This is tutorialspoint.com
Output
Total size of file.txt = 27 bytes
ii. The rewind() Function
· The rewind() function can be used in sequential or random access C file programming, and
simply tells the file system to position the file pointer at the start of the file. Any error flags
will also be cleared, and no value is returned.
Description
The C library function void rewind(FILE *stream) sets the file position to the beginning of the
file of the given stream.
Declaration
Following is the declaration for rewind() function.
void rewind(FILE *stream)
Parameters
stream -- This is the pointer to a FILE object that identifies the stream.
Return Value
This function does not return any value.
Example
#include <stdio.h>
int main()
{
char str[] = "This is tutorialspoint.com";
FILE *fp;
int ch;
/* First let's write some content in the file */
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
fseek() - It is used to moves the reading control to different positions using fseek function.
ftell() - It tells the byte location of current position in file pointer.
rewind() - It moves the control to beginning of a file.
Program
1
#include
2
void main(){
3 FILE *fp;
4 int i;
5 clrscr();
6 fp = fopen("CHAR.txt","r");
7 for (i=1;i<=10;i++){
8 printf("%c : %d\n",getc(fp),ftell(fp));
fseek(fp,ftell(fp),0);
9
if (i == 5)
10
rewind(fp);
11
}
12
fclose(fp);
13
}
14
Output
W : 0
e : 1
l : 2
c : 3
o : 4
W : 0
e : 1
l : 2
c : 3
o:4
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
· It is possible to pass some values from the command line to the C programs when they are
executed. These values are called command line arguments and many times they are
important for the c program.
· The command line arguments are handled using main() function arguments where argc
refers to the number of arguments passed, and argv[] is a pointer array which points to each
argument passed to the program.
· main() function of a C program accepts arguments from command line or from other shell
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Enter
} marks of student 0 for subject 0 : 90
Enter
printf("\nTotal
marks of student
marks
0 for
obtained
subjectby1 student
: 89 %s are %dn", st[i].name,total);
Enter
a[i]
marks
= total;
of student 0 for subject 2 : 78
Enter
} marks of student 1 for subject 0 : 67
/* (ii) for loop toEnter
list out
marks
the student's
of student
roll
1 for
numbers
subject
who1 : have
88 secured the highest marks in each
subject */ Enter marks of student 1 for subject 2 : 99
Total
/* roll
marks
number
obtained
who by
secured
student
thePritesh
highestare
marks
257 */
Total
for (jmarks
= 0; jobtained
< 3; j++)by{ student Suraj are 254
Student
maxPritesh
= 0; got maximum marks = 90 in Subject : 0
Student
for (iPritesh
= 0; i <
gotn;maximum
i++) { marks = 89 in Subject : 1
Student
if Suraj
(max <gotst[i].sub[j])
maximum{marks = 99 in Subject : 2
Pritesh obtained
max = st[i].sub[j];
the total highest marks.
ni = i;
}
}
printf("\nStudent %s got maximum marks = %d in Subject : %d",st[ni].name,
max, j);
}
max = 0;
for (i = 0; i < n; i++) {
if (max < a[i]) {
max = a[i];
ni = i;
}
}
printf("\n%s obtained the total highest marks.", st[ni].name);
getch();
}
http:\\www.francisxavier.ac.in
www.Vidyarthiplus.com