View
129
Download
2
Category
Tags:
Preview:
Citation preview
UNIT-1
INTRODUCTION TO C
C is a relatively minimalist programming language that operates close to the hardware, and is more similar
to assembly language than most high-level languages are. Indeed, C is sometimes referred to as "portable
assembly," reflecting its important difference from low-level languages such as assembly languages: C
code can be compiled to run on almost any computer, more than any other language in existence, while
any given assembly language runs on at most a few very specific models of computer. For these reasons C
has been called a medium-level language.
We briefly list some of C's characteristics that define the language and also have lead to its popularity as a
programming language. Naturally we will be studying many of these aspects throughout the course.
Small size
Extensive use of function calls
Loose typing -- unlike PASCAL
Structured language
Low level (BitWise) programming readily available
Pointer implementation - extensive use of pointers for memory, array, Structures and functions
C has now become a widely used professional language for various reasons.
It has high-level constructs.
It can handle low-level activities.
It produces efficient programs.
It can be compiled on a variety of computers.
Its main drawback is that it has poor error detection which can make it off putting to the beginner.
However diligence in this matter can pay off handsomely since having learned the rules of C we can break
them. Not many languages allow this. This if done properly and carefully leads to the power of C
programming.
A Brief History of C
C is a general-purpose language which has been closely associated with the UNIX operating system for
M V B REDDY GITAM UNIVERSITY BLR
which it was developed - since the system and most of the programs that run it are written in C.
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards. The
influence of BCPL on C proceeded indirectly through the language B, which was written by Ken Thompson
in 1970 at Bell Labs, for the first UNIX system on a DEC PDP-7. BCPL and B are "type less" languages
whereas C provides a variety of data types.
In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C Programming Language
by Kernighan & Ritchie caused a revolution in the computing world
In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern,
comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI C", was completed late
1988.
UNIX developed c. 1969 -- DEC PDP-7 Assembly Language
BCPL -- a user friendly OS providing powerful development tools developed from BCPL. Assembler
tedious long and error prone.
A new language ``B'' a second attempt. c. 1970.
A totally new language ``C'' a successor to ``B''. c. 1971
By 1973 UNIX OS almost totally written in ``C''
Introduction
M V B REDDY GITAM UNIVERSITY BLR
Now a days computers are playing very vital role in each and every field of problem solving. The
communication medium between a computer and a human being is a typical 'language' i.e.. humans arc able
to communicate with the computer system in some form of language. There are basically three types of
languages viz.. Machine Understandable Language. Assembly Level Language and High Level Language. There
are number of high level languages developed in the past three decades like Fortran, Pascal, Basic. C
Language etc. Clearly, no other language has had so much of influence in the computing as 'C'-language.
Evolution of 'C'- as a programming language has made application development very easy.
ALGORITHM
( An algorithm is a method of representing the step-by-step procedure for solving a problem. An algorithm is \
cry useful for finding the right answer to a problem or to a difficult problem by breaking the problem into
simple cases.
An algorithm must possess the following properties:
i) Finiteness : An algorithm should terminate in a finite number of steps.
ii) Definiteness : Each step of the algorithm must be precisely stated.
iii) Effectiveness : Each step must be effective, in the sense that it should be easily convertible into program
statement and can be performed exactly in a finite amount of time.
i\) Generality : The algorithm should be complete in itself so that it can be used to solve all problems of a
given type for any input data.
v) Input/Output : Each algorithm must take zero, one or more quantities as input data and
yield one or more output values.
An algorithm can be written in English like sentences or in any standard representation^. Sometimes,
algorithm written in English like language is called Pseudo Code.
Flow chart
M V B REDDY GITAM UNIVERSITY BLR
Flow chart is diagrammatic representation of an algorithm. It is built using different types of boxes of symbols. The operation to be performed is written in the box. All symbols are inter connected by arrows to indicate the flow of information and processing.
Following are the standard symbols used in drawing flowcharts.
M V B REDDY GITAM UNIVERSITY BLR
Oval Terminal Start/stop/begin/end symbol
Parallelogram Input/Output Making data available for processing (input) or
recording of the processed
information(output)
Rectangle Process Any processing to be performed. An
assignment operation normally represented by
this symbol
Diamond Decision Decision or switching type of operations that
determines which of the alternative paths is to be
followed.
Circle Connecter Used for connecting different parts of flow
chart.
Arrow Flow Joins two symbols and also represents executions flow.
Bracket with broken line
Annotation Descriptive comments or explanations
Double sided rectangle
Predefined process
Modules or subroutines given elsewhere
Different steps followed to develop a program
The following steps are used in sequence for developing an efficient program:
Specifying the problem statement
M V B REDDY GITAM UNIVERSITY BLR
Designing an algorithm Coding Debugging Testing and validating Documentation and maintenance
Introduction to C
C is a programming language developed at AT& T’s Bell Laboratories of USA in 1972.It was designed and written by Dennis Ritchie. C has the features of both BASIC and PASCAL.
As a middle language, C allows the manipulation of bits, bytes and addresses the basic elements with which computer functions.
C’s code is very portable, in the sense that it is easy to adapt software written for one type of computer or operating system to another type.
C has very small keywords. Set includes extensive library functions which enhances the
C TOKENS
Smallest individual units in a C program are known as C tokens. C has six tokens as given
below:
C tokens
Keywords identifiers constants strings operators special symbols
Keywords
Keywords are the tokens used in C program which have predefined meaning and these meanings cannot be
changed by the programmer. There are 32 keywords. They are also called as Reserved words. We cannot use them
for any other purpose.
M V B REDDY GITAM UNIVERSITY BLR
Standard key words
are
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Running C Program
Developing a program in a compiled language such as C requires at least four steps:
1. editing (or writing) the program 2. compiling it 3. linking it 4. executing it
We will now cover each step separately.
Editing
You write a computer program with words and symbols that are understandable to human beings. This is
the editing part of the development cycle. You type the program directly into a window on the screen and
save the resulting text as a separate File. This is often referred to as the source File (you can read it with
the TYPE command in DOS or the cat command in unix). The custom is that the text of a C program is
stored in a File with the extension .c for C programming language
M V B REDDY GITAM UNIVERSITY BLR
Compiling
You cannot directly execute the source File. To run on any computer system, the source File must be
translated into binary numbers understandable to the computer's Central Processing Unit (for example, the
80*87 microprocessor). This process produces an intermediate object File - with the extension .obj, the .obj
stands for Object.
LinkingThe first question that comes to most peoples minds is Why is linking necessary? The main reason is that many compiled languages come with library routines which can be added to your program. Theses routines are written by the manufacturer of the compiler to perform a variety of tasks, from input/output to complicated mathematical functions. In the case of C the standard input and output functions are contained in a library (stdio.h) so even the most basic program will require a library function. After linking the file extension is .exe which are executable files.
Executable filesThus the text editor produces .c source files, which go to the compiler, which produces .obj object files, which go to the linker, which produces .exe executable file. You can then run .exe files as you can other applications, simply by typing their names at the DOS prompt or run using windows menu.
Using Microsoft C Edit stage:
Type program in using one of the Microsoft Windows editing packages.
Compile and link:
Select Building from Make menu. Building option allows you to both compile and link in the same option.
Execute:
Use the Run menu and select Go option.
Errors:
First error highlighted. Use Next Error from Search menu for further errors if applicable.
If you get an error message, or you find that the program doesn't work when you finally run it (at least not
in the way you anticipated) you will have to go back to the source file - the .c file - to make changes and go
through the whole development process again!
Using Unix
Please note that Unix is a case sensitive operating system and files named firstprog.c and FIRSTPROG.c
are treated as two separate files on these system. By default the Unix system compiles and links a
program in one step, as follows:
cc firstprog.cThis command creates an executable file called a.out that overwrites any existing file called a.out.
Executable files on Unix are run by typing their name. In this case the program is run as follows
a.outTo change the name of the executable file type:
cc -o firstprog firstprog.cThis produces an executable file called firstprog which is run as follows:
firstprogOn all Unix systems further help on the C compiler can be obtained from the on-line manual. Type man cc
M V B REDDY GITAM UNIVERSITY BLR
Identifiers
Identifiers refer to the names of variables, constants, functions and arrays.
Identifiers are user defined names and consist of sequence of letters or digits, with letter or underscore as first
character.
Both lower case and upper case letters can be used for identifiers.
Underscore can be used to link words of identifier
Identifiers can be of any length
Some valid identifiers :
max
ist_of_ words.
a123 sum etc.
Invalid identifiers :
12 abc
Maxi mum { there is a space between Maxi and mum}
etc.
Constants
Constants refer to fixed values that do not change during execution of program. Several types of constants are:
Constants
M V B REDDY GITAM UNIVERSITY BLR
Numeric Character
Integer Float single character constant String constant
Octal Hexadecimal Decimal
Operators Available in C
Operators are C tokens which can join together individual constants, variables array elements and function references. Operators act upon data items called as operands.
C operators are classified into the categories
Arithmetic operators Relational operators Logical operators Assignment operators Increment and decrement operators Bitwise operators Special operators
Variables and Data Type
The first thing you need to know is that you can create variables to store values in. A variable is just a
named area of storage that can hold a single value (numeric or character). Every variable has a name and
M V B REDDY GITAM UNIVERSITY BLR
a value.
The name identifies the variable, the value stores data. There is a limitation on what these names can be.
Every variable name in C must start with a letter, the rest of the name can consist of letters, numbers and
underscore characters. No Space allowed in variable name. C recognizes upper and lower case characters
as being different. Finally, you cannot use any of C's keywords like main, while, switch etc as variable
names.
It demands that you declare the name of each variable that you are going to use and its type, or class,
before you actually try to do anything with it.
There are five basic data types associated with variables
int - integer: a whole number.
float - floating point value: ie a number with a fractional part.
double - a double-precision floating point value.
char - a single character.
void - valueless special purpose type which we will examine closely in later sections.
Integer Number Variables
The first type of variable we need to know about is of class type int - short for integer. An int variable can
store a value in the range -32768 to +32767. You can think of it as a largish positive or negative whole
number: no fractional part is allowed. To declare an int you use the instruction: int variable name;
For example:
int a;
declares that you want to create an int variable called a.To assign a value to our integer variable we would
use the following C statement.
a=10;
The C programming language uses the "=" character for assignment. A statement of the form a=10;
should be interpreted as take the numerical value 10 and store it in a memory location associated with the
integer variable a. The "=" character should not be seen as an equality otherwise writing statements of the
form:
a=a+10;
This statement should be interpreted as take the current value stored in a memory location associated with
the integer variable a; add the numerical value 10 to it and then replace this value in the memory location
associated with a.
Decimal Number Variables
As described above, an integer variable has no fractional part. Integer variables tend to be used for
counting, whereas real numbers are used in arithmetic. C uses one of two keywords to declare a variable
that is to be associated with a decimal number: float and double. They are each offer a different level of
M V B REDDY GITAM UNIVERSITY BLR
precision as outlined below.
float
A float, or floating point, number has about seven digits of precision and a range of about 1.E-36 to
1.E+36. A float takes four bytes to store.
double
A double, or double precision, number has about 13 digits of precision and a range of about 1.E-303 to
1.E+303. A double takes eight bytes to store.
For example:
float total;
double sum;
To assign a numerical value to our floating point and double precision variables we would use the following
C statement.
total=0.0;
sum=12.50;
Before you can use a variable you have to declare it. As we have seen above, to do this you state its type
and then give its name. For example, int i; declares an integer variable. You can declare any number of
variables of the same type with a single statement.
For example:
int a, b, c;
Here is an example program that includes some of the concepts outlined above. It includes a slightly more
advanced use of the printf function which will covered in detail in the next part of this course:
main()
{
int a,b,average;
a=10;
b=6;
average = ( a+b ) / 2 ;
printf("Here ");
printf("is ");
printf("the ");
printf("answer... ");
printf("\n");
printf("%d.",average);
}
M V B REDDY GITAM UNIVERSITY BLR
Character Variables
C only has a concept of numbers and characters. It very often comes as a surprise to some programmers
who learnt a beginner's language such as BASIC that C has no understanding of strings but a string is only
an array of characters and C does have a concept of arrays which we shall be meeting later in this course.
To declare a variable of type character we use the keyword char. - A single character stored in one byte.
For example
char c;
To assign, or store, a character value in a char data type is easy - a character variable is just a symbol
enclosed by single quotes. For example, if c is a char variable you can store the letter A in it using the
following C statement.
c='A'
Notice that you can only store a single character in a char variable. Later we will be discussing using
character strings, which has a very real potential for confusion because a string constant is written
between double quotes. But for the moment remember that a char variable is 'A' and not "A".
Constants
ANSI C allows you to declare constants. When you declare a constant it is a bit like a variable declaration
except the value cannot be changed.
The const keyword is to declare a constant, as shown below.
int const a = 1;
const int a =2;
The preprocessor #define is another more flexible (see Preprocessor Chapters) method to define constants
in a program.
You frequently see const declaration in function parameters. This says simply that the function is not going
to change the value of the parameter.
The following function definition used concepts we have not met (see chapters on functions, strings,
M V B REDDY GITAM UNIVERSITY BLR
pointers, and standard libraries) but for completenes of this section it is is included here:
void strcpy(char *buffer, char const *string)
Assignment Statement
The easiest example of an expression is in the assignment statement. An expression is evaluated, and the
result is saved in a variable. A simple example might look like
y = (m * x) + c
This assignment will save the value of the expression in variable y.
Arithmetic operators
Here are the most common arithmetic operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Reduction
*, / and % will be performed before + or - in any expression. Brackets can be used to force a different order
of evaluation to this. Where division is performed between two integers, the result will be an integer, with
remainder discarded. Modulo reduction is only meaningful between integers. If a program is ever required
to divide a number by zero, this will cause an error, usually causing the program to crash.
Here are some arithmetic expressions used within assignment statements.
velocity = distance / time; force = mass * acceleration; count = count + 1; C has some operators which allow abbreviation of certain types of arithmetic assignment statements
ShorthandEquivalent
i++; or ++i; i=i+1;i--; or --i; i=i-1;
These operations are usually very efficient. They can be combined with another expression.
x= a *b++; is equivalent to x= a * b, b=b+1;Versions where the operator occurs before the variable name change the value of the variable before
evaluating the expression, so
x=-- i * ( a + b) is equivalent to x= i-1; x= i * (a+ b)
These can cause confusion if you try to do too many things on one command line. You are recommended
to restrict your use of ++ and - to ensure that your programs stay readable.
Shorthand Equivalent
i +=10i -=10
i = i+10i = i-10
M V B REDDY GITAM UNIVERSITY BLR
i *=10 i /=10
i = i*10 i = i/10
Comparison Operator
C has no special type to represent logical or Boolean values. It improvises by using any of the integral
types char, int, short, long, unsigned, with a value of 0 representing false and any other value
representing true. It is rare for logical values to be stored in variables. They are usually generated as
required by comparing two numeric values. This is where the comparison operators are used, they
compare two numeric values and produce a logical result.
C notation Meaning
== Equal to
> Grater Than
< Less Than
>= Grater than or equal to
<= Less than or equal to
!= not equal to
Note that == is used in comparisons and = is used in assignments. Comparison operators are used in
expressions like the ones below.
x == y
i > 10
a + b != c
In the last example, all arithmetic is done before any comparison is made.
Logical Operators
These are the usual And, Or and Not operators
SymbolMeaning
&&
||
!
AND
OR
Not
They are frequently used to combine relational operators, for example
x < 20 && x >= 10
M V B REDDY GITAM UNIVERSITY BLR
In C these logical connectives employ a technique known as lazy evaluation. They evaluate their left hand
operand, and then only evaluate the right hand one if this is required. Clearly false && anything is always
false, true || anything is always true. In such cases the second test is not evaluated.
Not operates on a single logical value, its effect is to reverse its state. Here is an example of its use.
if ( ! acceptable )
printf("Not Acceptable !!\n");
Type conversion
You can mix the types of values in your arithmetic expressions. char types will be treated as int. Otherwise
where types of different size are involved, the result will usually be of the larger size, so a float and a
double would produce a double result. Where integer and real types meet, the result will be a double.
There is usually no trouble in assigning a value to a variable of different type. The value will be preserved
as expected except where.
The variable is too small to hold the value. In this case it will be corrupted (this is bad).
The variable is an integer type and is being assigned a real value. The value is rounded down. This
is often done deliberately by the programmer.
Values passed as function arguments must be of the correct type. The function has no way of determining
the type passed to it, so automatic conversion cannot take place. This can lead to corrupt results. The
solution is to use a method called casting which temporarily disguises a value as a different type.
eg. The function sqrt finds the square root of a double.
int i = 256;
int root
root = sqrt( (double) i);
The cast is made by putting the bracketed name of the required type just before the value. (double) in this example. The result of sqrt( (double) i); is also a double, but this is automatically converted to an int on assignment to root
Conditional Operator: ? :
Syntax of Conditional operators is
M V B REDDY GITAM UNIVERSITY BLR
logical-or-expression ? expression : conditional-expression
The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator
works as follows
The first operand is implicitly converted to bool. It is evaluated and all side effects are completed
before continuing.
If the first operand evaluates to true (1), the second operand is evaluated.
If the first operand evaluates to false (0), the third operand is evaluated.
The result of the conditional operator is the result of whichever operand is evaluated — the second or the
third. Only one of the last two operands is evaluated in a conditional expression.
#include<stdio.h>
void main()
{
int a,b;
printf("Enter value of a);
scanf("%d",&a);
printf("Enter value of b);
scanf("%d",&b);
(a>b)?printf("%d is big",a):printf("%d is big",b);
getch();
}
BITWISE OPERATORS
C has a distinction of supporting special operators known as bitwise operators for manipulation of data at
bit level. These operators are used for testing the bits, or shifting them right or left. Bitwise operators may
not be applied to float or double. Bitwise operators are
OperatorsMeaning
&
|
^
<<
>>
~
bitwise AND
bitwise OR
bitwise exclusive OR
Shift left
Shift right
One's complement More about bitwise operators
User Defined Type Declaration
C support the feature known as type definition that allows user to define an identifier that would represent an exiting data type. The user defined datatype isentifier can later be used to declare variables. It takes the general form.
M V B REDDY GITAM UNIVERSITY BLR
typedef type identifier;
Where type refers to an existing data type may belong to any class of type , including the user defined
ones. Remember that the new type is 'new' only in name , but not the data type. typedef can not create a
new type. Some example of type definition are
typedef int unit; typedef float marks;Here , unit symbolizes int and mark symbolizes folat. They can be later used to declare variables as follows.
units batch1, batch2; marks name1[50], name2[50];Bacth1 and batch2 are declare as int variable and name1[50] and name2[50] are declared as 50 element
of floating point array variables. The main advantage of typedef is that we can create meaningful data type
name for increasing the readability of the program
Another user-defined data type is enumerated data type provided by ANSI standard. It is defined as
follows.
enum identifier { value1,value2,....valuen };
The identifier is user -defined enumerated data type which can be used to declare variable that can have
one of the value enclosed with in the braces ( known as enumeration constant). After this we can declare
variables to be of this new type as below.
enum identifier v1,v2,...vn.The enumerated variable v1,v2,..vn can only have one of the following types are valid;
v1= value3; v3= value1;An example
enum day { Monday, Tuesday,...,Sunday};
enum day week_st, Week_end;
Weel_st= Monday;
week_end= Friday;
if(week_st==Tuesday)
week_end=Saturday;
The compiler automatically assign integer digit beginning with 0 to all the enumeration constants that is ,
the enumeration constant value1 is assign 0, value 1 , and so on. However the automatic assignment can
be overridden by assigning values explicitly to the enumeration constant For example
enum day { Monday=1, Tuesday,...Sunday };
Here, the constant Monday is assigned the value of 1. The remaining constants are assigned values that
M V B REDDY GITAM UNIVERSITY BLR
increase successively by 1.
The definition and deceleration of enumerated variable can be combined in one statement
enum day { Monday,....Sunday} Week_st, Week_end;
Input and Output
One of the advantages of C is that essentially it is a small language. This means that you can write a
complete description of the language in a few pages. It doesn't have many keywords or data types for that
matter. What makes C so powerful is the way that these low-level facilities can be put together to make
higher level facilities.
C supplies a standard package for performing input and output to Files or the terminal. This contains most
of the functions which will be introduced in this section, along with definitions of the datatypes required to
use them. To use these facilities, your program must include these definitions by adding the line This is
done by adding the line
#include<stdio.h>
near the start of the program File. If you do not do this, the compiler may complain about undefined
functions or datatypes.
Character Input / Output
This is the lowest level of input and output. It provides very precise control, but is usually too fiddly to be
useful. Most computers perform buffering of input and output. This means that they'll not start reading any
input until the return key is pressed, and they'll not print characters on the terminal until there is a whole
line to be printed.
getchar()
getchar returns the next character of keyboard input as an int. If there is an error then EOF (end of File) is
returned instead. It is therefore usual to compare this value against EOF before using it. If the return value
is stored in a char, it will never be equal to EOF, so error conditions will not be handled correctly.
As an example, here is a program to count the number of characters read until an EOF is encountered. EOF
can be generated by typing Control - z.
#include <stdio.h>
M V B REDDY GITAM UNIVERSITY BLR
void main()
{
int ch, i = 0;
while((ch = getchar()) != EOF)
i ++;
printf("%d\n", i);
}
putchar
putchar puts its character argument on the standard output (usually the screen).
The following example program converts any typed input into capital letters. To do this it applies the
function toupper from the character conversion library ctype.h to each character in turn.
#include <ctype.h>
#include <stdio.h>
void main()
{
int ch;
while((ch = getchar()) != '\n')
putchar(toupper(ch));
}
getch(), getche()
These input functions are same as getchar(). The difference is getch() used to input a charater, will not
echo character on the screen. The difference is getche() used to input a charater, will echo character on
the screen.The difference is getchar() used to input a charater, will echo character on the screen and wait
for carriage return.
printf()
The printf (and scanf) functions do differ from the sort of functions that you will created for yourself in that
they can take a variable number of parameters. In the case of printf the first parameter is always a string
(c.f. "Hello World") but after that you can include as many parameters of any type that you want to. That is,
M V B REDDY GITAM UNIVERSITY BLR
the printf function is usually of the form:
printf(string,variable,variable,variable...)
where the ... means you can carry on writing a list of variables separated by commas as long as you want
to. The string is all-important because it specifies the type of each variable in the list and how you want it
printed. The string is usually called the control string or the format string. The way that this works is that
printf scans the string from left to right and prints on the screen, or any suitable output device, any
characters it encounters - except when it reaches a % character. The % character is a signal that what
follows it is a specification for how the next variable in the list of variables should be printed. printf uses
this information to convert and format the value that was passed to the function by the variable and then
moves on to process the rest of the control string and anymore variables it might specify. For example:
printf("Hello World");
only has a control string and, as this contains no % characters it results in Hello World being displayed and
doesn't need to display any variable values. The specifier %d means convert the next value to a signed
decimal integer and so:
printf("Total = %d",total);
will print Total = and then the value passed by >total as a decimal integer.
The C view of output is at a lower level than you might expect. The %d isn't just a format specifier, it is a
conversion specifier. It indicates the data type of the variable to be printed and how that data type should
be converted to the characters that appear on the screen. That is %d says that the next value to be printed
is a signed integer value (i.e. a value that would be stored in a standard int variable) and this should be
converted into a sequence of characters (i.e. digits) representing the value in decimal. If by some accident
the variable that you are trying to display happens to be a float or a double then you will still see a value
displayed - but it will not correspond to the actual value of the float or double.
The reason for this is twofold. The first difference is that an int uses two bytes to store its value, while a
float uses four and a double uses eight. If you try to display a float or a double using %d then only the first
two bytes of the value are actually used. The second problem is that even if there wasn't a size difference
ints, floats and doubles use a different binary representation and %d expects the bit pattern to be a simple
signed binary integer.
This is all a bit technical, but that's in the nature of C. You can ignore these details as long as you
remember two important facts
The specifier following % indicates the type of variable to be displayed as well as the format in which that
the value should be displayed; If you use a specifier with the wrong type of variable then you will see some
strange things on the screen and the error often propagates to other items in the printf list.
M V B REDDY GITAM UNIVERSITY BLR
You can also add an 'l' in front of a specifier to mean a long form of the variable type and h to indicate a
short form (long and short will be covered later in this course). For example, %ld means a long integer
variable (usually four bytes) and %hd means short int. Notice that there is no distinction between a four-
byte float and an eight-byte double. The reason is that a float is automatically converted to a double
precision value when passed to printf - so the two can be treated in the same way. (In pre-ANSI all floats
were converted to double when passed to a function but this is no longer true.) The only real problem that
this poses is how to print the value of a pointer? The answer is that you can use %x to see the address in
hex or %o to see the address in octal. Notice that the value printed is the segment offset and not the
absolute address - to understand what we am going on about you need to know something about the
Structure of your processor.
The % Format Specifiers:The % specifiers that you can use in ANSI C are:
Usual variable type Display
%c char single character
%d (%i) int signed integer
%e (%E) float or double exponential format
%g (%G) float or double use %f or %e as required
%o int unsigned octal value
%s array of char sequence of characters
%u int unsigned decimal
%x (%X) int unsigned hex value
Formatting Output
The type conversion specifier only does what you ask of it - it convert a given bit pattern into a sequence of
characters that a human can read. If you want to format the characters then you need to know a little more
about the printf function's control string.Each specifier can be preceded by a modifier which determines
how the value will be printed. The most general modifier is of the form
flag width.precision
The flag can be any of
flag meaning - left justify + always display sign space display space if there is no sign 0 pad with leading zeros # use alternate form of specifier
The width specifies the number of characters used in total to display the value and precision indicates the
number of characters used after the decimal point.
For example, %10.3f will display the float using ten characters with three digits after the decimal point.
Notice that the ten characters includes the decimal point.and a - sign if there is one. If the value needs
M V B REDDY GITAM UNIVERSITY BLR
more space than the width specifies then the additional space is used - width specifies the smallest space
that will be used to display the value.
The specifier %-1Od will display an int left justified in a ten character space. The specifier %+5d will display
an int using the next five character locations and will add a + or - sign to the value.
The only complexity is the use of the # modifier. What this does depends on which type of format it is used
with.
The only complexity is the use of the # modifier. What this does depends on which type of format it is used
with
%#o adds a leading 0 to the octal value%#x adds a leading 0x to the hex value%#f or%#e ensures decimal point is printed%#g displays trailing zeros
Strings will be discussed later but for now remember: if you print a string using the %s specifier then all of
the characters stored in the array up to the first null will be printed. If you use a width specifier then the
string will be right justified within the space. If you include a precision specifier then only that number of
characters will be printed.
printf("%s,Hello")will print Hello
printf("%25s ,Hello") will print 25 characters with Hello right justified and
printf("%25.3s,Hello") will print Hello right justified in a group of 25 spaces.
Also notice that it is fine to pass a constant value to printf as in printf("%s,Hello").
Finally there are the control codes
\b backspace
\f formfeed
\n new line
\r carriage return
\t horizontal tab
\' single quote
\0 null
If you include any of these in the control string then the corresponding ASCII control code is sent to the
screen, or output device, which should produce the effect listed. In most cases you only need to
remember \n for new line.
M V B REDDY GITAM UNIVERSITY BLR
Scanf()
Now that we have mastered the intricacies of printf you should find scanf very easy. The scanf function
works in much the same way as the printf. That is it has the general form:
scanf(control string,variable,variable,...)
In this case the control string specifies how strings of characters, usually typed on the keyboard, should be
converted into values and stored in the listed variables. However there are a number of important
differences as well as similarities between scanf and printf.
The most obvious is that scanf has to change the values stored in the parts of computers memory that is
associated with parameters (variables).
To understand this fully you will have to wait until we have covered functions in more detail. But, just for
now, bare with us when we say to do this the scanf function has to have the addresses of the variables
rather than just their values. This means that simple variables have to be passed with a preceding >&.
(Note for future reference: There is no need to do this for strings stored in arrays because the array name
is already a pointer.)
The second difference is that the control string has some extra items to cope with the problems of reading
data in. However, all of the conversion specifiers listed in connection with printf can be used with scanf.
The rule is that scanf processes the control string from left to right and each time it reaches a specifier it
tries to interpret what has been typed as a value. If you input multiple values then these are assumed to
be separated by white space - i.e. spaces, newline or tabs
scanf("%d %d",&i,&j);
will read in two integer values into i and j. The integer values can be typed on the same line or on different
lines as long as there is at least one white space character between them.
The only exception to this rule is the %c specifier which always reads in the next character typed no matter
what it is. You can also use a width modifier in scanf. In this case its effect is to limit the number of
characters accepted to the width.
scanf("%lOd",&i)
would use at most the first ten digits typed as the new value for i.untile maximum value match data type.
There is one main problem with scanf function which can make it unreliable in certain cases. The reason
being is that scanf tends to ignore white spaces, i.e. the space character. If you require your input to
contain spaces this can cause a problem. Therefore for string data input the function getstr() may well be
M V B REDDY GITAM UNIVERSITY BLR
more reliable as it records spaces in the input text and treats them as an ordinary characters.
A program to demonstrate input,output task.
#include <stdio.h>
main()
{
int a,b,c;
printf("\nThe first number is ");
scanf("%d",&a);
printf("The second number is ");
scanf("%d",&b);
c=a+b;
printf("The answer is %d \n",c);
}
gets(),puts()
Where we are not too interested in the format of our data, or perhaps we cannot predict its format in
advance, we can read and write whole lines as character strings. This approach allows us to read in a line
of input, and then use various string handling functions to analyse it at our leisure.
gets reads a whole line of input into a string until a newline or EOF is encountered. It is critical to ensure
that the string is large enough to hold any expected input lines. When all input is finished, NULL as defined
in stdio.h is returned.
puts writes a string to the output, and follows it with a newline character.Example: Program which uses
gets and puts to double space typed input.
#include <stdio.h> main() { char line[80]; /* Define string sufficiently large to store a line of input */
while(gets(line) != NULL) /* Read line */ { puts(line); /* Print line */ printf("\n"); /* Print blank line */ }}
M V B REDDY GITAM UNIVERSITY BLR
Control Statements
A program consists of a number of statements which are usually executed in sequence. Programs can be
much more powerful if we can control the order in which statements are run.
Statements fall into three general types
Assignment, where values, usually the results of calculations, are stored in variables.
Input / Output, data is read in or printed out.
Control, the program makes a decision about what to do next.
This section will discuss the use of control statements in C. We will show how they can be used to write
powerful programs by;
Repeating important sections of the program.
Selecting between optional sections of a program.
If else Statement
This is used to decide whether to do something at a special point, or to decide between two courses of
action. The following test decides whether a student has passed an exam with a pass mark of 45
if (result >= 45)
printf("Pass\n");
else
printf("Fail\n");
It is possible to use the if part without the else.
if (temperature < 0)
print("Frozen\n");
Each version consists of a test, (this is the bracketed statement following the if). If the test is true then the
next statement is obeyed. If it is false then the statement following the else is obeyed if present. After this,
the rest of the program continues as normal.
If we wish to have more than one statement following the if or the else, they should be grouped together
between curly brackets. Such a grouping is called a compound statement or a block.
if (result >= 45) { printf("Passed\n"); printf("Congratulations\n") } else { printf("Failed\n"); printf("Good luck in the resits\n"); }
M V B REDDY GITAM UNIVERSITY BLR
Sometimes we wish to make a multi-way decision based on several conditions. The most general way of
doing this is by using the else if variant on the if statement. This works by cascading several comparisons.
As soon as one of these gives a true result, the following statement or block is executed, and no further
comparisons are performed. In the following example we are awarding grades depending on the exam
result.
if (result >= 75)
printf("Passed: Grade A\n");
else if (result >= 60)
printf("Passed: Grade B\n");
else if (result >= 45)
printf("Passed: Grade C\n");
else
printf("Failed\n");
In this example, all comparisons test a single variable called result. In other cases, each test may involve a
different variable or some combination of tests. The same pattern can be used with more or fewer else if's,
and the final lone else may be left out. It is up to the programmer to devise the correct Structure for each
programming problem.
The switch Statement
This is another form of the multi way decision. It is well Structured, but can only be used in certain cases
where;
Only one variable is tested, all branches must depend on the value of that variable. The variable
must be an integral type. (int, long, short or char).
Only one variable is tested, all branches must depend on the value of that variable. The variable
must be an integral type. (int, long, short or char).
Hopefully an example will clarify things. This is a function which converts an integer into a vague
description. It is useful where we are only concerned in measuring a quantity when it is quite small.
estimate(number)
int number;
/* Estimate a number as none, one, two, several, many */
{ switch(number) {
case 0 :
printf("None\n");
break;
case 1 :
printf("One\n");
break;
case 2 :
printf("Two\n");
break;
M V B REDDY GITAM UNIVERSITY BLR
case 3 :
case 4 :
case 5 :
printf("Several\n");
break;
default :
printf("Many\n");
break;
}
}
Each interesting case is listed with a corresponding action. The break statement prevents any further
statements from being executed by leaving the switch. Since case 3 and case 4 have no following break,
they continue on allowing the same action for several values of number.
Both if and switch constructs allow the programmer to make a selection from a number of possible
actions.
The other main type of control statement is the loop. Loops allow a statement, or block of statements, to
be repeated. Computers are very good at repeating simple tasks many times, the loop is C's way of
achieving this.
LOOP
C gives you a choice of three types of loop, while, do while and for.
The while loop keeps repeating an action until an associated test returns false. This is useful where
the programmer does not know in advance how many times the loop will be traversed.
The do while loops is similar, but the test occurs after the loop body is executed. This ensures that
the loop body is run at least once.
The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It
is very flexible, and novice programmers should take care not to abuse the power it offers.
The while Loop
The while loop repeats a statement until the test at the top proves false.
As an example, here is a function to return the length of a string. Remember that the string is represented
as an array of characters terminated by a null character '\0'.
int string_length(char string[])
{
M V B REDDY GITAM UNIVERSITY BLR
int i = 0;
while (string[i] != '\0')
i++;
return(i);
}
The string is passed to the function as an argument. The size of the array is not specified, the function will
work for a string of any size.
The while loop is used to look at the characters in the string one at a time until the null character is found.
Then the loop is exited and the index of the null is returned. While the character isn't null, the index is
incremented and the test is repeated.
The do while Loop
This is very similar to the while loop except that the test occurs at the end of the loop body. This
guarantees that the loop is executed at least once before continuing. Such a setup is frequently used
where data is to be read. The test then verifies the data, and loops back to read again if it was
unacceptable.
do
{
printf("Enter 1 for yes, 0 for no :");
scanf("%d", &input_value);
} while (input_value != 1 && input_value != 0);
The for Loop
The for loop works well where the number of iterations of the loop is known before the loop is entered. The
head of the loop consists of three parts separated by semicolons.
The first is run before the loop is entered. This is usually the initialisation of the loop variable
The second is a test, the loop is exited when this returns false.
The third is a statement to be run every time the loop body is completed. This is usually an
increment of the loop counter.
The example is a function which calculates the average of the numbers stored in an array. The function
takes the array and the number of elements as arguments.
float average(float array[], int count)
{
float total = 0.0;
int i;
for(i = 0; i < count; i++)
total += array[i];
M V B REDDY GITAM UNIVERSITY BLR
return(total / count);
}
The for loop ensures that the correct number of array elements are added up before calculating the
average.
The three statements at the head of a for loop usually do just one thing each, however any of them can be
left blank. A blank first or last statement will mean no initialisation or running increment. A blank
comparison statement will always be treated as true. This will cause the loop to run indefinitely unless
interrupted by some other means. This might be a return or a break statement.
It is also possible to squeeze several statements into the first or third position, separating them with
commas. This allows a loop with more than one controlling variable. The example below illustrates the
definition of such a loop, with variables hi and lo starting at 100 and 0 respectively and converging.
for (hi = 100, lo = 0; hi >= lo; hi--, lo++)
The for loop is extremely flexible and allows many types of program behaviour to be specified simply and
quickly.
The break Statement
We have already met break in the discussion of the switch statement. It is used to exit from a loop or a
switch, control passing to the first statement beyond the loop or a switch.
With loops, break can be used to force an early exit from the loop, or to implement a loop with a test to
exit in the middle of the loop body. A break within a loop should always be protected within an if statement
which provides the test to control the exit condition.
The continue Statement
This is similar to break but is encountered less frequently. It only works within loops where its effect is to
force an immediate jump to the loop control statement.
In a while loop, jump to the test statement.
In a do while loop, jump to the test statement.
In a for loop, jump to the test, and perform the iteration.
Like a break, continue should be protected by an if statement. You are unlikely to use it very often.
The goto Statement
C has a goto statement which permits un Structured jumps to be made. Its use is not recommended for
professional programming. Syntax for goto statment is goto label. Label is a mark where control is
transfered.
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<ctytpe.h>
void main()
M V B REDDY GITAM UNIVERSITY BLR
{
int num;
char ch;
repite:
printf("Enter a Number");
scanf("%d",&num);
printf("Squre root of the given number is %f",sqrt(num));
printf(do you want to continue(Y/N)");
fflush(stdin);
ch=getchar();
if((toupper(ch))=='Y')
goto repite;
}
M V B REDDY GITAM UNIVERSITY BLR
Recommended