Chapter - 1 Problem Solving Using Computer: Computer Programming in C
Chapter - 1 Problem Solving Using Computer: Computer Programming in C
Chapter – 1
Problem Solving using Computer
What is a problem?
Problem is defined as the difference between an existing situation and a desired
situation, that is, in accordance with calculation; a problem is numerical situation and has
complex form. Solution is desired situation and has simplest form. If a problem is solved by
computing using machine called computer, then such process is called Problem Solving using
Computer.
Suppose you are asked by your father to solve an arithmetic problem and you are not
familiar with the steps involved in solving that problem. In such a situation, you will not be
able to solve the problem. The same principle applies to writing computer program also. A
programmer cannot write the instruction to be followed by a computer unless the programmer
knows how to solve the problem manually.
Suppose you know the steps to be followed for solving the given problem but while
solving the problem you forget to apply some steps or you apply the calculation steps in the
wrong sequences. Obviously, you will get a wrong answer. Similarly, while writing a
computer program, if the programmer leaves out some of the instructions for the computer or
writes the instructions in the wrong sequences, then the computer will calculate a wrong
answer. Thus to produce an effective computer program, it is necessary that the programmers
write each and every instruction in the proper sequence. However, the instruction sequence
(logic) of a computer program can be very complex. Hence, in order to ensure that the
program instructions are appropriate for the problem and are in correct sequence, program
must be planned before they are written.
Problem:
There are 50 students in a class who appeared in their final examination. Their mark
sheets have been given to you. Write an algorithm to calculate and print the total number of
students who passed in first division.
Algorithm:
Step 1: Initialize Total First Division and Total Mark sheet checked to zero
i.e. total_first_div = 0;
total_marksheet_chkd = 0;
Step 2: Take the mark sheet of the next student.
Step 3: Check the division column of the mark sheet to see if it is I: if no, go to step 5.
Step 4: Add 1 to Total First Division i.e.
total_first_div +1;
Step 5: Add 1 to Total Mark sheets checked
i.e. total_marksheet_chkd +1;
Step 6: Is Total Mark sheets checked = 50: if no go to step
2 Step 7: Print Total First Division.
Step 8: Stop (End)
The above mentioned example is simpler one but development of an algorithm of a complex
problem is very difficult. It may also be noted that in order to solve a given problem, each and
every instruction must be strictly carried out in a particular sequence.
Flowchart:
A flowchart is a pictorial representation of an algorithm that uses boxes of different
shapes to denote different types of instructions. The actual instructions are written within
these boxes using clear and concise statements. These boxes are connected by solid lines
having arrow marks to indicate the flow of operation, that is, the exact sequence in which the
instructions are to be executed.
Normally, an algorithm is first represented in the form of a flowchart and the flowchart
is then expressed in some programming language to prepare a computer program. The main
advantage of this two steps approach in program writing is that while drawing a flowchart
one is not concerned with the details of the elements of programming language. Since a
flowchart shows the flow of operations in pictorial form, any error in the logic of the
procedure can be detected more easily than in the case of a program. Once the flowchart is
ready, the programmer can forget about the logic and can concentrate only on coding the
operations in each box of the flowchart in terms of the statements of the programming
language. This will normally ensure an error-free program.
Flowchart Symbols:
A flowchart uses boxes of different shapes to denote different types of instructions. The
communication of program logic through flowcharts is made easier through the use of
symbols that have standardized meanings. For example, a diamond always means a decision.
Only a few symbols are needed to indicate the necessary operations in a flowchart. These
symbols are standardized by the American National Standard Institute (ANSI). These
symbols are listed below:
Terminal
Input/Output Processing
Terminal: The terminal symbol, as the name implies is used to indicate the beginning
(START), ending (STOP) and pauses (HALT) in the program logic flow. It is the first symbol
and last symbol in the program logic. In addition, pause (HALT) used with a terminal symbol
in program logic in order to represent some error condition.
Flowlines: Flowlines with arrowheads are used to indicate the flow of operations, that is, the
exact sequence in which the instructions are to be executed. The normal flow of flowchart is
from top to bottom and left to right. Arrowheads are required only when the normal top to
bottom flow is not to be followed. However, as a good practice and in order to avoid
ambiguity, flowlines are usually drawn with an arrowhead at the point of entry to a symbol.
Good practice also dictates that flowlines should not cross each other and that such
intersections should be avoided whenever possible.
Decision: The decision symbol is used in a flowchart to indicate a point at which a decision
has to be made and a branch to one of two or more alternative points is possible. The criteria
for making the decision should be indicated clearly within the decision box.
Connector: If a flowchart becomes very long, the flowlines start criss-cross at many places
that causes confusion and reduces understandability of the flowchart. Whenever a flowchart
becomes complex enough that the number and direction of flowlines is confusing or it
spreads over more than one page, it is useful to utilize the connector symbol as a substitute
for flowlines.
Problem:
A student appears in an examination that consists of total 10 subjects, each subject
having maximum marks of 100. The roll number of the students, his name, and the marks
obtained by him in various subjects is supplied as input data. Such collection of related data
items that is treated as a unit is known as a record. Draw a flowchart for the algorithm to
calculate the percentage marks obtained by the student in this examination and then to print it
along with his roll number and name.
START
READ INPUT
DATA
ADD MARKS OF
ALL SUBJECTS
GIVING TOTAL
PERCENTAGE =
TOTAL/10
WRITE
OUTPUT DATA
STOP
Fig : Flowchart
1.3 Coding:
In order to make a program in any programming language, what we have written is
known as code. The act of writing code in a computer language is known as coding. In other
words, code is a set of instruction that a computer can understand.
1.4 Compilation & Execution:
The process by which source codes of a computer (programming) language are
translated into machine codes is known as compilation. After compilation if everything is ok,
the code is going under other process that is known as execution. We can get the required
output after execution process.
Testing is the process of reviewing and executing a program with the intent of detecting
errors. Testing can be done manually and computer based testing.
Manual Testing is an effecting error-detection process and is done before the computer
based testing begins. Manual testing includes code inspection by the programmer, code
inspection by a test group and a review by a peer group. Computer based testing is done by
computer with the help of compiler (a program that changes source codes into machine codes
word by word).
Some details may be built-in as an integral part of the program. These are known as internal
documentation. Two important aspects of internal documentation are; selection of meaningful
variable names and the use of comments. Selection of meaningful names is crucial for
understanding the program. For example,
Area = Breadth * Length;
is more meaningful than
A=B*L
And comments are used to describe actions parts and identification in a program. For
example,
/ * include file * / describes parts of program
/* header file * / describes parts of program.
Chapter – 2
Introduction to C
C was used mainly in academic environments for many years, but eventually with the
release of C compiler for commercial use and the increasing popularity of UNIX, it began to
gain widespread support among compiler professionals. Today, C is running under a number
of operating systems including Ms-DOS. C was now standardized by American National
Standard Institute. Such type of C was named ANSI C.
2.2 Importance of C:
Programs written in C are efficient and fast. This is due to its variety of data types and
powerful operators. It is many times faster than BASIC (Beginners All Purpose Symbolic
Instruction Code – a high level programming language).
There are only 32 keywords and its strength lies in its built-in functions. Several
standard functions are available which can be used for developing programs. C is highly
portable. This means that C programs written for one computer can be seen on another with
little or no modification. Portability is important if we plan to use a new computer with a
different operating system.
C Language is well suited for structure programming thus requiring the user to think of
a problem in terms of function modules or blocks. A proper collection of these modules
would make a complete program. This modular structure makes program debugging, testing
and maintenance.
Every C program consists one or more modules called function. One of the function
must be called main( ).A function is a sub-routine that may include one or more statements
designed to perform a specific task. A C program may contain one or more sections shown in
fig:
Documentation Section
Link Section
Global Declaration Section
Main() Function Section
{
Declaration Part
Execution Part
}
Subprogram Section
Function 1
Function 2
(User-defined Functions)
Function n
Fig : Basic Structure of a C program
The documentation section consists of a set of comment lines giving the name of the
program, the author and other details which the programmer would like to use later. The link
section provides instructions to the compiler to link function from the system library. The
definition defines all the symbolic constants. There are some variables that are used in more
than one function. Such variables are called global variables and are declared in global
declaration section that is outside of all the function.
Every C program must have one main( ) function section. This section consists two
parts: declaration part and executable part. The declaration part declares all the variables used
in the executable part. These two parts must appear between the opening and the closing
braces. The program execution begins at the opening braces and ends at the closing brace.
The closing brace of the main ( ) function section is the logical end of the program. All the
statements in the declaration and executable parts ends with a semicolon.
The subprogram section contains all the user-defined functions that are called in the
main ( ) function. User-defined functions are generally placed immediately after the main ( )
function, although they may appear in any order. All section, except the main ( ) function
section may be absent when they are not required.
Written by Er. Arun Kumar Yadav, Lecturer, Eastern College of Engineering Biratnagar
2.4 Executing a C Program
Executing a program written in C involves a series of steps:
1. Creating the program;
2. Compiling the program;
3. Linking the program with functions that are needed from the C library; and
4. Executing the program.
The program can be created using any word processing software in non-document
mode. The file name should end with the characters “.c” like program .c, lab1.c, etc. Then the
command under Ms DOS operating system would load the program stored in the file program
.c i.e.
MSC pay .C
and generate the object code. This code is stored in another file under name ‘program.obj’. In
case any language errors are found , the compilation is not completed. The program should
then be corrected and compiled again.
The linking is done by the command
LINK program.obj
which generates the executable code with the filename program.exe. Now the command
.program
would execute the program and give the results.
1.
2.Write down the importance of C.(PU2004)
3. ow can you define the structure of C -program? Explain with general form.(PU2003)
Chapter – 3
C Fundamentals
C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and
certain special characters as building blocks to form basic program elements (e.g. constants,
variables, operators, expressions, etc). The special characters are listed below:
+ - * / = % & # ! ? ^ “ ' ~ \ | < > ( ) [ ] { } : ; . , - (Blank space) (Horizontal tab)
(White Space)
Most versions of the language also allow certain other characters, such as @ and $ to be
included with strings & comments.
Identifiers:
Identifiers are names that are given to various program elements, such as variables,
functions and arrays. Identifiers consisted of letters and digits, in any order, except that first
character must be a letter. Both upper and lower case letters are permitted, though common
usage favors the use of lowercase letters for most type of identifiers. Upper and lowercase
letters are not interchangeable (i.e. an uppercase letter is not equivalent to the corresponding
lowercase letters). The underscore ( _ ) can also be included, and considered to be a letter. An
underscore is often used in middle of an identifier. An identifier may also begin with an
underscore.
The following names are not valid identifier for the reason stated
4th The first character must be letter
“x” Illegal characters (“)
Order-no Illegal character (-)
Error flag Illegal character (blank space)
Keywords:
There are certain reserved words, called keywords that have standard, predefined
meanings in C. These keywords can be used only for their intended purpose; they cannot be
used as programmer-defined identifiers. The standard keywords are
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
The keywords are all lowercase. Since upper and lowercase characters are not
equivalent, it is possible to utilize an uppercase keyword as an identifier. Normally, however,
this is not done, as it is considered a poor programming practice.
C language is rich in its data types. C supports several different types of data, each of
which may be represented differently within the computer memory. There are three cases of
data types:
1. Basic data types (Primary or Fundamental) e.g.: int, char
2. Derived data types e.g.: array, pointer, function
3. User defined data types e.g.: structure, union, enum
The basic data types are also known as built in data types. The basic data types are
listed below. Typical memory requirements are also given:
Data Types Description Typical Memory Requirement
char single character 1 byte
int integer quantity 2 bytes
float floating-point number 4 bytes (1 word)
double double-precision floating point number 8 bytes (2 word)
In order to provide some control over the range of numbers and storage space, C has
following classes: signed, unsigned, short, long.
Types Size
char or signed char 1 byte
unsigned char 1 byte
int 2 bytes
short int 1 byte
unsigned short int 1 byte
signed int 2 bytes
unsigned int 2 bytes
long int 4 bytes
signed long int 4 bytes
unsigned long int 4 bytes
float 4 bytes
double 8 bytes
long double 10 bytes
void is also a built-in data type used to specify the type of function. The void type has
no values.
Er. Arun Kumar Yadav, 14
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
Constants in C refer to fixed values that do not change during the execution of a
program. There are four basic types of constants in C. They are integer constants, floating
point constants, character constants and string constants.
Integer and floating point constants represent numbers. They are often referred to
collectively as numeric _ type constants. The following rules apply to all numeric type
constants.
Integer Constants:
A decimal integer constant can consists of any combination of digits taken from the set
0 through 9. If the constant contains two or more digits, the first digit must be something
other than 0. Several valid decimal integer constants are shown below:
0 1 143 5280 12345 9999
The following decimal integer constants are written incorrectly for reason stated:
12,452 Illegal character (,)
36.0 Illegal character (.)
10 20 30 Illegal character (blank space )
123-45-6743 Illegal character (-)
0900 the first digit cannot be zero.
An octal integer constant can consist of any combination of digits taken from the set 0
through 7. However, the first digit must be 0, in order to identify the constant as an octal
number.
Valid octal number (integer) constants are shown below:
0 01 0743 07777
The following octal integer constants are written incorrectly for the reason stated:
743 Does not begin with 0.
05280 Illegal character (8)
777.777 Illegal character (.)
A hexadecimal integer constant must begin with either 0x or 0X. It can then be followed
by any combination of digits taken from the sets 0 through 9 and a through f (either upper or
lower case). The letters a through f (or A through F) represent the (decimal) quantities 10
through 15 respectively. Several valid hexadecimal integer constants are shown below:
0x 0X1 0X7FFF 0xabcd
The following hexadecimal integer constants are written incorrectly for the reason
stated:
0X12.34 Illegal character (.)
013E38 Doesn’t begin with 0x or 0X.
0x.4bff Illegal character (.)
0XDEFG Illegal character(G)
Unsigned integer constants may exceed the magnitude of ordinary integer constants by
approximately a factor of l, though they may not be negative. An unsigned integer constant
can be identified by appending the letter ( ) (either upper or lowercase) to the end of the
constant.
Long integer constants may exceed the magnitude of ordinary integer constants, but
require more memory within the computer. A long integer constant can be identified by
appending the letter L (either upper or lowercase) to the end of the constant.
An unsigned long integer may be specified by appending the letters UL to the end of the
constant. The letters may be written in either upper or lowercase. However, the U must
preced the L.
A floating point constant is a base 10 number that contains either a decimal point or an
exponent (or both).
The following are not valid floating point constants for the reason stated.
1 Either a decimal point or an exponent must be present.
1,000.0 Illegal character (,)
2E+10.2 The exponent must be an integer (it cannot contain a decimal
point)
3E 10 Illegal character (blank space) in the exponent.
5
The quantity 3×10 can be represented in C by any of the following floating point
constants:
300000. 3e5 3e+5 3E5 3.0e+5
.3e5 0.3E6 30E4 30.E4 300e3
Character Constants:
A character constant is a single character, enclosed in apostrophes (i.e. single quotation
marks).
Several character constants are shown
below: ‘A’ ‘X’ ‘3’ ‘?’ ‘ ´
Character constants have integer values that are determined by the computer’s particular
character set. Thus, the value of a character constant may vary from one computer to another.
The constants themselves, however, are independent of the character set. This feature
eliminates the dependence of a C program on a particular character set.
Most computers, and virtually all personal computer make use of ASCII (i.e. American
Standard Code for Information Interchange) character set, in which each individual character
7
is numerically encoded with its own unique 7-bit combination (hence a total of 2 =128
difference characters).
Constant Value
‘A’ 65
‘X’ 120
‘3’ 51
‘?’ 63
‘’ 32
These values will be the same for all computer that utilize the ASCII character
The string constants “Line 1\n Line 2\n Line 3” extends over three lines, because of the
newline characters that are embedded within the string. Thus, the string would be displayed
as
Line 1
Line 2
Line 3
The compiler automatically places a null character (\0) at the end of every string
constant, as the last character within the string (before the closing double quotation mark).
This character is not visible when the string is displayed.
A character constant (e.g. ‘A’) and the corresponding single-character string constant
(“A’) are not equivalent. A character constant has an equivalent integer value, whereas a
single character string constant does not have an equivalent integer value and in fact, consists
of two characters – the specified character followed by the null character (\o).
Variables:
char d ;
-----
-----
a=3;
b=5;
c=a+b;
d = ‘a’ ;
-----
-----
a=4;
b=2;
c=a–b;
d= ‘w’
The first two lines are not type declaration which state that a, b and c are integer
variables, and that d is a character type. Thus, a, b and c will each represent an integer-valued
quantity, and d will represent a single character. The type declaration will apply throughout
the program.
The next four lines cause the following things to happen: the integer quantity 3 is
assigned to a, 5 is assigned to b and the quantity represented by the sum a+b (.e. 8) is
assigned to c. The character ‘a’ is assigned then assigned to d.
In the third line within this group, the values of the variables a and b are accessed
simply by writing the variables on the right-hand side of the equal sign.
The last four lines redefine the values assigned to the variables as the integer quantity 4
is assigned to a, replacing the earlier value, 3; then 2 is assigned to b, replacing the earlier
value, 5; The difference between a and b (i.e. 2) is assigned to c, replacing the earlier value 8.
Finally the character ‘w’ is assigned to d, replacing the earlier character, ‘a’.
3.5 Declarations
A declaration associates a group of variables with a specific data type. All variables
must be declared before they can appear in executable statements.
A declaration consists of a data type, followed by one or more variable names, ending
with a semicolon. Each array variable must be followed by a pair of square brackets,
containing a positive integer which specifies the size (i.e. the number of elements) of the
array.
Thus, a, b and c are declared to be integer variables, root1 and root 2 are floating
variables, flag is a char-type variable and text is an 80-element, char-type array. Square
brackets enclosing the size specification for text.
Also written as
short a, b, c ;
long r, s, t ;
int p, q ;
short and short int are equivalent, as are long and long int.
Thus, c is an integer variable whose initial value is 12, star is a char type variable
initially assigned the character ‘*’, sum is a floating point variable whose initial value is 0. ,
6
and factor is double precision variable whose initial value is 0.21023 × 10 .
This declaration will cause text to be an 11-element character array. The first 10
th
elements will represent the 10 characters within the word California, and the 11 element
will represent the null character (\0) which automatically added at the end of the string.
c a l i f o r n i a \0
Subscript: 0 1 2 3 4 5 6 7 8 9 10
Certain nonprinting character, as well as the backslash (\) and apostrophe (`), can be
expressed in terms of escape sequences. An escape sequence always begins with a backslash
and is followed by one or more special characters. For example, a linefeed (LF), which is
Escape Sequence ‘\0’ represents the null character (ASCII 000), which is used to
indicate the end of a string. The null character constant ‘\0’ is not equivalent to the character
constant ‘0’.
The general form ‘\000’ represents an octal digit (0 through 7). The general form of a
hexadecimal escape sequence is \xhh, where each h represents a hexadecimal digit (0 through
9 and a through f).
Directives Functions
#define Defines a macro substitution
Er. Arun Kumar Yadav, 22
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
C supports a feature known as “type definition” that allows users to define an identifier
that would represent an existing data type. The user-defined data type identifier can later be
used to declare variables. It takes the general form:
typedef type identifier ;
where type refers to an existing data type and identifier refers to the “new” name given to the
data type. The existing data type may belong to any class of type, including the user defined
ones. The new type is new only in name, but not the data type. typedef cannot create a new
type. Some examples of type definition are:
typedef int units ;
typedef float marks ;
where, units represent int and marks represents float. They can be later used to declare
variables as follows:
units batch1, batch2 ;
marks name1 [50] , name2[50] ;
batch1 and batch2 are declared as int variable and name1[50] and namer[50] are
declared as 50 element floating point array variables. The main advantage of typedef is that
we can create meaningful data type names for increasing the readability of the program.
3.9 Symbolic Constants:
Symbolic constants are usually defined at the beginning of a program. The symbolic
constants may then appear later in the program in place of the numeric constants, character
constant, etc that the symbolic constants represent.
Chapter – 4
Operators & Expressions
Individual constants, variables, array elements and function references can be joined
together by various operators to form expression. C includes a number of operators which fall
into several different categories such as arithmetic operators, unary operators, rational and
logical operators, assignment operators and the conditional operators, bitwise operator.
The data items that operators act upon are called operands. Some operators require two
operands, while other act upon only one operand. Most operators allow the individual
operands to be expressions. A few operators permit only single variable as operand.
4.1 Operators
Arithmetic Operators:
There are five arithmetic operators in C. They are
Operators Purposes
+ Addition
- Subtraction
* Multiplication
/ Division
% remainder after integer division (also called modulus operator)
The operands acted upon by arithmetic operators must represent numeric values. The
remainder operator (%) requires that both operands be integers and the second operand be
non zero. Similarly, the division operator (/) requires that the second operand be non-zero.
carried out before operation having a lower precedence. The natural order of evaluation can
be altered using parenthesis.
Associativity:
The order, in which consecutive operations within the same precedence group are
carried out, is known as associativity. Within each of the precedence groups described above,
the associativity is left to right. In other word, consecutive addition and subtraction operations
are carried out from left to right, as are consecutive multiplication, division and remainder
operations.
# a = 10, b = 3
Expression Value
a+b 13
a-b 7
a*b 30
a/b 3
a%b 1
# Determine the hierarchy of operations and evaluate the following expressions, assuming
that i is an integer variables:
i = 2*3/4+4/4+8-2+5/8
# Determine the hierarch of operations and evaluate the following expression, assuming that
k is a float integer variable.
k = 3/2*4+3/8+3
Solution: Stepwise
k = 3/2*4+3/8+3
= 1*4+3/8+3 Operation : /
= 4+3/8+3 Operation : *
= 4+0+3 Operation : /
= 4+3 Operation : +
=7 Operation : +
Operators Meaning
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== Equality equal to
!= Operators not equal to
These operators all fall within the same precedence group, which is lower than the
arithmetic and unary operators. The associativity of these operators is left to right.
# Suppose that i, j and k are integer variables whose values are 1, 2 and 3 respectively.
Several relational expressions involving these variables:
Expressions Interpretation Value
i<j true 1
(i+j) >= k true 1
(j+k) > (i+5) false 0
k! = 3 false 0
j==2 true 1
Er. Arun Kumar Yadav, 28
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
In addition to the relational and equality operators, C also includes the unary operator !
that negates the value of a logical expression, i.e. it causes an expression that is originally true
to become false and vice-versa. This operator is referred to as the logical negative (or logical
not) operator.
Logical operators:
Logical operators are used to compare & evaluate logical and relational expressions.
Operator && is referred as logic and, the operator || is referred as logic or.
The result of a logic and operation will be true only if both operands are true where as
the result of a logic or operation will be true if either operand is true or if both operands are
true. In other word, the result of a logic or operation will be false only if both operands are
false.
Assignment Operators:
There are several different assignment operators in C. All of them are used to form
assignment expressions which assign the value of an expression to an identifier.
The most commonly used assignment operator is =. Assignment expressions that make
use of the operator are written in the form
identifier = expression
where identifier generally represents a variable, and expression represents a constant, a
variable or more complex expression.
# Here are some typical assignment expressions that make use of the = operator.
a=3
x=y
delta = 0.001
sum = a+b
area = length * width
Unary Operators:
C includes a class of operators that act upon a single operand to produce a new value,
Such operators known as unary operators. Unary operators usually precede their single
operands, though some unary operators are written after their operands.The common use
unary operators in C are:
1. Increment Operator (+ +)
2. Decrement Operator (- -
) 3.Unary minus(-)
4.unary plus(+)
The increment operator causes its operand to be increased by 1 where as the decrement
operator causes its operand to be decreased by 1. The operand used with each of these
operators must be a single variable.
Unary expression Equivalent expression
++ variable or (variable ++) variable = variable +1
-- variable or (variable _ _) variable = variable -1
The increment or decrement operators can each be utilized two different ways,
depending on whether the operator is written before or after. If the operator is written before
the operand then it is called as prefix unary operator. If the operator is written after the
operand, then it is called as postfix unary operator. When prefix is used, the operand will be
altered in value before it is utilized for its intended purpose within the program. Similarly,
when postfix is used, the operand will be altered in value after it is utilized.
The most common use unary operator is unary minus, where a numeric constant,
variable expression is preced by a minus sign.Unary minus is distinctly difference from the
arithmetic operator which denotes subtraction (-).The subtractor operator requires two
separate operands .Several examples of unary minus are
-743 -0x7fff -0.2 -5E-8 -root1 -(x+y) -3*(x+y)
In C, all numeric constants and variable are considered as positive. So, unary plus is not
written as unary minus such as
+743 = 743
+(x+y) = x+y
The precedence of unary increment or decrement or unary minus or plus is same and
associativity is right to left.
Bitwise Operators:
Bitwise Operators are used for manipulating data at bit level. These operators are used
for testing the bits, or shifting them right or left. Bitwise operators can be applied only to
integer type signed or unsigned) and not to float or double. They are
Er. Arun Kumar Yadav, 32
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Left shift
>> Right shift
~ Bitwise one’s complement operator
C supports some special operators such as comma operator, size of operator, pointer
operator (* and &) and member selection operators. (.and )
Comma Operator:
The comma operator can be used to link the related expression together. A comma
linked list of expression are evaluated left to right and the value of right-most expression is
the value of combined expression. For example,
Size of Operator:
The size of operator is used with an operand to return the number of bytes it occupies. It
is a compile time operand. The operand may be a variable, a constant or a data type qualifier.
The associativity of size of right to left. For e.g.
# Suppose that i is an integer variable, x is a floating-point variable, d is double-precision
variable and c is character type variable.
The statements:
printf (“integer : %d \n”, size of i) ;
printf (“float : %d \n”, size of x) ;
printf (“double : %d \n”, size of d) ;
printf (“character : %d \n”, size of c) ;
Conditional Operators:
The operator ?: is known as conditional operator. Simple conditional operations can be
carried out with conditional operator. An expression that make use of the conditional operator
is called a conditional expression. Such an expression can be written in place of traditional if-
else statement.
In this example, x will be assigned the value of b. This can be achieved by using the
if_else statement as follows:
if (a<b)
x=a;
else
x=b;
Summary of C operators:
>> Rightshift
< Less than Left ->Right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equality Left ->Right 7
!= Inequality
& Bitwise AND Left ->Right 8
^ Bitwise XOR Left ->Right 9
| Bitwise XOR Left ->Right 10
&& Logic AND Left ->Right 11
|| Logic OR Left -> Right 12
?: Conditional operator Right -> Left 13
= Assignment operators Right -> Left 14
+=
-=
*=
/=
%=
, Comma operator Left -> Right 15
1. Write the general form of ternary operator and explain with example. (PU2003)
2. What is a datatype? Write down the various types of it in C-program. (PU2003Back)
3. What are the various types of operators used in C language? Give a table that shows their
precedence and associatively. (PU2005)
4. Define the data types. Describe different data types. (PU2005Back)
5. Write a program to enter two numbers. Make the" comparison between them with
conditional operator. If the first number is greater than second, perform multiplication
otherwise division
6. What are operators? Describe unary, binary and ternary operators with examples.
Chapter – 5
Input and Output Operations
A program is a set of instructions that takes some data and provides some data after
execution. The data that is given to a program is known as input data. Similarly, the data that
is provided by a program is known as output data. Generally, input data is given to a program
from a keyboard (a standard input device) or a file. The program then proceeds the input data
and the result is displayed on the screen (monitor – a standard output device) or a file.
Reading input data from keyboard and displaying the output data on screen, such input output
system is considered as conio input out.
To perform input/output operation in console mode, C has a number of input and output
functions. When a program needs data, it takes the data through the input functions and sends
the results to output devices through the output functions. Thus the input/output functions are
the link between the user and the terminal.
As keyboard is a standard input device, the input functions used to read data from
keyboard are called standard input functions. The standard input functions are scanf( ),
getchas( ), getch( ), gets( ), etc. Similarly, the output functions which are used to display the
result on the screen are called standard output functions. The standard output functions are
printf( ), putchas( ), putch( ), puts( ), etc. The standard library stdio.h provides functions for
input and output. The instruction #include<stdio.h> tells the compiler to search for a file
named stdio.h and place its contents at this point in the program. The contents of the header
file become part of the source code when it is compiled.
Formatted Functions:
Formatted functions allow the input read from the keyboard or the output displayed on
screen to be formatted according to our requirements. The input function scanf() and output
function: printf() fall under this category. While displaying a certain data on screen, we can
specify the number of digits after decimal point, number of spaces before the data, the
position where the output is to be displayed, etc, using formatted functions.
Formatted Input:
Formatted input refers to an input data that has been arranged in a particular format. For
example, consider the following data.
20 11.23 Ram
The above line contains three types of data and must be read according to its format.
The first be read into a variable int, the second into float, and the third into char. This is
possible in C using the scanf function. scanf( )stands for scan formatted.
The input data can be entered into the computer from a standard input device keyboard
by means of the C library function scanf. This function can be used to enter any combination
of numerical values, single characters and strings. The function returns the number of data
items that have been entered successfully. The general syntax of scanf function is
scanf (control string, arg1, arg2, ………, argn)
where,
control string refers to a string containing certain required formatting information so
also known as format string and arg1, arg2, ……, argn are arguments that represent the
individual input data items. Actually, the arguments represent pointers that indicate the
addresses of the data items within the computer’s memory.
The control string consists of individual groups of characters, with one character group
for each input data item. Each character group must begin with a percent sign (%). In its
simplest form, a single character group will consist of the percentage sign, followed by a
conversion character which indicates the types of corresponding data item. Within the control
string, multiple character groups can be contiguous, or they can be separated by whitespace
(i.e. blankspace), tabs or newline characters. If whitespace characters are used to separate
multiple character groups in the control string, then all consecutive white-space characters in
the input data will be read but ignored. The use of blank spaces as character group separators
is very common.
Several of the more frequently used conversion characters are listed below:
The following data items could be entered from the standard input device when the
program is executed.
Biratnagar B
1245 B
0.05 B
Biratnagar B
1245 0.05 B
Biratnagar 1245 B
0.05 B
Example: 2
#include<stdio.h>
main( )
{
char line [80];
------
scanf (“%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]”, line) ;
------
}
If the string
EASTERN COLLEGE OF ENGINEERING
Is entered from the standard input device when the program is executed, the entire string will
be assigned to the array line since the string is comprised entirely of uppercase letters &
blank spaces.
If the string were written as
Eastern College of Engineering
then only the single letter E would be assigned to line. Since the first lowercase letter ( in this
case a) would be interpreted as the first character beyond the string.
Example: 3
#include<stdio.h>
main( )
{ char line [80];
-----
scanf (“ %[^\n]”, line) ;
-----
}
A variation of this feature which is often more useful is to precede the characters within
the square brackets by a circumflex (or caret). If the character within the brackets is simply
the circumflex followed by a newline character, then string entered from the standard input
device can contain any ASCII characters except the newline characters (line feed). Thus, the
user may enter whatever he or she wishes and then presses the Enter Key. The Enter Key will
issue the newline character, thus signifying the end of the string.
The consecutive nonwhitespace characters that define a field. It is possible to limit the
number of such characters by specifying a maximum field width for that data item. To do so,
an unsigned integer indicating the field width is placed within the control spring between the
percent sign (%) and the conversion character.
Er. Arun Kumar Yadav, 40
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
The data item may contain fewer characters than the specified filed width. However, the
number of characters in the actual data item cannot exceed the specified field width. Any
characters that extend beyond the specified filed width will not be read. Such leftover
characters may be incorrectly interpreted as the components of the next data item.
Example: 4
#include<stdio.h>
main( )
{
int a, b, c ;
-----
scanf (“%3d %3d %3d”, &a, &b, &c) ;
-----
}
Suppose the input data items that are entered as
123B
Then the following assignment will result:
a = 1, b = 2, c = 3
Example: 5
#include<stdio.h>
main( )
{ int i ;
float x ;
char c ;
-----
scanf (“%3d %5f %c”, &i, &x &c) ;
-----
}
If the data items are entered as
10 256.875 T
The output would now
be 10, 256.8, 7
The remaining two input characters (5 and T) will be ignored.
Example:6
#include<stdio.h>
main( )
{
short ix, iy ;
long lx, ly ;
double dx, dy;
------
scanf (“%hd %ld %lf”, &ix, &ly, &dx) ;
------
}
The control string in the first scanf function indicates that the first data item will be
assigned to a short decimal integer variable. The second will be assigned to a long decimal
integer variable, and the third will be assigned to a double precision variable.
The control string in the second scanf function indicates that the first data item will
have a maximum field width of 3 characters and it will be assigned to short octal integer
variable, the second data item will have a maximum field width of 7 characters and it will be
assigned to a long hexadecimal integer variable, and the third data item will have a maximum
field width of 15 characters and it will be assigned to double precision variable.
In most version of C, it is possible to skip over a data item, without assigning it to the
designated variable or array. To do so, the % sign within the appropriate control group is
followed by an asterisk (*). This feature is referred to as assignment suppression.
Example: 7
#include<stdio.h>
main( )
{
char item[20] ;
Er. Arun Kumar Yadav, 42
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
int partno ;
float cost
------
scanf (“%s %*d %f”, item, &partno, &cost),
------
}
If the corresponding data item are input
fasterner 12345 0.05
fasterner is assigned to item and 0.05 will be assigned to cost. However 12345 will not
be assigned partno because of asterisk, which is interpreted as an assignment suppression
character.
Formatted Output:
Formatted output refers to the output of data that has been arranged in a particular
format. The printf() is a built-in function which is used to output data from the computer onto
a standard output device i.e. screen, This function can be used to output any combination of
numerical values, single character and strings. The printf() statement provides certain features
that can be used to control the alignment and spacing of print-outs on the terminals. The
general form of printf() statement is printf (control string, arg1, arg2, …. , argn) where
control string refers to a string that contains formatting information, and arg1, arg2, …….,
argn are arguments that represent the individual output data item. The arguments can be
written as constants, single variable or array names, or more complex expressions. Function
references may also be included. In contrast to scanf() function, the arguments in a printf()
function do not represent memory addresses and therefore are not preceded by ampersands.
An individual character group in control string will consist of the percent sign, followed by a
conversion character indicating the type of the corresponding data item.
Several of the more frequently used conversion characters are listed below:
For example: 1
#include<stdio.h>
main( )
{
char item [20]
; int partno ;
float cost ;
------
printf (“%s%d%f ”, item, partno, cost) ;
}
Suppose fastener, 12345 and 0.5 have been assigned to name, partno and cost. So, the
output generated will be
fastener123450.05
Example: 2
#include<stdio.h>
main( )
{
Er. Arun Kumar Yadav, 44
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
Example: 3
/* read and write a line of text */
#include <stdio.h>
main( )
{
char line [80] ;
scanf (“%[^\n]”, line)
; printf (“%s”, line) ;
}
Arun Kumar B
Arun Kumar
Control string:
The general syntax of control string :
Flags [Optional]
T he flag affect the appearance of the output. They must be placed immediately after the
percent sign. The flags may be -, +, 0, blank space or #.
Flags Meanings
- : Data item is left justified within the field.
The blank spaces required to fill the
Table:Flags
The field width is an integer specifying the minimum output field width. If the number of
characters in the corresponding data item is less than the specified field width then the data
item will be preceded by enough leading blanks to fill the specified field. If the number of
characters in the data item exceeds the specified field width, then additional space will be
allocated to the data item so that the entire data item will be displayed.
Precision [Optional]
The operation of precision field depends on the types of conversion. It must start with a
period (.)
where w is the integer number specifying the minimum field width of output data. If the
length of the variable is less than the specified field width, then the variable is right justified
with leading blanks.
printf (“%2d”, n)
1 2 3 4 w<l
printf (“%-6d”, n) w>l
1 2 3 4
printf (“%-6d”, n) 0 0 1 2 3 4
Format Output
printf (“%.4d”, 12) ; 0 0 1 2
#eg .:2
float x = 12.3456
Format Output
printf (“%7.4f”, x) ; 1 2 . 3 4 5 6
printf (“%7.2f”, x) ; 1 2 . 3 5
printf (“%-7.2f”, x) ;
1 2 3 5
printf (“%7.2f”, -x) ; _ 1 2 3 5
printf (“%6.4f”, x) ; 1 2 3 4 5 6
printf (“%10.2e”, x) ; 1 2 3 e + 0 1
printf (“%-10.2e”, x) ; 1 2 3 e + 0 1
printf (“%10.2e”, -x) ; _
1 2 3 e + 0 1
Output of Strings:
The general form of control string is %w.p.s
where
w specifies the field width for display and p instructs that only the first P characters of the
string are to be displayed. The display is right justified
For example
char str[10] = “MY NEPAL”
Format Output
Unformatted Functions:
Unformatted functions do not allow the user to read or display data in desired format. These
library functions basically deal with a single character or a string of characters. The functons
getchar( ), putchse( ), gets( ), puts( ), getch( ), getche( ), putch( ) are considered as
unformatted functions.
The getchar( ) function reads a character from a standard input device. The general syntax
is
character_variable = getchar( );
where character_variable is a valid C char type variable. When this statement is encounted,
the computer waits until a key is pressed and assign this character to character_variable.
The putchar( ) function displays a character to the standard output device. The general
syntax of putchar( ) function is
putchar(character_variable) ‘
where character_variable is a char type variable containing a character.
Output:
Enter gender M or F : M
B Our gender is : M
Note:
clrscr( ) is a console fumction used to clear console(display) screen .clrscr( ) is
pronoused clearscreen.getch( ) function is used to hold the console screen.
The functions getch( ) and getche( ) reads a single character the instant it is typed without
waiting for the enter key to be hit. The difference between them is that getch( ) reads the
character typed without echoing it on the screen, while getche( ) reads the character and
echoes (displays) it on the screen. The general syntax of getch( ):
character_variable = getch( ) ;
Similarly, the syntax of getch( ) is
character_variable = getche( ) ;
The putch( ) function prints a character onto the screen. The general syntax is
putch(character_variable) ;
These three functions are defined under the standard library function conio.h and hence we
should include this in our program using the instruction #include<conio.h>
#include<stdio.h>
Er. Arun Kumar Yadav, 50
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
#include<conio.h>
main( )
{
char ch1, ch2 ;
clrscr( );
printf (“Enter first character:”)
; ch1 = getch( ) ;
printf (“\n Enter second character:”) ;
ch2 = getche( )
printf (“\n First character:”)
; putch(ch1) ;
printf(“\n Second character:”) ;
putch(ch2) ;
}
Output:
aB
Enter first character : Enter second
character : b B
First character : a
Second character : b
Since the first input is taken using getch() function, the character ‘a’ entered is not
echoed. However, using getche() function, we can see what we have typed. In both cases,
input accepted as soon as the character typed. The last getch() simply takes a character but
doesnot store it anywhere. So, its work is merely to hold the output screen until a key is
pressed.
The gets( ) function is used to read a string of text containing whitespaces, until a
newline character is encountered. It offers an alternative function of scanf( ) function for
reading strings. Unlike scanf( ) function, it doesnot skip whitespaces. The general syntax of
gets( ) is gets(string_variable) ;
The puts( ) function is used to display the string onto the terminal. The general syntax of
puts( ) is
puts (string _variable)
This prints the string value of string_variable and then moves the cursor to the
beginning of the next line on the screen.
#include<stdio.h>
#include<conio.h>
void main( )
{
char name[20] ;
clrscr( );
printf (“Enter your name:”) ;
gets (name) ;
printf (“your name is:”) ;
puts (name) ;
getch ();
}
output:
Enter your name : Ram Kumar B
Your name is : Ram Kumar
include<stdio.h>
#include<cnio.h>
void main( )
{
int x = 10;
float y = 20;
char z = 'C’;
clrscr( );
printf("%8d,%8.1f, %8e \n",x,y,z);
Er. Arun Kumar Yadav, 52
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
Chapter – 6
Control Statements
The statements which alter the flow of execution of the program are known as control
statements. In the absence of control statements, the instruction or statements are executed in
the same order in which they appear in the program. Sometimes, we may want to execute
some statements several times. Sometime we want to use a condition for executing only a part
of program. So, control statements enable use to specify the order in which various
instruction in the program are to be executed.
6.1 Loops
Loops are used when we want to execute a part of program or block of statement
several times. So, a loop may be defined as a block of statements which are repeatedly
executed for a certain number of times or until a particular condition is satisfied. There are
three types of loop statements in C:
1. For
2. While
3. Do...while
Each loop consists of two segments, one is known as the control statement and the other
is the body of the loop. The control statement in loop decides whether the body is to be
executed or not. Depending on the position of control statement in the loop, loops may be
classified either entry_controlled loop or exit_controlled loop. While and For are
entry_controlled loops where as do...while is exit_controlled loop.
For Loop:
For loops is useful to execute a statement for a number of times. When the number of
repetitions is known in advance, the use of this loop will be more efficient. Thus, this loop is
also known as determinate or definite loop. The general syntax
for (counter initialization ; test condition ; increment or decrement)
{
| * body of loop * |
}
Counter Initialization
Test False
Condition
True
Body of Loop
Update expression
Out of Loop
Algorithm:
1.Start.
2.Print" Enter a number whose factorial is to be calculated”.
3.Read num.
4.Initilize fact to 1 and counter i to1
5.For i<=num
fact=fact*i
i++
End of For
6.Print fact as factorial of the number num.
7.Stop
For example:
/* Calculate the factorial of a number */
/* factorial.c */
#include<stdio.h>
main( )
{
int num, i ;
long fact =
1; clrscr( );
printf (“\n Enter a number whose factorial is to be calculated : “)
; scanf (“%d”, &num) ;
for (i=1 ; i<=num ; i++)
While Loop:
The while statement can be written as
while(condition) while(condition)
statement ; {
statement ; /* body of the loop */
statement ;
-------
}
First the condition is evaluated ; if it is true then the statements in the body of loop are
executed. After the execution, again the condition is checked and if it is found to be true then
again the statements in the body of loop are executed. This means that these statements are
executed continuously till the condition is true and when it becomes false, the loop terminates
and the control comes out of the loop. Each execution of the loop body is known as iteration.
while
condition
Body of Loop
Next statement
out of loop
fig : Flowchart of while loop
#include<stdio.h>
main( )
{
int n, sum = 0, rem
; clrscr( );
printf (“Enter the number :”)
; scanf (%d”, &n) ;
while (n>0)
{
rem = n%10 ; /* taking last digit of number */
sum+ = rem ; /* sum = sum + rem * /
n/ = 10 ; /*n = n/10 */
/* skipping last digit */
}/*end of while*/
printf (“Sum of digits = %d \n”, sum)
; getch( );
}
Output:
Enter the number : 1452
Sum of digits = 12
do...while loop:
The do...while statement is also used for looping. The body of this loop may contain a
single statement or a block of statements. The general syntax is :
do do
statement ; {
while(condition) ; statement1 ;
statement2 ;
--------
statementn ;
} while(condition) ;
Body of Loop
Condition False
Here firstly the segments inside the loop body are executed and then the
condition is evaluated. If the condition is true, then again the loop body is executed and this
process continues until the condition becomes false. Unlike while loop, here a semicolon is
placed after the condition. In a ‘while’ loop, first the condition is evaluated and then the
statements are executed whereas in do while loop, first the statements are executed and then
the condition is evaluated. So, if initially the condition is false the while loop will not execute
at all, whereas the do while loop will always execute at least once.
2. The body of the loop may not be executed 2. The body of the loop is always executed at
at all if the condition is not satisfied at the least once.
very first attempt.
3. syntax : 3. syntax :
while (condition) do
{ {
body of the loop body of the loop
} } while (condition)
Nesting of loops:
When a loop is written inside the body of another loop, then it is known as nesting of
loops. Any type of loop can be nested inside any other type of loop. For example, a for loop
may be nested inside another for loop or inside a while or do...while loop. Similarly, while
and do while loops can be nested.
Output:
i=1
j=1 j=2 j=3 j=4
i=2
j=1 j=2 j=3 j=4
i=3
j=1 j=2 j=3 j=4
6.2 Decisions
Since decision making statements control the flow of execution, they also fall under the
category of control statements. Following are decision making statements:
• if statements
• if....else statements
• else if statement
• Nested if...else statement
• switch statement
if statement:
The if statement is a powerful decision making statement and is used to control the flow
of execution of statements. This is a bi-directional condition control statements. This statement
is used to test a condition and take one of two possible actions, If the condition is true then a
single statement or a block of statements is executed (one part of the program), other wise
another single statement or a block of statements is executed (other part of the program). In C,
any non-zero value is regarded as true while zero is regarded as false.
syntax :
if (condition) if (condition) statement1 ; { statement1 ;
-----
statement n ;
}
Flowchart:
True
Condition
Statement1
False
Next Statement
#include<stdio.h>
main( )
{
int num ;
clrscr( );
printf (“Enter a number to be tested:” ) ;
scanf (“%d”, &num) ;
if (num<0)
printf(“The number is negative”) ;
printf (“value of num is : %d\n”, num) ;
getch( ) ;
}
st
Output : 1 run
Enter a number to be tested : -6
B The number is negative
Value of num is : -
nd
62 run
Enter a number to be tested : 6 B
Value of num is : 6
if...else statement:
The if..else statement is an extension of the simple if statement. It is used when there are
two possible actions – one when a condition is true and the other when it is false. The syntax is
:
if (condition) if (condition)
statement1 ; {
else statement ;
statement2; } ----
else
{
statement ;
----
}
Flowchart:
Condition
statement1
statement2
Next statement
Here if the condition is true then statement1 is executed and if it is false then statement2
is executed. After this the control transfers to the next statement which is immediately after the
if...else control statement.
else if statement:
if(year%100 = = 0)
{
if(year%400 = = 0)
printf (“Leap year \n”) ;
else
printf (“Not leap year\n”) ;
}
getch( );
}
Output:
Enter the numbers: 3 4 5 B
Largest num is 5
else if statement:
This is a type of nesting in which there is an if...else statement in every else part except
the last else part. This type of nesting is frequently used in programs and is also known as
else if ladder. if(condition1)
statementA ; if(condition1)
else statementA ;
if(condition2) statementB ; elseif(condition2)
else statementB ;
if (condition3) statementC ; elseif(condition3)
else statementC ;
statement D ; else
statement D ;
False
True
Condition2
Stat A
True
C
on
dit
io
n3
False
Stat B
Stat C Stat D
Next Statement
Fig : Flowchart of else if ladder
/* Program to find out the grade of a student when the marks of 4 subjects are given. The
method of assuming grade is as
per>=80 grade = A
per<80 and per>=60 grade = B
per<60 and per>=50 grade = C
per<50 and per>=40 grade = D
per<40 grade = F
Here Per is percentage
*/
#include<stdio.h>
main( )
{
float m1, m2, m3, m4, total, per
; char grade ;
clrscr( );
printf (“Enter marks of 4 subjects : ”) ;
scanf (“%f%f%f%f”,&m1, &m2, &m3, &m4) ;
total = m1+m2+m3+m4 ;
per = total /4
; if(per>=80)
grade = ‘A’
; elseif(per>=60)
grade = ‘B’ ;
elseif(per>=50)
grade = ‘C’ ;
elseif(per>=40)
grade = ‘D’ ;
else
grade = ‘F’ ;
printf(“Percentage is %f\n Grade is %c\n”, per, grade) ;
getch( );
}
if(per<40)
grade = ‘F’ ;
In else_if ladder whenever a condition is found true other conditions are not checked,
while in if statement all the conditions will always be checked wasting a lot of time and
moreover the conditions here are more lengthy.
6.3 Statements: switch, break, continue, goto
Switch Statement:
This is a multi-directional conditional control statement. Sometimes, there is a need in
program to make choice among number of alternatives. For making this choice, we use the
switch statement.
The general syntax is
switch(expression)
{ case constant1:
statements ;
break ;
----
----
case constantN:
statements ;
break,
default: statements
;
}
Here, switch, case and default are keywords. The ‘expression’ following the switch
keyword can be any C expression that yields an integer value or a character value. It can be
value of any integer or character variable, or a function call returning on integer, or an
arithmetic, logical, relational, bitwise expression yielding integer value.
The constants following the case keywords should be of integer or character type. These
constants must be different from each other.
The statements under case can be any valid C statements like if...else, while, for or even
another switch statement. Writing a switch statement inside another is called nesting of
switches.
Firstly, the switch expression is evaluated then value of this expression is compared one
by one with every case constant. If the value of expression matches with any case constant,
then all statements under that particular case are executed. If none of the case constant
matches with the value of the expression then the block of statements under default is
executed.
Flowchart:
switch
(expression)
case constant
case constant
case N
default default
Out of switch
case 2 :
printf (“second\n”)
; case 3 :
printf (“third\n”) ;
default :
printf (“wrong choice\n”) ;
}
getch( );
}
Output:
Enter your choice : 2
Second
Third
Wrong Choice
Here value of choice matches with second case so all the statements after case 2 are
executed sequentially. The statements of case 3 and default are also executed in addition to
the statements of case2. This is known as falling through cases.
Suppose we don’t want the control to fall through the statements of all the cases under
the matching case, then we can use break statement.
Break statement:
Break statement is used inside lops and switch statements. Sometimes it becomes
necessary to come out of the loop even before the loop condition becomes false. In such a
situation, break statement is used to terminate the loop. This statement causes an immediate
exit from that loop in which this statement appears. It can be written as (i.e. general syntax) :
break,
If a break statement is encountered inside a switch, then all the statements following
break are not executed and the control jumps out of the switch.
{
case1:
print (“First\n”) ;
break ; /* break statement */
case2:
printf(“Second\n”)
; break ;
case3:
printf (Third\n”)
; break ;
default :
printf (“Wrong choice\n”) ;
}/*end of switch*/
getch( );
} /* End of main( ) */
Output:
Enter your choice : 2 B
Continue statement:
The continue statement is used to bypass the remainder of the current pass through a
loop. The loop does not terminate when a continue statement is encountered. Instead the
remaining loop statements are skipped and the computation proceeds directly to the next pass
through the loop. The general syntax :
continue ;
Loop statements
before continue
Next
iteration of
loop
condition True continue statements
false
Loop statements
after continue
fig : flowchart of continue control statemen
goto statement:
The goto statement is used to alter the normal sequence of program execution by
unconditionally transferring control to some other part of the program. The goto statement
transfers the control to the labeled statement somewhere in the current function. The general
syntax of goto statement:
goto label ;
-----
-----
label :
statement ;
-----
-----
Here, label is any valid C identifier and it is followed by a colon. Whenever, the statement
goto label, is encountered, the control is transferred to the statement that is immediately after
the label.
Generally, the use of goto statement is avoided as it makes program illegible and unreliable.
This statement is used in unique situations like
• Branching around statements or group of statements under certain conditions
• Jumping to the end of a loop under certain conditions, thus bypassing the remainder of
loop during current pass.
• Jumping completely out of the loop under certain conditions, terminating the execution
of a loop.
odd :
printf (“Number is odd”) ;
end :
printf (“\n”) ;
getch( );
}
Output:
Enter the number : 6
B Number is even.
We have already known that we can jump out of a loop using either the break statement
or goto statement. In a similar way, we can jump out of a program by using the library
function exit( ). In case, due to some reason, we wish to break out of a program and return to
the operating system. The general syntax is
-----
-----
if (condition) exit (0) ;
-----
-----
The exit( ) function takes an integer value as its argument. Normally zero is used to
indicate normal termination and non zero value to indicate termination due to some error or
abnormal condition. The use of exit( ) function requires the inclusion of the header file
<stdio.h>.
printf("Enter number:");
scanf("%d",&num);
i=2,c=0;
while(i<=num-1)
{
if(num% i= =0)
c++;
i++;
}
if(c= = 0)
getch( );
}
Output:
Enter number:3
3 is prime number
}
getch( );
}
PU2009
/* WAP to show
*
***
** * * *
*******
*/
main( )
{
int i,j,n;
clrscr( );
printf(“Enter value of n:”);
scanf(“%d”,&n);
getch( );
}
Output:
Enter the number to be checked : 32123
The number is palindrome
/* WAP to find the roots of quadratic equation */
#include<math.h>/*used for math function like sqrt() and fabs()*/
main( )
{
Float a, b, c, x1,x2,d,real ,img;
clrscr( );
Er. Arun Kumar Yadav, 78
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
Chapter – 7
Functions
Library Functions:
These are the functions which are already written, compiled and placed in C Library and
they are not required to be written by a programmer. The function’s name, its return type,
their argument number and types have been already defined. We can use these functions as
required. For example: printf(), scanf(), sqrt(), getch(), etc.
main( )
{
int c ;
double d ;
crlscr( );
printf (“Enter temperature in Celsius: ”) ;
scanf (“%d”, &c) ;
d = convert(c) ; /*Function call*/
printf (“The Fahrenheit temperature of %d C = %lf F”,c, d) ;
getch( );
}
double convert (int C) /* function definition */
{
double f ;
f = 9.0*c/5.0+32.0 ;
return f ;
}
where, return_type specifies the data type of the value returned by the function. A
function can return value of any data type. If there is no return value, the keyword void is
used. type1, type2, ....., typen are type of arguments. Arguments are optional. For example:
int add (int, int) ; /* int add (int a, int b) ;*/
void display (int a) ; /* void display (int); */
Function definition:
A function definition is a group of statements that is executed when it is called from
some point of the program. The general syntax is
return_type function_name (parameter1, parameter2, ....., parametern)
{-----
statements ;
-----
}
where,
return_type is the data type specifier of data returned by the function.
function_name is the identifier by which it will be possible to call the function.
Parameters(as many as needed) : Each parameter consists of a data type specifier
followed by an identifier like any regular variable declaration. (for eg: int x) and
which acts within the function as a regular local variable. They allow to pass
arguments to the function when it is called. The different parameters are separated
by commas.
statements is the function’s body. It is a block of statements surrounded by
braces{}.
The first line of the function definition is known as function header.
return statement:
The return statement is used in a function to return a value to the calling function. It
may also be used for immediate exit from the called function to the calling function without
returning a value.
This statement can appear anywhere inside the body of the function. There are two
ways in which it can be used:
return ;
return (expression) ;
where return is a keyword. The first form of return statement is used to terminate the
function without returning any value. In this case only return keyword is written.
return (x+y*z);
return (3*sum(a,b)) ;
If function return int, float or any other type value then we have to assign the call to
same type value like
variable = function_name(parameter) ;
For example:
m = mul(x, y)
The type of m is same as the return type of mul function. So, we can write
printf (“%d”, mul(x, y) ); also as printf (“%d”, m) ;
Actual: When a function is called some parameters are written within parenthesis. These are
known as actual parameter. For example
main() {
-----
convert(c) ; actual parameter
-----
}
Formal parameters are those who are written in function header. For
example double convert (int a) /* function header */
{ formal parameter
Types of functions:
The functions can be classified into four categories on the basis of the arguments and
return values:
1. Functions with no arguments and no return value
2. Functions with no arguments and a return value
3. functions with arguments and no return value
4. Functions with arguments and a return value
Er. Arun Kumar Yadav, 84
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
int func(void)
{
----
----
return (expressions) ;
}
7.3 Call by value & Call by reference ( Or Pass by value & Pass by reference)
printf (“y=%d\n”,
y) getch( ) ;
}
void swap (int a, int b) /*function definition */
{
int t ;
t=a;
a=b;
b=t;
}
Output x = 10
y = 20
Pointer:
A pointer is a variable that stores a memory address of a variable. Pointer can have any
name that is legal for other variable and it is declared in the same fashion like other variables
but always preceded /xy ‘*’ (asterik) operator. Thus pointer variables are defined as
int *a ;
float *b ;
char *c ;
where a, b, c are pointer variable which stores address of integer, float and char
variable. Thus the following assignments are valid.
int x ;
float y ;
char c ;
a = &x ; /* the address of x is assigned to pointer variable a */
b = &y ; /* the address of y is stored to pointer variable b */ c
= &c ; /* the address of c is stored to pointer variable c */
#include<stdio.h>
void swap(int *, int * ) ; /* function prototype
*/ main ( )
{
int x, y ;
x = 10 ;
y = 20 ;
clrscr( );
swap (&x, &y) ; /* function call by address */
printf (“x=%d\n”, x) ;
printf (“y=%d\n”, y) ;
getch( ) ;
}
void swap(int *a, int *b)
{
int t ; t
= *a ;
*a = *b
; *b = t ;
}
Output:
x = 20
y=10
[P.U.2005]
7.5 Concept of Local, Global & Static variables:
Default initial value of such type of variable is an unpredictable value which is often
called garbage value. The scope of it is local to the block in which the variable is defined.
Again, its life is till the control remains within the block in which the variable is defined.
Storage class refers to the performance of a variable and its scope within the program.
Initial Value: This is the initial value assigned by the language to a variable if no value is
assigned to variable explicitly by the programmer.
Scope: Scope of a variable can be defined as the region over which the variable is visible or
valid.
Life time: The period of time during which memory is associated with a variable is called the
life time or extent of the variable.
Er. Arun Kumar Yadav, 90
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
void main( )
{
clrscr( );
printf (“\t%d”,a) ;
func( );
printf (“\t%d”,a) ;
}
Output : 10 20 21 Illustratration
of extern variable: main( )
{
extern float marks ;
-----
}
func1( )
{
extern float marks ;
-----;
}
float marks ; /* global space but defined after function */
The extern declaration does not allocate storage space variables. The extern declaration
of marks inside the function informs the compiler that marks is a float type extern variable
defined somewhere else in the program.
Static variables :
Static variables are declared by writing keyword static in front of the declaration.
static type var_name ;
A static variable is initialized once and the value of a static variable is retained between
function call. If a static variable is not initialized then it is automatically initialized to O. Its
scope is local to the block in which the variable is defined. Again, the life time is global i.e.
its value persists between different function calls.
main( ) main( )
{ clrscr( ); {
increment( ) ; increment( ) ;
increment() ; increment( ) ;
increment() ; increment( ) ;
increment() ; increment( ) ;
getch( ); getch( );
} }
Output :
1 1
1 2
2 3
1 4
Register variable:
Register variables are special case of automatic variables. Automatic variables are
allocated storage in the memory of the computer; however, for most computers accessing data
in memory is considerably slower than processing in the CPU. These computers often have
small amounts of storage within the CPU itself where data can be stored and accessed
quickly. These storage cells are called registers. If a variable is declared as register variable,
then it is stored in the CPU register. They are allocated storage upon entry to a block ; and the
storage is freed when the block is exited. The scope of register variables is local to the block
in which they are declared. Rules for initializations for register variables are the same as for
automatic variables. For eg.
main( )
{
register int a = 10 ;
-----
-----
}
To solve a problem using recursive method, two conditions must be satisfied. They are:
• Problem could be written or defined in terms of its previous result.
• Problem statement must include a stopping condition i.e. we must have an if statement
somewhere to force the function to return without the recursive call being executed,
otherwise function will never return.
/* WAP to find the factorial of a number using recursive method */
long int factorial (int n)
{
if (n = = 1)
return (1) ;
else
return (n*factorial(n-1)) ;
}
main( )
{ int num ;
printf (“Enter a number : ”) ;
scanf (“%d”, &num) ;
printf (“The factorial is %ld”, factorial (num)) ;
}
Output:
Enter a number : 5 B
The factorial is 120
Recursion Iteration
1. A function is called from the definition of 1. Loop is used to do repeated task.
the same function to do repeated.
2. Recursive is a top-down approach to 2. Iteration is like bottom-up approach.
problem solving.
3. In recursion, a function calls to itself until 3. In iteration, a function doesn’t call to itself.
some condition will be satisfied.
4. Problem could be defined in terms of its 4. It is not necessary to define a problem in
previous result to solve a problem using term of its previous result to solve using
recursion. iteration.
5. All problems cannot be solved using 5. All problems can be solved using iteration.
recursion.
around any of the poles. Initially, the disks are stacked on the leftmost pole in the order of
decreasing size i.e. the largest on the bottom and the smallest on the top.
1
2
3
4
The object of the game is to transfer the disks from the leftmost pole to the rightmost
pole, without ever placing a larger disk on the top of a smaller disk. Only one disk may be
moved at a time, and each disk must always be placed around one of the poles.
The general strategy is to consider one of the poles to be the origin, and another to be
the destination. The third pole will be used for immediate storage. Thus allowing the disks to
be moved without placing a larger disk over a smaller one. Assume there are n disks,
numbered from smallest to largest. If the disks are initially stacked on the left pole, the
problem of moving all n disks to the right pole can be stated in the following recursive
manner.
1. Move the top n-1 disks from the left pole to the centre pole.
2. Move the nth disk (the largest disk) to the right pole.
3. Move the n-1 disks on the centre pole to the right pole.
The problem can be solved in this manner for any value of n greater than, 0(n=0
represents a stopping condition). In order to program this game, we first label the poles so
that the left pole is represented as L, the centre pole as C and the right pole as R. We then
construct a recursive function called transfer that will transfer n disks from one pole to
another. Let us refer to the individual poles with the char type variable from, to and temp for
the origin, destination, and the temporary storage respectively. Thus, if we assign the
character L to from, R to and C to temp, we will in effect be specifying the movement of n
disks from the leftmost pole to righmost pole, using the centre pole for immediate storage.
int n ;
printf (“Welcome to the Tower of Hanoi \n\n”) ;
printf (“How many disk?”) ;
scanf (“%d”, &n) ;
printf (“\n”) ;
transfer (n, ‘l’, ‘R’, ‘C’) ;
}
void transfer (int n, char from, char to, char temp)
/* transfer n disks from one pole to another */
/* n = number of disks
from = origin
to = destination
temp = temporary storage */
{
if(n>0) {
/* move n-1 disk from origin to temporary */
transfer (n-1, from, temp to) ;
/* move nth disk from origin to destination */
printf (“Move disk %dfrom%cto%c\n”, n, from, to) ;
/* move n-1 disks from temporary to destination */
transfer (n-1, temp, to, from) ;
}
return ;
}
We know that every C program should have one main( ) function and that it marks the
beginning of the program. But what we have not mentioned so far is that it can also take
arguments like other functions. In fact main can take two arguments called argi and argu and
the information contained in the command line (i.e. C>PROGRAM X_FILE Y_FILE) is
passed on to the program through these arguments when main( ) is called up by the system.
The variable argc is an argument counter that the number of arguments on the command
line. The argu is an argument vector and represents an array of character pointers that point to
the command line arguments. The size of this array will be equal to the value of argc. For
instance, for the command line given above, argc is three and argu is an array of three
pointers to strings as shown below:
argu[0] PROGRAM
argu[1] X_FILE
argu[2] Y _FILE
In order to access the command line arguments, we must declare the main function and
its parameters as follows:
main(argc, argu)
; int argc ;
char *argu[] ;
{
WAP that will receive a filename and a line of text as command line arguments and write the
text to the file.
The command line
F12_6 TEXT AAAAAA BBBBBB - - - - - - - GGGGGG Each word in the command
line is an argument to the main and therefore the total
number of argument is 9.
The argument vector argv[1] points to the string TEXT and therefore the statement.
fp = fopen(argv[1], “w”) ; opens a file with name TEXT. The for loop that follows
immediately write the remaining 7 arguments the file TEXT.
Program also prints two output, one from the file TEXT and the other from the system
memory. The argument vector argv contains the entire command line in the memory and
therefore the statement:
printf (“%s\n”, i*s, argv[i]) ;
prints the argument from the memory.
#include<stdio.h>
main(argc, argv) /* main with arguments */
int argc ; /* argument count */
char * argv[ ] ; /* list of arguments */
{
file *fp
; int i ;
char word[15] ;
fp=fopen(argv[1], “w”) ; /* open file with name arg[1] */
printf(“/n No arguments in command line = %d\n\n”, argc) ;
for (i = 2 ; i<large ; i++)
{
Er. Arun Kumar Yadav, 98
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
1.Define function and list all the types of user defined function used in C. How do
you differentiate library function from user defined function?
2.Write a program to calculate factorial of 'n' number by using recursive function where n
is the number inputted by user.
3.What are local and global variables? Determine what would be the output of the
following:
int i=l;
printf("i=%d i=%d i=%d",i, i + +, ++i)
4.What is the method of declaring local and global variables?
5.What is a recursive function? Write a program in C to allow a user to enter an integer
number interactively and display its factorial value.
6.What is a static variable? Write a programin C that uses a static variable.
7.What is a function? Give the syntax of declaring a function in C.
8.Explain how an array can be passed to a function with the help of a suitable program in C.
9.What is Differences between call by value and call by reference.
Chapter – 8
Arrays and Strings
8.1 Introduction:
An array is a collection of same type of data item which are stored in consecutive
memory locations under a common name. Suppose, we have 20 numbers of type integer and
we have to sort them in ascending or descending order. If we have no array, we have to define
20 different variable like a1, a2, ......, a20 of type int to store these twenty numbers which will
be possible but inefficient, If the number of integers increase the number of variables will
also be increased and defining different variables for different numbers will be impossible
and inefficient. In such situation where we have multiple data items of same type to be stored,
we can use array. In array system, an array represents multiple data items but they share same
name. The individual elements are characterized by array name followed by one or more
subscripts or indices enclosed in square brackets. The individual data items can be characters,
integers, floating point numbers, etc. However, they must all be of the same type and the
same storage class (i.e. auto, register, static or extern)
The elements of an integer array a[5] are stored continuous memory locations. It is
assumed that the starting memory location is 2000. As each integer element requires 2 bytes,
subsequent element appears after gap of 2 locations. The general syntax of array is [i.e.
declaration of an array :]
data_type array_name[size];
or if we want to add storage classes then that look like:
storage_class data_type array_name[size] ;
where
• storage_class refers to the storage class of the array. It may be auto, static, extern and
register, It is optional.
• data_type is the data type of array. It may be int, float, char, etc.
• array_name is name of the array. It is user defined name for array. The name of array
may be any valid identifier.
• size of the array is the number of elements in the array. The size is mentioned within[ ].
The size must be an int constant like 10, 15, 100, etc or a constant expression like
symbolic constant. For
example #define size 80
a [size] ;
The size of the array must be specified [i.e. should not be blank) except in array
initialization.
int num[5] ; i.e. num is an integer array of size 5 and store 5 integer values
char name[10] ; i.e. name is a char array of size 10 and it can store 10 characters.
float salary[50] ; i.e. salary is a float type array of size 50 and it can store 50 fractional
numbers.
Initialization of array:
The array is initialized like follow if we need time of declaration
data_type array_name[size] = {value1, value2, ........, valuen} ;
For eg.
1. int subject[5] = {85, 96, 40, 80, 75} ;
2. char sex[2] = {‘M’, ‘F’} ;
3. float marks[3] = {80.5, 7.0, 50.8} ;
4. int element[5] = {4, 5, 6}
In example(4), elements are five but we are assigning only three values. In this case the
value to each element is assigned like following
element[0] = 4
element[1] = 5
element[2] = 6
element[3] = 0
element[4] = 0
i.e. missing element will be set to zero
b = a ; /* not acceptable
*/ if (a<b)
{_ _ _ _ } /* not acceptable */
we can assign integer values to these individual element
directly: a[0] = 30 ;
a[1] = 31 ;
a[2] = 32 ;
a[3] = 33 ;
a[4] = 34 ;
Multi-dimensional arrays:
An array of arrays is called multi-dimensional array. For example a one dimensional
array of one dimensional array is called two dimensional array.
A one dimensional array of two dimensional arrays is called three dimensional arrays,
etc. The two dimensional array are very useful for matrix operations.
clrscr( ) ;
for (i=0 ; i<2 ; i++)
for (j = 0 ; j<3 ; j++)
{
printf(“Enter matrix [%d] [%d] : \t”, i, j) ;
scanf(“%d”, &matrix [i] [j] ) ;
}
printf (“\n Entered matrix is : \n”)
; for (i=0 ; i<2 ; i++)
{
printf(“%d\t”, matrix [i] [j])
; printf(“\n”) ;
}
getch( )
}
Output:
Enter matrix [0] [0] : 1
Enter matrix [0] [1] : 2
Enter matrix [0] [2] : 3
Enter matrix [1] [0] : 4
Enter matrix [1] [1] : 5
Enter matrix [1] [2] : 6
Enter matrix is
1 2 3
4 5 6
getch( ) ;
} /* end of main( ) */
Output:
Enter row of the first matrix (<=10) : 2
Enter column of the first matix (<=10) : 1
Enter row of the second matrix (<=10) : 1
Enter column of the second matrix (<=10) : 2
Enter the first matrix :
Enter a[0] [0] : 2
Enter a[1] [0] : 2
Enter the second matrix :
Enter b[0] [0] : 3
Enter b[0] [1] : 3
The matrix multiplication is :
6 6
6 6
#Solve the Matrix
2
a= b = (3 3)
1×2
2 2×1
6 6
s=
6
6 2×2
a b e f
A= B=
c d g
2×2 h 2×2
ae +bg af +bh
A×B =
ce + dg cg + dh) 2×2
8.3 Passing arrays to functions:
Like any other variables, we can also pass entire array to a function. An array name can
be named as an argument for the prototype declaration and in function header. When we call
the function no need to subscript or square brackets. When we pass array that pass as a call
by reference because the array name is address for that array.
main( )
{
int num[5] = {100, 20, 40, 15, 33, i
; clrscr( ) ;
printf (“\n The content of array is \n”) ;
for (i=0; i<5; i++)
display (num[i]) ; /*Pass array element fo fun */
getch( ) ;
}
void display(int n)
{
printf (“\t%d”, n ) ;
}
Output:
The content of array is
100 20 40 15 3
/* Program to read 10 numbers from keyboard to store these num into array and then
calculate sum of these num using function */
#include<stdio.h>
#include<conio.h>
int sum (int a[ ]) ;
void output (int a[ ])
; main( )
{
int a[10], s, i
; clrscr( ) ;
printf (“Enter 10 elements : \n”) ;
for (i=0 ; i<=9 ; i++) ;
scanf (“%d”, &a[i])
; output (a) ;
s = sum (a) ;
printf (“Sum of array element is :\n”, s) ;
getch( ) ;
}
int sum (int a[ ] ) for
(i=0 ; i<=9 ; i++) n
= n+a[i] ;
return (n) ;
}
Enter second
array: 1 2
34
Subtraction is:
3 1
-1 2
8.4Arrays of Strings:
String:
Array of character type which is terminated by null characters is known as string. In other
words, we can say that a string is a sequence of contiguous character in memory terminated
by the null character ‘\0’. The terminating null character ‘\0’ is important because it is the
only way the string handling functions can know there the string ends. Normally, each
character is stored in one byte, and successive characters of the string are stored in successive
bytes. In C, header file string.h provides special function for manipulating strings.
Initializing string:
A string is initialized as
char name[ ] = {‘A’, ‘R’, ‘U’, ‘N’}
Then string name is initialized to ARUN. This technique is also valid. But C offers special
way to initialize the string as
char name[ ] = “Arun” ;
The characters of the string are enclosed within a pair of double quotes.
Arrays of strings:
Arrays of string means two dimensional array of characters. For example
char str[5] [ 8] ;
The first dimension (size) tells how many strings are in the array. The second dimension tells
the maximum length of each string. In above declaration, we can store 5 strings, each can
th
store maximum 7 characters ; last : 8 space is for null terminator in each string.
1. strlen( ):
This function returns an integer which denotes the length of string passed. The length of
string is the number of characters present in it, excluding the terminating null character. Its
syntax is
integer_variable = strlen(string) ;
2. strcpy( ):
The strcpy( ) function copies one string to another. The function accepts two string as
parameters and copies the second string character by character into the first one upto
including the null character of the second string. The syntax is
strcpy(destination_string, source_string) ;
i.e. strcpy(s1, s2) ; means the content of s2 is copied to s1.
Output:
The copied string is Arun Kr. Yadav
3.strcat( ):
This function concatenates two strings i.e. it appends one string at the end of another.
This function accepts two strings as parameters and stores the contents of the second string at
the end of the first. Its syntax is:
strcat (string1, string2) ;
i.e. string1 = string1 + string2 ;
4.strump( ):
This function compares two strings to find out whether they are same or different. This
function is useful for constructing and searching strings as arranged into a dictionary. This
function accepts two string as parameters and returns an integer whose value is
1) less than 0 if the first string is less than the second
2) equal to 0 if both are same
3) greater than 0 if the first string is greater than the second
Two strings are compared character by character until there is a mismatch or end of one
of strings is reached. Whenever two characters in two strings differ, the string which has the
character with a higher ASCII value is greater. For example, consider two string “ram” and
“rajesh”. The first two character are same but third character in string ram and that is in rajesh
are different. Since ASCII value of character m in string ram is greater than that of j in string
rajesh, the string ram is greater than rajesh. Its syntax
integer_variable = strump(string1, string2) ;
#include<string.h>
main( )
{ char name1[15], name2[15] ; int
diff ;
printf (“\n Enter first string \t”)
; gets(name1) ;
printf (“\n Enter second string \t”)
; gets(name2) ;
diff = strcmp(name1, name2)
; if (diff>0)
printf (“%s is greater than %s by value %d”, name1, name2, diff)
; else
print (“%s is same as %s”, name1, name2) ;
}
Output:
Enter first string ram
Enter second string rajesh
ram is greater than rajesh by value 3.
5. Strrev( ):
This function is used to reverse all characters in a string except null character at the end
of string. The reverse of string “abc” is “cba”. Its syntax is
strrev(string) ;
For example:
strrev(s) means it reverses the characters in string s and stores reversed string in s.
char st[40] ;
int len i, pal = 1
; clrscr( ) ;
printf (“Enter string of our choice:”) ;
gets(st) ;
len = strlen(st) ;
for (i=0; i<(len 12); i++)
{
if (st[i] ! = st[len-i-
1]) pal = 0 ;
}
if (pal = = 0)
printf (“\n The input string is not palindrome”) ;
else
printf (“\n the input string is palindrome”)
; getch( ) ;
}
Some Important Questions:
1.What is an array? What are the advantages of using array?
Chapter – 9
Pointers
9.0 Pointers:
Before studying pointers, it is important to understand how memory is organized in a
computer. The memory in a computer is made up of bytes arranged in a sequential manner.
Each byte has an index number which is called address of that byte. The address of these
bytes start from zero and the address of last byte is one less than the size of memory. Suppose
20
we have 64MB of RAM (Random Access Memory), then memory will consist of 64×2 =
67108864. the address of these bytes will be from 0 to 67108863.
Memory Block
0
1
2
3
|
|
|
|
|
|
|
67108863
Memory Address
We have studied that it is necessary to declare a variable before using it, since compiler
has to reserve space for it. The data type of the variable also has to be mentioned so that the
compiler knows how much space need to be reserved. For example:
int age;
The compiler reserves 2 consecutive bytes from memory for this variable and associates
the name age with it. The address of first byte from the two allocated bytes is k\a the address
of variable age.
Suppose compiler has reserved bytes numbered 65524 and 65525 for the storage of
variable age, then the address of variable age will e 65524. Let us assign some value to this
variable.
age = 20;
Now this value will be stored in these 2 bytes in form of binary representation. The
number of bytes allocated will depend on the data type of variable. For example, 4 bytes
would have been allocated for a float variable, and the address of first byte would be called
the address of variable.
Introduction:
A pointer is a variable that contains a memory address of data or another variable. [In
other word, a pointer is a variable that stores memory address]. Like all other variables it also
has a name to be declared and occupies some space in memory. It is called pointer because it
points to a particular location in memory by storing the address of that location.
int *iptr,sn=30;
float *fptr,price=150.50;
iptr=&sn; \*assigning of pointer*\
fptr=&price;
Now, iptr contains the address of variable sn i.e. it points to variable sn, similarly fptr
points to variable sn, similarly fptr points variable price.
Pointer are also variables so compiler will reserve space for them and they will also
have some address. All pointers irrespective of their base type will occupy same space in
memory since all of them contain address only. Generally 2 bytes are used to store an address
(may vary in different computers), so the compiler allocates 2 bytes for a pointer variable.
If pointers are declare after the variable
like int sn=30,*p=sn;
float price=150.50,*q=&price;
It is also possible to assign the value of one pointer variable to the other provided their
base type is some.
P1=P;
Now, both pointer variable P and P1 contains the address of variable sn and points the
same variable
5000
5524
P 5524
30
5400 sn
5524
P1
We can also assign constant zero to a pointer of any type. A symbolic constant NULL is
defined in stdio.h which denotes the value zero. The assignment of NULL to a pointer
guarantees that it does not point to any valid memory locations. This can be done as
ptr=NULL;
Application of pointer:
Some uses of pointers are
1) Accessing array elements
2) Returning more than one value from a function
3) Accessing dynamically allocated memory
4) Implementing data structure like linked lists, trees, and graphs.
5) Increasing the execution speed as they refer address.
\* Program to convert upper case letter into lower and vice versa using passing pointer to a
function *\
#include<stdio.h>
void conversion(char*); \ function prototype *\ main( )
{
char input;
clrscr( );
printf(“Enter character of our choice:\n”);
scanf(“%c”,&input); conversion(&input);
printf(“%d\n”,*(p+i));
getch( );
}
The output of above program is
56789
Because the statement printf(“%d\n”,*(p+i)); exzecute 5 times from i=0 to i=4. When
i=0 then *(p+i) is *(p+0) means *p therefore this prints the value which store at location P.
Similarly *(p+1) means the value of second element because p+1 is pointer to the
second element of array. Similarly, other elements are printed.
We know that array name is also pointer to so the above program can be written
as #include<stdio.h>
#include<conio.h>
main( )
{
int a[5]={ 5, 6, 7, 8, 9};
int i;
clrscr( )
for(i=0; i<=4; i++)
printf(“%d\n”,*(a+i);
getch( );
}
output:
5
6
7
8
9
#include<conio.h>
void main( )
{
int a[2] [3] = {{5, 6, 7},{8, 9, 10}};
int i, j;
clrsc( );
for(c=0; i<=1; i++)
{ for(j=o; j<2; j++)
Printf(“%d\t”, *(*(a+i)+j));
}
printf(“\n”);
}
getch( );
}
output:
5 6 7
8 9 10
A memory space equivalent to 100 times the size of an integer (i.e. 1002 bytes = 200
bytes) is reserved and the address of the first byte of the memory allocated is assigned to the
pointer x of type int (i.e. x refers the first address of allocated memory).
2) calloc( ):
The function calloc( ) provides access to the C memory heap which is available for
dynamic allocation of variable_size block of memory. Unlike malloc( ), the function calloc( )
accepts two arguments: no_of_blocks and size_of_block. This parameter no_of_blocks
specifies the number of items to allocate and size_of_block specifies the size of each item.
The function calloc( ) allocates multiple blocks of storage, each of the same size and then sets
all bytes to zero. One important difference between malloc( ) and calloc( ) is that calloc( )
initializes all bytes in the allocated block to zero. Thus, it is normally used for requesting
memory space at runtime for storing derived data type such as arrays user defined. Its syntax
is
ptr=(data_type*calloc(no_of_block,size_of_each_block);
For example:
x=(int*)calloc(5,10*sizeof(int));
or x=(int*)calloc(5,20);
The above statement allocates contiguous space for 5 blocks, each of size 20 bytes i.e.
we can store 5 arrays, each of 10 elements of integer types.
3) free( ):
The built-in function frees previously allocated space by calloc, malloc or realloc
function. The memory dynamically allocated is not returned to the system until the
programmer returns the memory explicity. This can be done using free( ) function. Ths, this
function is used to release the space when it is not required. Its syntax is
Free(ptr);
Where ptr is a pointer to a memory block which has already been created by malloc( ),
calloc( ) or realloc( )function.
4) realloc( ):
This function is used to modify the size of previously allocated space. Sometimes, the
previously allocated memory is not sufficient, we nned additional space and sometime the
allocated memory is much larger than necessary. In both situations, we can change the
memory size already allocated with the help of function realloc( ). Its syntax is as
If the original allocation is done by the
statement, ptr=malloc(size);
then reallocationof space may be done by the statement
ptr=realloc(ptr,newsize);
This function allocates a new memory space of new size to the pointer variable ptr and
returns a pointer to the first byte of new memory block and on failure the function return
NULL.
/* Program to read marks obtained by dit.student & calculate sum & average using pointer */
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
main( )
{
int n, i;
float *p, sum=0,
avg; clrscr( );
printf(“\n How Many Students
arethere?\t”); scanf(“%d”,&n);
printf(“\n Enter marks of each students\n”);
p=(float*)malloc(n*sizeof(float));
for(i=0; i<n; i++)
{
scanf(“%f”,(p+i));
sum+=*(p+i);
Er. Arun Kumar Yadav, 128
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
}
avg=sum/n;
printf(“The average marks of”);
for(i=0; i<n; i++)
printf(“ % .2f \t ” , *( p + i));
printf(“ % .2f \t is ” , avg);
free(P);
getch( );
}
output:
How many students are there? 5
Enter marks of each student
45.5 56 89 90.5 47
The average marks of 45.5, 56.00, 89.00, 90.50, 47.00 is 65.00
/* write a pg to read an array of n integers using dynamic memory allocation and display the
largest and smallest element */
int main( )
{
int n, i;
int*num,max,min;
clrscr( );
printf(“\n enter number of elements in our array = ”);
scanf(“%d”,&n);
num = (int*)calloc(n,sizeof(int));
printf(“\nEnter%d integers=”,n)
for(i=0, i<n; i++)
scanf(“%d”, num+i);
max=*num;
min=*num;
for(i=0; i<n; i++)
{
if(max<*(num+i))
max=*(num+i);
if(min>*(num+i))
min=*(num+i);
}
printf(“\n the maximum
number=%d”,max); printf(“\n the minimum
number=%d”,min); getch( );
return( );
}
output:
Enter numbers of element in our array = 5
Enter 5 integers = 12 67 89 34 32 The maximum
number = 89
The minimum number = 12
Some Important Questions:
3.Write a program to calculate sum of all number in a given matrix using pointer.
4.Defien an array and a pointer. How are they related?
5 What is a pointer? How is a pointer variable different from an ordinary variable?
6.Write a program to read 10 numbers and sort them in ascending order using pointer.
7.Write short notes on : Dynamic memory allocation
8.Write a function using pointers to add two matrices.
9.
10.What does p, &p and *p represents if ‘p' is declared as integer pointer?
Chapter – 10
Structure and Union
Structure:
Structure is a collection of data item. The data item can be different type, some can be
int, some can be float, some can be char and so on. The data item of structure is called
member of the structure.
In other words we can say that heterogeneous data types can be grouped to form a
structure. In some languages structure is known as record.
The different between array and structure is the element of an array has the same type
while the element of structure can be of different type. Another different is that each element
of an array is referred to by its position while each element of structure has a unique name.
In above section, we have studied about how we declare structure but have not created
the structure variable. Note that the space in the memory for a structure is created only when
the structure variable are defined.
var2 name
roll_no
branch
semester
var3 name
roll_no
branch
semester
Initialization of structure:
A structure is initialized like other data type in C. The values to be initialized must
appear in order sa in the definition of structure within braces and separated by commas. C
doesnot allow the initialization of individual structure member within its definition. Its syntax
is
struct structure_name structure_variable = {value1, value2, value3 _ _ _ _ valuen}
/* Create a structure named student that has name, roll, marks and remarks as members.
Assume appropriate types and size of member. WAP using structure to read and display the
data entered by the user */
# include <stdio.h>
main( )
{
struct student
{
char name[20];
int roll;
float marks;
char remark;
};
struct student
s; clrsc( );
printf(“enter name: \t”);
gets(s.name); printf(“In
enter roll:\t”);
scanf(“%d”, &s.roll);
printf(“\n enter marks: \t”);
scanf(“%f”, &s.marks);
printf(“enter remarks p for pass or f for fail: \t”)
s.remark = getch( )
printf(“\n\n The student’s information is \n”);
printf(“Student Name ItItIt Roll It Marks It Remarks”);
printf(“\n - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
\n”); printf(“%s\t\t%d\t%.2f\t%c”, s.name, s.roll, s.marks, s.remark);
getch( );
}
output:
enter name: Ram Singh
enter roll : 45
entr marks : 89
Er. Arun Kumar Yadav, 134
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
Array of Structure:
Like array of int, float or char type, there may be array of structure. In this case, the array will
have individual structure as its elements. For example:
struct employee
{ char name[20];
int empid;
float salary;
} emp[10];
Where emp is an array of 10 employee structures. Each element of the array emp will contain
the structure of the type employee. The another way to declare structure is
struct employee{ char
name[20]; int
empid; float
salary;
};
struct employee emp[10];
/* Create a structure named student that has name, roll, marks and remarks as members.
Assume appropriate types and size of member. Use this structure to read and display records
of 5 student */
main()
{
struct student
{charname[30];
int roll;
float marks;
char remark;
};
struct student st[5];
int i; clrscr(
);
for(i=0; i<5; i++)
{
Marks: 27
Remarks: F
The Detail Information is:
Student Name Roll Marks Remarks
--------------------------------------------------------------
Ram 20 89 P
Shyam 21 46 P
Bikash 12 97 P
Jaya 23 87 P
Nisha 24 27 F
/* Create a structure named date that has day, month and year as its members. Include this
structure as a member in another structure named employee which has name, id, salary, as
other members. Use this structure to read and display employee’s name, id, dob and salary *|
#include<stdio.h>
void main( )
{
struct date
{
int day;
int month;
int year;
};
struct employee
{
char name[20];
int id;
struct dat dob;
float salary;
} emp;
printf(“Name of Employee: \t”);
scanf(“%s”, emp.name);
printf(“\n ID of employee: \t”);
scanf(“%d”, & emp.id); printf(“\n
Day of Birthday: \t”);
scanf(“%d”, &emp.dob.day);
printf(“\n month of Birthday: \t”);
scanf(“%d”, &emp.dob.month);
printf(“\n Year of Birthday: \t”);
scanf(“%d”, &emp.dob.year);
printf(“salary of Employee: \t”);
scanf(“%d”, &emp.salary);
printf(“\n\n The Detail Information of Employee”);
printf(“\n Name \t id \t day \t month \t year \t salary”);
printf(“\n - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - n”);
printf(“%s\t%d\t%d\t%d\t%d\t%.2f”,emp.name,emp.id,emp.dob.day, emp.dob.month,
emp.dob.year, emp.dob.salary);
}
output:
Name of Employee : Teena
Id of Employee : 2001
Day of Birthday : 10
Month of Birthday : 10
Year of Birthday : 1987
Salary of Employee : 12000
void main( )
{
struct employee
{ char nam[20];
char Address[20];
float salary;
int ID;
};
int, i, j ;
float temp;
struct emp[5];
clrsc( ); printf(“enter5employee Information: “);
for(i=0; i<4; i++)
{ for(j=i+1; j<5; j++)
{if(emp[i].salary<emp[j].salary)
{temp = emp[i].salary; emp[i].salary = emp[j].salary; emp[j].salary =
temp;} printf(“Information of 3 employees having highest salary: In”);
printf(“\nName\t\t\tAddress\t\tSalary\t\D\t\n”);
printf(“\n - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n’);
for(i=0, i<3; i++)
{ printf(“%s\t\t%s\t\t%.2f\t%d”, emp[i].Name, emp[i].Address, emp[i].Salary,
emp[i].ID)
}
getch( )
}
PU2007
/* Create a user defined array structure student record having members physics, chemistry
and mathematics. Feed the marks obtained by three students in each subjects and calculate
the total marks of each student */
void main( )
{ struct student
{int physics;
int chemistry;
int mathematics;
int total;
};
struct student std[3]; int i;
printf(“Enter the marks in physics, chemistry and mathematics of 3 student:
”); for(i=0; i<3; i++)
{ printf(“Marks of students %d”, i+1);
scanf(“%d%d%d”, std[i].physics, std[i].chemistry, std[i].mathematics);
#include<stdio.h>
#include<conio.h>
void main( )
{
struct book;
{char name[20];
intpages;
float
price; };
struct book b, *p;
clrscr( );
printf(“Enter Book’s Name: \t”);
gets(b.name);
printf(“\n Number of pages: \t”);
scanf(“%d”, &b.pages);
printf(“\n price of the book:\t”);
scanf(“%+”, &b.price),
p = &b;
printf(“\n \n Book Information Using with arrow operator”);
printf(“\n Book Name=%s\t Pages=%d\t price=%.2f, p->name, p-> pages, p-
>price); printf(“\n\n Book Information using pointer with * operator”);
printf(“\n Book Name=%s\t Pages=%d\t price=%.2f”, (*p).name, (*p).pages,
(*p).price);
printf(“\n\n Book Information using structure variable (i.e. dot operation)”);
printf(“In Book Name=%s\t Pages=%d\t Price=%.2f”, b.name, b.pages, price);
getch( );
}
Output:
Enter Book’s Name : Let Us C
Nuber of Pages : 540
Price of the Book : 320.6
Book Information Using Pointer with arrow-operator
Book Name=Let Us C Pages=540 Price=320.60
Book Information Using Pointer with * operator.
Book name=Let Us C Pages=540 Price=320.6
Book Information Using Structure variable(i.e. dot operator)
Book Name=Let Us C Pages=540 Price=320.6
/* WAP which reads two complex numbers and then perform multiplication of these two
n
*/ So| : If two complex no. are a1+ib1 and a2+ib2 then multiplication is
(a1+ib1)*(a2+ib2)
2
a1a2 + i b1b2 + a1b2i + a2b1i
(a1a2 – b1b2) + (a1b2 +
2
a2b1)i (because i = -1)
#include<stdio.h>
#include<conio.h>
struct complex
{ float realpart;
float imagpart; };
struct complex mul ( struct complex, struct complex);
void main( )
Er. Arun Kumar Yadav, 142
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
{
struct complex a, b, c ;
clscr( );
printf(“Enter firstcomplex no.: \n”);
printf(“Enter real part:\t”);
scanf(“%f”, &a.realpart);
printf(“Enter Image part: \t”);
scanf(“%f”, &a.imagpart);
printf(“Enter Second Complex no.:\n”);
printf(“Enter real part:\t”);
scanf(“%f”, &b.realpart);
printf(“Enter imag part: \t”);
scanf(“%f”, &b.imagpart);
c = mul(a,b);
printf(“First no. is: %f+i%f\n”, a.realpart, a.imagpart);
printf(“Second no. is: %f+i%f\n”, b.realpart, b.imgpart)
printf(“Multiplication is: %f+i%f\n”, c.realpart, c.imagpart);
getch( );}
structcomplex mul (struct complex a, struct complex b)
{ structcomplex c;
c.realpoint = (a.realpoint * b.realpart) – (a.imagpart * b.imagpart);
c.imagpart = (a.imagpart * b.realpart) + (b.imagpart * a.realpart);
return(C);
}
output:
Enter first complex no. :
Enter real part : U2
Enter image part : 4
Enter Second Complex no. :
Enter real part : U3
Enter image part : 5
First no. is : 2.000000 + i4.000000
Second no. is : 3.000000 + i5.000000
Multiplication is : -14.000000 +i22.00000
The declaration of union is same as the structure. Only difference is in place of struct
keyword the union keyword is used. The accessing of union member is also same like
structure member. For example:
Union data { int a;
float b;
};
The union variable are declared like structure variable. For
example: Union data d1, d2;
If we write the
statement d1.a = 10;
Then that means the field a is valid but we want to print the value of b after above
assignment, the value is wrong because a is valid only. After above assignment if we write
d1.b = 20.5; now b is valid not a i.e. only that field value is valid in which we have assigned
value currently.
/* Create a union named student that has roll and marks as member one at a time and display
the result one at a time */
void main( )
{ union student
{
int roll;
float marks;
};
union student st;
st.roll = 455;
printf(“\nRoll=%d”,
st.roll); st.marks = 80;
printf(“\nMarks=%f”, st.marks);
}
output:
Er. Arun Kumar Yadav, 144
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
Roll=455
Marks=80.000000
Structure Union
(1) Each member within a structure is (1) All members within union share the
assigned its own unique storage. It takes same storage area of computer memory.
more memory than union. It takes less memory than structure.
(2) The a\m of memory required to store a (2) The a\m of memory required to store an
structure is the sum of the size of all union is same as member that occupies
members. largest memory.
(3) All the structure members can be (3) Only one member of union can be
accessed at any point of time. accessed at any given time.
(4) Structure is declared as (4) Union is declared as
struct student union student
{ char name[20]; { char name[20];
float marks; int roll;
} st; float mark;
} st;
5.Write a program to read several different names , roll, address, percentage and display
rd
name who has score the 3 highest.
6 Create a user defined array structure student record having member's physics, chemistry
and mathematics. Feed the marks obtained by three students in each subjects and calculate
the total of each student.
Chapter – 11
Data Files
High Low
Text Binary
{
- - - - - -;
- - - - - -;
---- - -
; } FILE;
A file pointer is a pointer to a structure of type FILE. Whenever a file is opened, a
structure of type FILE is associated with it, and a file pointer that points to this structure
identifies this file. The function fopen( ) is used to open a file.
1. “w” (write):
If the file dosen’t exist then this mode creates a new file for writing, and if the file
already exists, then the previous data is erased and the new data entered is written to the file.
2. “a” (append):
If the file doesn’t exist then this mode creates a new file, and if the file already exists
then the new data entered is appended at the new data entered is appended at the end of
existing data. In this mode, the data existing in the file is not erased as in “w” mode.
3. “r” (read):
This mode is used for opening an existing file for reading purpose only. The file to be
opened must exist and the previous data of file is not erased.
The file that was opened using fopen( ) function must be closed when no more
operations are to be performed on it. After closing the file, connection between file and
program is broken. Its syntax is
fclose(ptr_variable);
On closing the file, all the buffers associated with it are flushed and can be available for
other files. For example:
fclose(fp1);
fclose(fp2);
|* Program to open the file “text.txt” created above, read its content & display to the screen *|
#include <stdio.h>
Void main( )
{
FILE * fp ;
char s[100]
fp = fopen(“c:\\test.txt”,
“r”); if (fp = = NULL)
{
printf(“In file can not be opened”);
exit( );
}
fgets(s, fp);
printf(“in the text from file is: \t%s”,
s); fclose(fp);
getch( );
}
OUTPUT: The text from file is Welcome to Eastern College of Engineering.
|* Program that opens a file and copies all its content to another file. Take source &
destination file from user *|
#include <stdio.h>
Void main( )
{
FILE *fsource, *fdest;
char, ch, source[20], dest[20] ;
printf(“In Enter source file name: \t”);
gets(source);
printf(“Enter destination file name:
\t”); gets(dest)
fsource = fopen(source, “r”);
if(fsource = = NULL)
{
printf(“\n source file can not be opened”),
exit( );
}
fdest = fopen(dest, “w”);
if (fdest = = NULL)
{
printf(“\n Destination file can’t be created”),
exit( );
}
while(( ch = fgetc(source)! = EOF)
{
fputc(ch, fdest);
}
printf(“Sucessfully copied!”);
fclose(fsource); fclose(fdest);
getch( ):
}
sequentially, if we want to acess a particularly record. Random acess takes takes less time
than the sequential acess.
C supports these functions for random acess file processing:
- fseek( )
- ftell( )
- rewind( )
fseek( ):
This function is used for setting the file position pointer at the specified byte. The syntax is
int fseek(FILE *fp, long displacement, int origin)
where fp is file pointer, displacement is long integer which can be positive or negative and it
denotes the number of bytes which are skipped backward (if negative) or forward (if positive)
from the position specified in the third argument.
The third argument named origin is the position relative to which the displacement
takes place. It can take one of these three values:
Constant Value Poition
SEEK_SET 0 Beginning of file
SEEK_CURRENT 1 Current position
SEEK_END 2 End of File
rewind( ):
This function is used to move the file position positive to the beginning of the file syntax
rewind(File *fp)
using rewind(fp) is equivalent to fseek(fp, OL, O)
ftell( ):
This function returns the current position of the file position pointer. The value is counted
from the beginning of the file. The syntax is
long ftell(FILE *fp);
Some Programs:
/* Program to write some text “welcome to my college” to a data file in binary mode. Read its
content and display it */
#include <stdio.h>
Void main( )
{ FILE *fptr;
char c;
fptr = fopen(“test.txt”,
“w+b”) if(fptr = = NULL)
{ printf(“\n File can not be created”);
fputs(“welcome to my college”, fptr),
rewind(fptr);
Er. Arun Kumar Yadav, 154
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
® |* Create a structure named employee having numbers: empName, age and salary. Use this
structure to read the name, age and salary of employee and write entered information to a file
employee.dat in D:\ drive *|
#include <studio.h>
void main( )
{
struct employee
{ char empName[20];
int age;
float salary;
};
struct employee
emp; FILE *fptr ;
ftpr = fopen(“d:\\employee.dat”,
“wb”); if(fptr = = NULL)
{ printf(“File can not be entered”);
exit( );
}
printf(“Employee Name: It”);
scanf(“%s”, emp. empName);
printf(“employee age: It);
scanf(“%d”, &emp.age);
printf(“salary of the employee:
It”); scarf(“%f”, & emp.salary);
printf(“In writing this information to a file _ _ _ In”);
fwrite(&emp, sizeof(emp), 1, fptr);
getch( );
}
|*Create a structure named student that has name, roll and marks as members. Assume
appropriate types and size of member. Use this structure to read and display records of 3
students. Write an array of structure to a life & then read its content to display to the screen *|
Void main( )
{ struct student
{Char name[30]; int roll; float marks;};
struct student s[3], st[3];
int i,
float tempMarks;
FILE *fptr ;
fptr = fopen(“d:\\student.txt”.
“w+b”) if(fptr = = NULL)
{ printf(“File can’t be
created.”); exit( );
}
for(i=0, i<3; itt)
{ printf(“\n Enter Information of student No %d \n”, i+1);
printf(“Name: \t”); scanf(“%s”, s[i].name);
printf(“\n Roll:\t”); scanf(“%d”, & s[i].roll);
printf(“\n Marks: \t”); scanf(“%f”, & tempMarks);
s[i].marks = tempMarks;
}
printf(“\n working Information to file _ _ _ _ _ \n”);
fwrite(&s, size of (s), 3, fptr);
rewind(fptr);
printf(“\n reading same content from file _ _ _ _ _ \n”);
fread( &st, size of (st), 3, fptr);
printf(“\n student Name \t Roll \t Marks”);
printf(“\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ \n”)
for(i=0, i<3; i++)
printf(“%s\t\t%d\t%.2f \n”, st[i].name, st[i].roll, st[i].marks);
fclose(fptr);
getch( );
}
# In Program ® read employee information again and again until user wants to add more
employees. Finally, write a program to search information of a particular employee from the
file.
#include <stdio.h>
#include <string.h>
void main( )
Er. Arun Kumar Yadav, 156
Lecturer, Eastern College of Engineering, Biratnagar
Computer Programming in C
{ struct employee
{char name[20]; int age; float
salary; };
structemployee
emp; FILE *fptr;
char yes_no, name[15];
int dataFound = 0;
clrscr( );
fptr = fopen(“C:\\employee.txt”,
“w+b”), if(fptr = = NULL)
{ printf(“File can not be
created”); exit( );
}
Do { printf(“employee Name: \t”);
scanf(“%s”, & emp.name);
printf(“employee age: \t”);
scanf(%d”, &emp.age);
printf(“salary of the employee: \t”);
scanf(“%f”, &emp.salary);
fwrite(&emp, size of (emp), 1,fptr0,
printf(“Do you want to add another employee? Press Y or Y: it);
fflush(stdin);
yes_no = getchar( );
3 while(yes_no = = ‘y’ || yes_no = = ‘y’);
printf(“Enter the name of employee which is to be searched”)
fflush(stdin);
gets(name);
rewind(fptr);
while(fread (&emp, size of (emp), 1 fptr) = = 1)
{ if(strcmp(emp.name, name) = = 0)
{dataFound = 1;
printf(“Name \t Age \t \t Salarly \n”)
printf(“\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __ _ _ _ _ _ _ _ \n”)
print(“%s\t%d\t%.2f”,emp.name, emp.age, emp.salary);
}}
If(dataFound = = 0)
print(“\n Matching data not
found.”); getch( );
}
Chapter – 12
Graphics
The C graphics function fall into two categories those that work in text mode and those
that work in graphics mode.
The text mode functions are concerned with placing text in certain area of screen. They
work with any graphics monitor and adapter.
The graphics mode function require a graphics monitor and adapter card such as CGA,
EGA or VGA. Graphics mode function allow us to draw dots, lines and shapes (like circle,
rectangle, etc.), add color to lines and area and perform many other graphics related activities.
In order to perform graphics related activities, we include graphics.h.
clrscr( ) : This function erases the text window. Its syntax is clrscr( );
window( ) : This fuction takes four integer arguments that determine the left, top, right and
bottom coordinates of the window. The general syntax:
Window (left, top, right, bottom)
gotoxy( ) : The gotoxy( ) library function points the cursor position within a text window;
its syntax is gotoxy(x,y);
text color( ) function: It is used to give color of any text. The syntax of text color( ) is text
color(color constant)
textbackground ( ) function: This function is used to set background color of each character.
The syntax is
textbackground (color constant);
Some color constants:
Color No. 0 1 2 3 4 5 6 Color name
Black Blue
Green Cyan
Red
Magenta
Brown, etc.
Downloaded from
www.bhawesh.com.np 159
Downloaded from www.bhawesh.com.np
C offers certain graphics driver and these are the files with .BGI extension. They are
stored in subdirectory BGI of TC directory (particularly C:\\T\\BGI). Depending on what
adapter is used, one of these driver gets selected. The some constants defined in graphics .h
file for this argument are DETECT(=0), CGA(=1), EGA(=3), VGA(=9),etc.
Graphics Mode:
In text mode we are restricted to display text or graphics character but in graphics
mode we can display points, lines and compleax shapes. In text mode, we can address only
2000 location (80*25) but in graphicsmode we can address individual pixel or dots on the
screen. This gives we much finer resolution.
For example in a 640x480 VGA mode we can address 307,200 pixels. If we want to
use graphics mode functions then we have to add graphics .h header file but for text mode
function no need of graphics .h header file. If we want to use the graphics mode functions
then our first job is to set our computer mode to graphics mode.
Function initgraph( ) sets our mode for graphics work. The syntax of initgraph( )
function is
initgraph(& driver, & mode, path of bgi files), where driver and mode both are integer
type and path for bgi files means where our .BGI files are in disk.
If we want to set the mode of computer is graphics mode by initgraph ( ) function then
we have to write the following set of statements:
intdriver, mode;
driver=DETECT;
initgraph(& driver, & mode, “C:\\tc\\bgi”)
we are assuming that our .bgi are in sub directory C:\tc\bgi therefore the path of bgi
files is written in initgraph ( ) function like:
“C:\\tc\\bgi”
The statement driver=DETECT will check our hardware and select appropriate values
for argument to function initgraph( )
Some Graphics Mode Graphic Functions:
putpixel( ): Plot a point with specified color. Its syntax is
Putpixel (int x, int y, int color),
line( ): The line ( ) function can draw a line. The syntax of line( ) function
is: line(x1, y1, x2, y2),
where x1, y1, x2, y2 are integer type and they represent the coordinate (x1, y1) and (x2, y2).
The above command draws a line joining two points with coordinates (x1, y1) and (x2, y2).
lineral( ): the function lineral (x, y) draws a line joining the current cursor position and a
point at a distance of x in the horizontal and y in vertical direction.
Note that x and y both are integer type.
lineto( ): The function lineto (x, y) draws a line joining the current cursor position and a point
with coordinates x and y.
Where x and y both are integer type.
moveto( ): The function moveto (x, y) moves the cursor position to a point with coordinates x
and y.
moveral( ): The function moveral (x, y) moves the current cursor position a relative distance
of x in x-direction & a relative distance of y in y-direction.
rectangle( ): The function rectangle (x1, y1, x2, y2) draw rectangle where point (x1, y1) is left
top corner point of rectangle and point (x2, y2) is right bottom corner.
( x1, y1)
(x2, y2)
circle( ): The function circle (x, y, r) draws a circle of radius r. The coordinates of the centre
of the circle is (x, y).
r
(x, y)
arc( ): Function arc (x, y, a1, a2, r) draws an arc on the screen starting from angle a1 to a2.
The radius of the circle of which the arc forms a part is r and x, y are its centre coordinates.
For example:
arc (100, 45, 90, 30) ;
Above statement draws an arc like
30
90°
45°
100, 100
ellipse( ): The function ellipse (x1, y1, c1, c2, a1, a2, x, y) draws an ellipse of centre (c1, c2).
The a1 and a2 are start and end angle of the arc x and y are the x-axis and y-axis radii.
a2
a1
c1, c2
Er. Arun Kumar Yadav, 162 Lecturer, Eastern College of
Engineering, Biratnagar
Computer Programming in C
drawpoly( ): Function drawpoly (int n, int p[ ]); draws n vertices of polygon. P is an array of
integer numbers which gives x and y co-ordinates of the points to be joined. To draw a closed
polugon with n vertices, we must pass n+1 co-ordinates.
Int P={10, 75, 50, 25, 100, 25, 140, 75, 100, 125, 50, 125, 10, 75};
Drawpoly (7, P);
setlinestyle( ): This function can select different style of line. Its syntax is
setlinestyle (int style, patern, thickness)
The type of style and thickness is int type and the type of pattern is unsigned int type.
Where style are SOLID_LINE, DOTTED_LINE, CENTRE_LINE, DASHED_LINE,
USERBIT_LINE or integer number 0, 1, 2, 3, 4 respectively. The pattern is required only if
user defined style (USERBIT_LINE) is used. We can specify it to zero. The thickness
parameter can have value NORM_WIDTH or THICK_WIDTH or integer value 1 or 3
respectively.
2007 PU
|* Program to draw 3 concentric circle having radius 25m 50 and 75 units
*| #include <graphics.h>
main( )
{
int gd = DETECT,
gm; clrscr ( );
initgraph ( &gd, &gm, “C:\\tc\\bgi”);
setcolor (3);
circle (150, 150, 25);
circle (150, 150, 50);
circle (150, 150, 75);
getch ( );
closegraphc ( );
}
2.Write a program using graphics to draw a rectangle and a circle. (PU2003 BACK)
3.Write a program in C to draw a circle, a rectangle and an ellipse. (PU2005)
4.Write a program in C that can display a circle and a rectangle. Choose centre and radius of
the circle as well as coordinates of the rectangle on your own. (PU2006)
5.Write a program to draw 3 concentric circles having radius 25, 50 and 75 units. (PU2007)
References: