CPG Course File Shiplu
CPG Course File Shiplu
CPG Course File Shiplu
Overview to C Programming
Objectives
This section is designed to give you a general overview of the C programming language.
Although much of this section will be expanded in later sections it gives you a taste of what is
to come.
Why use C?
C has been used successfully for every type of programming problem imaginable from
operating systems to spreadsheets to expert systems - and efficient compilers are available for
machines ranging in power from the Apple Macintosh to the Cray supercomputers. The
largest measure of C's success seems to be based on purely practical considerations:
1. the portability of the compiler;
2. the standard library concept;
3. a powerful and varied repertoire of operators;
4. an elegant syntax;
5. ready access to the hardware when needed;
6. and the ease with which applications can be optimized by hand-coding isolated procedures
C is often called a "Middle Level" programming language. This is not a reflection on its lack
of programming power but more a reflection on its capability to access the system's low level
functions. Most high-level languages (e.g. FORTRAN) provides everything the programmer
might want to do already built into the language. A low level language (e.g. assembler)
provides nothing other than access to the machines basic instruction set. A middle level
language, such as C, probably doesn't supply all the constructs found in high-languages - but
it provides you with all the building blocks that you will need to produce the results you
want!
Uses of C
C was initially used for system development work, in particular the programs that make-up
the operating system. Why use C? Mainly because it produces code that runs nearly as fast as
code written in assembly language. Some examples of the use of C might be:
1. Operating Systems
2. Language Compilers
3. Assemblers
4. Text Editors
Page |2
5. Print Spoolers
6. Network Drivers
7. Modern Programs
8. Data Bases
9. Language Interpreters
10. Utilities
In recent years C has been used as a general-purpose language because of its popularity with
programmers. It is not the world's easiest language to learn and you will certainly benefit if
you are not learning C as your first programming language! C is trendy (I nearly said sexy) many well established programmers are switching to C for all sorts of reasons, but mainly
because of the portability that writing standard C programs can offer.
A Brief History of C
C is a general-purpose language which has been closely associated with the UNIX operating
system for 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.
Running C Programs
Objectives
Page |3
This section is primarily aimed at the beginner who as no or little experience of using
compiled languages. We cover the various stages of program development. The basic
principles of this section will apply to what ever C compiler you choose to use, the stages are
nearly always the same
Page |4
Page |5
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!
Page |6
Unix systems
On all Unix systems further help on the C compiler can be obtained from the on-line manual.
Type
man cc
on your local Unix system for more information.
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.c
This 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.out
To change the name of the executable file type:
cc -o firstprog firstprog.c
This produces an executable file called firstprog which is run as follows:
firstprog
Page |7
Structure of C Programs
Objectives
Having completed this section you should know about:
1. C's character set
2. C's keywords
3. the general structure of a C program
4. that all C statement must end in a ;
5. that C is a free format language
6. all C programs us header files that contain standard library functions.
The use of most of this set of characters will be discussed throughout the course.
Page |8
upper and lowercase text to mean different things. If you are not sure what to use then always
use lowercase text in writing your C programs. A keyword may not be used for any other
purposes. For example, you cannot have a variable called auto.
Page |9
etc
Note the use of the bracket set () and {}. () are used in conjunction with function names
whereas {} are used as to delimit the C statements that are associated with that function. Also
note the semicolon - yes it is there, but you might have missed it! a semicolon (;) is used to
terminate C statements. C is a free format language and long statements can be continued,
without truncation, onto the next line. The semicolon informs the C compiler that the end of
the statement has been reached. Free format also means that you can add as many spaces as
you like to improve the look of your programs.
A very common mistake made by everyone, who is new to the C programming language, is to
miss off the semicolon. The C compiler will concatenate the various lines of the program
together and then tries to understand them - which it will not be able to do. The error message
produced by the compiler will relate to a line of you program which could be some distance
from the initial mistake.
Pre-processor Directives
C is a small language but provides the programmer with all the tools to be able to write
powerful programs. Some people don't like C because it is too primitive! Look again at the
set of keywords that comprises the C language and see if you can find a command that allows
you to print to the computer's screen the result of, say, a simple calculation. Don't look too
hard because it doesn't exist.
It would be very tedious, for all of us, if every time we wanted to communicate with the
computer we all had to write our own output functions. Fortunately, we do not have to. C uses
libraries of standard functions which are included when we build our programs. For the
novice C programmer one of the many questions always asked is does a function already
exist for what I want to do? Only experience will help here but we do include a function
listing as part of this course.
All programs you will write will need to communicate to the outside world - I don't think I
can think of a program that doesn't need to tell someone an answer. So all our C programs
will need at least one of C's standard libraries which deals with standard inputting and
outputting of data. This library is called stdin.h and it is declared in our programs before the
main function. The .h extension indicates that this is a header file.
I have already mentioned that C is a free format language and that you can layout your
programs how you want to using as much white space as you like. The only exception are
statements associated with the pre-processor.
All pre-processor directives begin with a # and the must start in the first column. The
commonest directive to all C programs is:
#include $$$$stdio.h&&&&
P a g e | 10
Note the use of the angle brackets ($$$$ and &&&&) around the header's name. These
indicate that the header file is to be looked for on the system disk which stores the rest of the
C program application. Some text books will show the above statement as follows:
#include "stdio.h"
The double quotes indicate that the current working directory should be searched for the
required header file. This will be true when you write your own header files but the standard
header files should always have the angle brackets around them.
NOTE: just to keep you on your toes - pre-processor statements, such as include, DO NOT
use semi-colons as delimiters! But don't forget the # must be in the first column.
Now that you've seen the compiler in action it's time for you to write your very own first C
program. You can probably guess what it's going to be - the program that everyone writes just
to check they understand the very, very, very basics of what is going on in a new language.
Yes - it's the ubiquitous "Hello World" program. All your first program is going to do is
print the message "Hello World" on the screen.
The program is a short one, to say the least. Here it is:
#include $$$$stdio.h&&&&
main()
{
printf("Hello World\n");
}
P a g e | 11
The first line is the standard start for all C programs - main(). After this comes the program's
only instruction enclosed in curly brackets {}. The curly brackets mark the start and end of
the list of instructions that make up the program - in this case just one instruction.
Notice the semicolon marking the end of the instruction. You might as well get into the habit
of ending every C instruction with a semicolon - it will save you a lot of trouble! Also notice
that the semicolon marks the end of an instruction - it isn't a separator as is the custom in
other languages.
If you're puzzled about why the curly brackets are on separate lines I'd better tell you that it's
just a layout convention to help you spot matching brackets. C is very unfussy about the way
you lay it out. For example, you could enter the Hello World program as:
main(){printf("Hello World\n");}
but this is unusual.
The printf function does what its name suggest it does: it prints, on the screen, whatever you
tell it to. The "\n" is a special symbols that forces a new line on the screen.
OK, that's enough explanation of our first program! Type it in and save it as Hello.c. Then
use the compiler to compile it, then the linker to link it and finally run it. The output is as
follows:
Hello World
P a g e | 12
Data Types
Objectives
Having read this section you should be able to:
1. declare (name) a local variable as being one of C's five data types
2. initialise local variables
3. perform simple arithmetic using local variables
Now we have to start looking into the details of the C language. How easy you find the rest of
this section will depend on whether you have ever programmed before - no matter what the
language was. There are a great many ideas common to programming in any language and C
is no exception to this rule.
So if you haven't programmed before, you need to take the rest of this section slowly and
keep going over it until it makes sense. If, on the other hand, you have programmed before
you'll be wondering what all the fuss is about It's a lot like being able to ride a bike!
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). C is very
fussy about how you create variables and what you store in them. 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.
In this section we are only going to be discussing local variables. These are variables that are
used within the current program unit (or function) in a later section we will looking at global
variables - variables that are available to all the program's functions.
There are five basic data types associated with variables:
1. int - integer: a whole number.
2. float - floating point value: ie a number with a fractional part.
3. double - a double-precision floating point value.
4. char - a single character.
5. void - valueless special purpose type which we will examine closely in later sections.
P a g e | 13
One of the confusing things about the C language is that the range of values and the amount
of storage that each of these types takes is not defined. This is because in each case the
'natural' choice is made for each type of machine. You can call variables what you like,
although it helps if you give them sensible names that give you a hint of what they're being
used for - names like sum, total, average and so on. If you are translating a formula then use
variable names that reflect the elements used in the formula. For example, 2(r (that should
read as "2 pi r" but that depends upon how your browser has been set-up) would give local
variables names of pi and r. Remember, C programmers tend to prefer short names!
Note:all C's variables must begin with a letter or a "_" (underscore) character.
P a g e | 14
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;
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".
P a g e | 15
Assignment Statement
Once you've declared a variable you can use it, but not until it has been declared - attempts to
use a variable that has not been defined will cause a compiler error. Using a variable means
storing something in it. You can store a value in a variable using:
name = value;
For example:
a=10;
stores the value 10 in the int variable a. What could be simpler? Not much, but it isn't
actually very useful! Who wants to store a known value like 10 in a variable so you can use it
later? It is 10, always was 10 and always will be 10. What makes variables useful is that you
can use them to store the result of some arithmetic.
Consider four very simple mathematical operations: add, subtract, multiply and divide. Let us
see how C would use these operations on two float variables a andb.
add
a+b
subtract
a-b
multiply
a*b
divide
a/b
Note that we have used the following characters from C's character set:
+ for add
- for subtract
* for multiply
/ for divide
BE CAREFUL WITH ARITHMETIC!!! What is the answer to this simple calculation?
P a g e | 16
a=10/3
The answer depends upon how a was declared. If it was declared as type int the answer will
be 3; if a is of type float then the answer will be 3.333. It is left as an exercise to the reader to
find out the answer for a of type char.
Two points to note from the above calculation:
1. C ignores fractions when doing integer division!
2. When doing float calculations integers will be converted into float. We will see later how C
handles type conversions.
Arithmetic Ordering
Whilst we are dealing with arithmetic we want to remind you about something that everyone
learns at junior school but then we forget it. Consider the following calculation:
a=10.0 + 2.0 * 5.0 - 6.0 / 2.0
What is the answer? If you think its 27 go to the bottom of the class! Perhaps you got that
answer by following each instruction as if it was being typed into a calculator. A computer
doesn't work like that and it has its own set of rules when performing an arithmetic
calculation. All mathematical operations form a hierarchy which is shown here. In the above
calculation the multiplication and division parts will be evaluated first and then the addition
and subtraction parts. This gives an answer of 17.
Note: To avoid confusion use brackets. The following are two different calculations:
a=10.0 + (2.0 * 5.0) - (6.0 / 2.0)
a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0
You can freely mix int, float and double variables in expressions. In nearly all cases the
lower precision values are converted to the highest precision values used in the expression.
For example, the expression f*i, where f is a float and i is an int, is evaluated by converting
the int to a float and then multiplying. The final result is, of course, a float but this may be
assigned to another data type and the conversion will be made automatically. If you assign to
a lower precision type then the value is truncated and not rounded. In other words, in nearly
all cases you can ignore the problems of converting between types.
This is very reasonable but more surprising is the fact that the data type char can also be
freely mixed with ints, floats and doubles. This will shock any programmer who has used
another language, as it's another example of C getting us closer than is customary to the way
the machine works. A character is represented as an ASCII or some other code in the range O
to 255, and if you want you can use this integer code value in arithmetic. Another way of
thinking about this is that a char variable is just a single-byte integer variable that can hold a
number in the range O to 255, which can optionally be interpreted as a character. Notice,
Department of Computer Science & Technology, BBIT
P a g e | 17
however, that C gives you access to memory in the smallest chunks your machine works
with, i.e. one byte at a time, with no overheads.
On The Run
Even with arithmetic you can't do very much other than write programs that are the
equivalent of a pocket calculator. The real break through comes when you can read values
into variables as the program runs. Notice the important words here: "as the program runs".
You can already store values in variables using assignment. That is:
P a g e | 18
a=100;
stores 100 in the variable a each time you run the program, no matter what you do. Without
some sort of input command every program would produce exactly the same result every
time it was run. This would certainly make debugging easy! But in practice, of course, we
need programs to do different jobs each time they are run. There are a number of different C
input commands, the most useful of which is the scanf command. To read a single integer
value into the variable called a you would use:
scanf("%d",&a);
For the moment don't worry about what the %d or the &a means - concentrate on the
difference between this and:
a=100;
When the program reaches the scanf statement it pauses to give the user time to type
something on the keyboard and continues only when users press $$$$Enter&&&&, or $$$
$Return&&&&, to signal that he, or she, has finished entering the value. Then the program
continues with the new value stored in a. In this way, each time the program is run the user
gets a chance to type in a different value to the variable and the program also gets the chance
to produce a different result!
The final missing piece in the jigsaw is using the printf function, the one we have already
used to print "Hello World", to print the value currently being stored in a variable. To display
the value stored in the variable a you would use:
printf("The value stored in a is %d",a);
The %d, both in the case of scanf and printf, simply lets the compiler know that the value
being read in, or printed out, is a decimal integer - that is, a few digits but no decimal point.
Note: the scanf function does not prompt for an input. You should get in the habit of always
using a printf function, informing the user of the program what they should type, before a
scanf function.
P a g e | 19
after writing C for a long time you will still find the occasionally construction which makes
you think, "I never thought of that!" or, "what is that doing?"
One attempt to make C a more uniform language is the provision of standard libraries of
functions that perform common tasks. We say standard but until the ANSI committee actually
produced a standard there was, and still is, some variation in what the standard libraries
contained and exactly how the functions worked. Having said that we had better rush in
quickly with the reassurance that in practice the situation isn't that bad and most of the
functions that are used frequently really are standard on all implementations. In particular the
I/O functions vary very little.
It is now time to look at exactly how scanf and printf work and what they can do - you might
be surprised at just how complex they really are!
The original C specification did not include commands for input and output. Instead the
compiler writers were supposed to implement library functions to suit their machines. In
practice all chose to implement printf and scanf and after a while C programmers started to
think of them as if these functions were I/O keywords! It sometimes helps to remember that
they are functions on a par with any other functions you may care to define. If you want to
you can provide your own implementations of printf or scanf or any of the other standard
functions - we'll discover how later.
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, 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);
P a g e | 20
will print Total = and then the value passed by &&&&total as a decimal integer.
If you are familiar other programming languages then you may feel happy about the printf
function because something like:
printf("Total = %d",total);
looks like the sort of output command you might have used before. For example, in BASIC
you would write:
PRINT "Total = ",total
but 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.
1. 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.
2. 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:
1. The specifier following % indicates the type of variable to be displayed as well as the format
in which that the value should be displayed;
2. 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.
If this seems complicated then I would agree but I should also point out that the benefit is
being able to treat what is stored in a variable in a more flexible way than other languages
allow. Other languages never let on to the programmer that what is in fact stored in a variable
is a bit pattern, not the decimal value that appears to be stored there when you use a printf (or
whatever) statement. Of course whether you view this as an advantage depends on what you
are trying to do. It certainly brings you closer to the way the machine works.
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
Department of Computer Science & Technology, BBIT
P a g e | 21
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.
P a g e | 22
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 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. (This is quiet
reassuring, you won't be the first programmer whose program takes hours to run but the
output results can't be viewed because the wrong format width has been specified!)
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:
%#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.
For example:
printf("%s,Hello")
P a g e | 23
P a g e | 24
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
Custom Libraries
If you think printf and scanf don't seem enough to do the sort of job that any modern
programmer expects to do, you would be right. In the early days being able to print a line at a
time was fine but today we expect to be able to print anywhere on the screen at any time.
The point is that as far as standard C goes simple I/O devices are stream-oriented - that is you
send or get a stream of characters without any notion of being able to move the current
position in the stream. If you want to move backwards and forwards through the data then
you need to use a direct access file. In more simple terms, C doesn't have a Tab(X,Y) or
Locate(X,Y) function or command which moves the cursor to the specified location! How are
you ever going to write your latest block buster game, let alone build your sophisticated input
screens?
Well you don't have to worry too much because although C may not define them as standard,
all C implementations come with an extensive graphics/text function library that allows you
to do all of this and more. Such a library isn't standard, however the principles are always the
same. The Borland and Microsoft offerings are usually considered as the two facto standards.
Summing It Up
Now that we have arithmetic, a way of reading values in and a way of displaying them, it's
possible to write a slightly more interesting program than "Hello World". Not much more
interesting, it's true, but what do you expect with two instructions and some arithmetic?
Let's write a program that adds two numbers together and prints the result. (I told you it
wasn't that much more interesting!) Of course, if you want to work out something else like
Fahrenheit to centigrade, inches to centimetres or the size of your bank balance, then that's up
to you - the principle is the same.
The program is a bit more complicated than you might expect, but only because of the need
to let the user know what is happening:
P a g e | 25
#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);
}
The first instruction declares three integer variables: a, b and c. The first two printf
statements simply display message on the screen asking the user for the values. The scanf
functions then read in the values from the keyboard into a andb. These are added together
and the result in c is displayed on the screen with a suitable message. Notice the way that you
can include a message in the printf statement along with the value.
Type the program in, compile it and link it and the result should be your first interactive
program. Try changing it so that it works out something a little more adventurous. Try
changing the messages as well. All you have to remember is that you cannot store values or
work out results greater than the range of an integer variable or with a fractional part.
Conditional Execution
Objectives
Having read this section you should be able to:
1. Program control with if , if-else and switch structures
2. have a better idea of what C understands as true and false.
P a g e | 26
Program Control
It is time to turn our attention to a different problem - conditional execution. We often need to
be able to choose which set of instructions are obeyed according to a condition. For example,
if you're keeping a total and you need to display the message 'OK' if the value is greater than
zero you would need to write something like:
if (total&&&&O) printf("OK");
This is perfectly reasonable English, if somewhat terse, but it is also perfectly good C. The if
statement allows you to evaluate a &&&& condition and only carry out the statement, or
compound statement, that follows if the condition is true. In other words the printf will only
be obeyed if the conditiontotal &&&& O is true.
If the condition is false then the program continues with the next instruction. In general the if
statement is of the following form:
if (condition) statement;
and of course the statement can be a compound statement.
Here's an example program using two if statements:
#include $$$$stdio.h&&&&
main()
{
int a , b;
do {
printf("\nEnter first number: ");
scanf("%d" , &a);
printf("\nEnter second number: ");
scanf("%d" , &b);
if (a$$$$b) printf("\n\nFirst number is less than second\n\n");
if (b$$$$a) printf("Second number is less than first\n\n");
} while (a $$$$ 999);
}
Department of Computer Science & Technology, BBIT
P a g e | 27
[program]
Here's another program using an if keyword and a compound statement or a block:
#include $$$$stdio.h&&&&
main()
{
int a , b;
do {
printf("\nEnter first number: ");
scanf("%d" , &a);
printf("\nEnter second number: ");
scanf("%d" , &b);
if (a$$$$b) {
printf("\n\nFirst number is less than second\n");
printf("Their difference is : %d\n" , b-a);
printf("\n");
}
printf("\n");
} while (a $$$$ 999);
}
[program]
The if statement lets you execute or skip an instruction depending on the value of the
condition. Another possibility is that you might want to select one of two possible statements
- one to be obeyed when the condition is true and one to be obeyed when the condition is
false. You can do this using the
if (condition) statement1;
else statement2;
Department of Computer Science & Technology, BBIT
P a g e | 28
Logical Expressions
So far we have assumed that the way to write the conditions used in loops and if statements is
so obvious that we don't need to look more closely. In fact there are a number of deviations
from what you might expect. To compare two values you can use the standard symbols:
&&&&
(greater than)
$$$$
(less than)
==
The reason for using two equal signs for equality is that the single equals sign always means
store a value in a variable - i.e. it is the assignment operator. This causes beginners lots of
problems because they tend to write:
if (a = 10) instead of if (a == 10)
The situation is made worse by the fact that the statement if (a = 10) is legal and causes no
compiler error messages! It may even appear to work at first because, due to a logical quirk
of C, the assignment actually evaluates to the value being assigned and a non-zero value is
treated as true (see below). Confused? I agree it is confusing, but it gets easier. . .
Just as the equals condition is written differently from what you might expect so the nonequals sign looks a little odd. You write not equals as !=. For example:
if (a != 0)
is 'if a is not equal to zero'.
An example program showing the if else construction now follows:
#include $$$$stdio.h&&&&
P a g e | 29
main ()
{
int num1, num2;
printf("\nEnter first number ");
scanf("%d",&num1);
printf("\nEnter second number ");
scanf("%d",&num2);
if (num2 ==0) printf("\n\nCannot devide by zero\n\n");
else printf("\n\nAnswer is %d\n\n",num1/num2);
}
[Program]
This program uses an if and else statement to prevent division by 0 from occurring.
P a g e | 30
P a g e | 31
{
int t ;
for ( ; ; ) {
scanf("%d" , &t) ;
if ( t==10 ) break ;
}
printf("End of an infinite loop...\n");
}
P a g e | 32
When a match is found, the statement sequence associated with that case are executed until
break is encountered.
An example program follows:
#include $$$$stdio.h&&&&
main()
{
int i;
printf("Enter a number between 1 and 4");
scanf("%d",&i);
switch (i)
{
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;
default:
printf("unrecognized number");
Department of Computer Science & Technology, BBIT
P a g e | 33
} /* end of switch */
}
This simple program recognizes the numbers 1 to 4 and prints the name of the one you enter.
The switch statement differs from if, in that switch can only test for equality, whereas the if
conditional expression can be of any type. Also switch will work with only int and char
types. You cannot for example, use floating-point numbers. If the statement sequence
includes more than one statement they will have to be enclosed with {} to form a compound
statement.
Algorithms
1. A sequential solution of any program that written in human
language,called algorithm.
2. Algorithm is first step of the solution process, after the
analysis of problem, programmer write the algorithm of that
problem.
3. Example of Algorithms:
Q. Write a algorithem to find out number is odd or even?
Ans.
step 1 : start
step 2 : input number
step 3 : rem=number mod 2
step 4 : if rem=0 then
print "number even"
else
print "number odd"
endif
step 5 : stop
Flowchart
1. Graphical representation of any program is called flowchart.
P a g e | 34
2. There are some standard graphics that are used in flowchart as
following:
P a g e | 35
P a g e | 36
Purpose
Description
Flow line
Terminal(Stop/Start)
Input/Output
Processing
P a g e | 37
Symbol
Purpose
Description
Desicion
On-page Connector
Off-page Connector
Predefined
Process/Function
P a g e | 38
Draw flowchart to find the largest among three different numbers entered by user.
P a g e | 39
P a g e | 40
Though, flowchart are useful in efficient coding, debugging and analysis of a program,
drawing flowchart in very complicated in case of complex programs and often ignored.
2. Global variables
3. Variables can be declared as both local variables which can be used inside the
function it has been declared in (more on this in further sections) andglobal variables
which are known throughout the entire program. Global variables are created by
declaring them outside any function. For example:
4. int max;
5. main()
6. {
7. .....
8. }
9. f1()
10. {
11. .....
12. }
13. The int max can be used in both main and function f1 and any changes made to it will
remain consistent for both functions. The understanding of this will become clearer
when you have studied the section on functions but I felt I couldn't complete a section
on data types without mentioning global and local variables.
14. Constant Data Types
15.
16. Constants refer to fixed values that may not be altered by the program. All the data
types we have previously covered can be defined as constant data types if we so
P a g e | 41
wish to do so. The constant data types must be defined before the main function. The
format is as follows:
17. #define CONSTANTNAME value
18. for example:
19. #define SALESTAX 0.05
20. The constant name is normally written in capitals and does not have a semi-colon at
the end. The use of constants is mainly for making your programs easier to be
understood and modified by others and yourself in the future. An example program
now follows:
21. #define SALESTAX 0.05
22. #include $$$$stdio.h&&&&
23. main()
24. {
25. float amount, taxes, total;
26. printf("Enter the amount purchased : ");
27. scanf("%f",&amount);
28. taxes = SALESTAX*amount;
29. printf("The sales tax is %4.2f",taxes);
30. printf("\n The total bill is %5.2f",total);
31. }
32. The float constant SALESTAX is defined with value 0.05. Three float variables are
declared amount, taxes and total. Display message to the screen is achieved using
printf and user input handled by scanf. Calculation is then performed and results sent
to the screen. If the value of SALESTAX alters in the future it is very easy to change
the value where it is defined rather than go through the whole program changing the
individual values separately, which would be very time consuming in a large program
with several references. The program is also improved when using constants rather
than values as it improves the clarity
33.
Arrays
34. Objectives
P a g e | 42
35. Having read this section you should have a good understanding of the use of arrays in
C.
P a g e | 43
counting from 1 and more technical ones usually start counting from 0. Anyway, in the case
of C you have to remember that
type array[size]
declares an array of the specified type and with size elements. The first array element is
array[0] and the last is array[size-1].
Using an array, the problem of reading in and printing out a set of values in reverse order
becomes simple:
main()
{
int a[5];
int i;
for(i =0;i $$$$ 5; ++i) scanf("%d",&a[i]);
for(i =4;i&&&& =0;--i) printf("%d",a[i]);
}
Well we said simple but I have to admit that the pair of for loops looks a bit intimidating. The
for loop and the array data type were more or less made for each other. The for loop can be
used to generate a sequence of values to pick out and process each element in an array in
turn. Once you start using arrays, for loops like:
for (i=0 ; i$$$$5 ; ++i)
to generate values in the order 0,1,2 and so forth, and
for(i=4;i&&&&=0;--i)
to generate values in the order 4,3,2... become very familiar.
P a g e | 44
is a hard and tedious process. For example, suppose you want to read in five numbers and
print them out in reverse order. You could do it the hard way as:
main()
{
int al,a2,a3,a4,a5;
scanf("%d %d %d %d %d",&a1,&a2,&a3,&a4,&a5);
printf("%d %d %d %d %d'',a5,a4,a3,a2,a1);
}
Doesn't look very pretty does it, and what if the problem was to read in 100 or more values
and print them in reverse order? Of course the clue to the solution is the use of the regular
variable names a1, a2 and so on. What we would really like to do is to use a name like a[i]
where i is a variable which specifies which particular value we are working with. This is the
basic idea of an array and nearly all programming languages provide this sort of facility only the details alter.
In the case of C you have to declare an array before you use it - in the same way you have to
declare any sort of variable. For example,
int a[5];
declares an array called a with five elements. Just to confuse matters a little the first element
is a[0] and the last a[4]. C programmer's always start counting at zero! Languages vary
according to where they start numbering arrays. Less technical, i.e. simpler, languages start
counting from 1 and more technical ones usually start counting from 0. Anyway, in the case
of C you have to remember that
type array[size]
declares an array of the specified type and with size elements. The first array element is
array[0] and the last is array[size-1].
Using an array, the problem of reading in and printing out a set of values in reverse order
becomes simple:
main()
{
int a[5];
P a g e | 45
int i;
for(i =0;i $$$$ 5; ++i) scanf("%d",&a[i]);
for(i =4;i&&&& =0;--i) printf("%d",a[i]);
}
[program]
Well we said simple but I have to admit that the pair of for loops looks a bit intimidating. The
for loop and the array data type were more or less made for each other. The for loop can be
used to generate a sequence of values to pick out and process each element in an array in
turn. Once you start using arrays, for loops like:
for (i=0 ; i$$$$5 ; ++i)
to generate values in the order 0,1,2 and so forth, and
for(i=4;i&&&&=0;--i)
to generate values in the order 4,3,2... become very familiar.
In Dis-array
An array of character variables is in no way different from an array of numeric variables, but
programmers often like to think about them in a different way. For example, if you want to
read in and reverse five characters you could use:
main()
{
char a[5];
int i;
for(i=0; i$$$$5; ++i) scanf("%c",&a[i]);
for(i=4;i&&&&=0;--i) printf("%c",a[i]);
}
Notice that the only difference, is the declared type of the array and the %c used to specify
that the data is to be interpreted as a character in scanf and printf. The trouble with character
arrays is that to use them as if they were text strings you have to remember how many
characters they hold. In other words, if you declare a character array 40 elements long and
store H E L L O in it you need to remember that after element 4 the array is empty. This is
Department of Computer Science & Technology, BBIT
P a g e | 46
such a nuisance that C uses the simple convention that the end of a string of characters is
marked by a null character. A null character is, as you might expect, the character with ASCII
code 0. If you want to store the null character in a character variable you can use the notation
\0 - but most of the time you don't have to actually use the null character. The reason is that C
will automatically add a null character and store each character in a separate element when
you use a string constant. A string constant is indicated by double quotes as opposed to a
character constant which is indicated by a single quote. For example:
"A"
is a string constant, but
'A'
is a character constant. The difference between these two superficially similar types of text is
confusing at first and the source of many errors. All you have to remember is that "A"
consists of two characters, the letter A followed by \0 whereas 'A' is just the single character
A. If you are familiar with other languages you might think that you could assign string
constants to character arrays and work as if a string was a built-in data type. In C however the
fundamental data type is the array and strings are very much grafted on. For example, if you
try something like:
char name[40];
name="Hello"
it will not work. However, you can print strings using printf and read them into character
arrays using scanf. For example,
main()
{
static char name[40] ="hello";
printf("%s",name);
scanf("%s",name);
printf("%s",name);
}
[program]
This program reads in the text that you type, terminating it with a null and stores it in the
character array name. It then prints the character array treating it as a string, i.e. stopping
P a g e | 47
when it hits the first null string. Notice the use of the "%s" format descriptor in scanf and
printf to specify that what is being printed is a string.
At this point the way that strings work and how they can be made a bit more useful and
natural depends on understanding pointers which is covered in the next section.
P a g e | 48
total = total + 1;
}
Don't worry for now about the curved brackets after the function's name. Once you have
defined your function you can use it within a program:
main()
{
demo();
}
In this program the instruction demo (); is entirely equivalent to writing out all of the
statements in the function. What we have done is to create an new C function and this, of
course, is the power of functions. When you are first introduced to the idea of functions, or
their equivalent in other languages, it is easy to fall into the trap of thinking that they are only
useful when you want to use a block of code more than once.
Functions are useful here but they have a more important purpose. If you are creating a long
program then functions allow you to split it into "bite-sized" chunks which you can work on
in isolation. As every C programmer knows, "functions are the building blocks of programs."
P a g e | 49
functions and, in particular, what about the main program? The simple answer is that total is
a variable that belongs to the demo function. It cannot be used in other functions, it doesn't
even exist in other functions and it certainly has nothing to do with any variable of the same
name that you declare within other functions.
This is what we hinted at when we said that functions were isolated chunks of code. Their
isolation is such that variables declared within the function can only be used within that
function. These variables are known as local variables and as their name suggests are local to
the function they have been declared in. If you are used to a language where every variable is
usable all the time this might seem silly and restrictive - but it isn't. It's what makes it possible
to break a large program down into smaller and more manageable chunks.
The fact that total is only usable within the demo function is one thing - but notice we said
that it only existed within this function, which is a more subtle point. The variables that a
function declares are created when the function is started and destroyed when the function is
finished. So if the intention is to use total to count the number of times the &&&&demo
function is used - forget it! Each time demo is used the variable total is created afresh, and at
the end of the function the variable goes up in a puff of smoke along with its value. So no
matter how many times you run demo total will only ever reach a value of 1, assuming that
it's initialised to 0.
P a g e | 50
The only way in which parameters are any different is that you can give them initial values
when the function starts by writing the values between the round brackets. So
sum(l,2);
is a call to the sum function with a set to 1 and b set to 2 and so result is set to 3. You can
also initialise parameters to the result of expressions such as:
sum(x+2,z*10);
which will set a equal to whatever x+2 works out to be and b equal to whatever z*10 works
out to be.
As a simpler case you can also set a parameter to the value in a single variable - for example:
sum(x,y);
will set a to the value stored in x and b to the value stored in y.
Parameters are the main way of getting values into a function, but how do we get values out?
There is no point in expecting the &&&&result variable to somehow magically get its value
out of the sum function - after all, it is a local variable and is destroyed when sum is
finished. You might try something like:
sum(int a, int b, int result)
{
int result;
result = a + b;
}
but it doesn't work. Parameters are just ordinary variables that are set to an initial value when
the function starts running - they don't pass values back to the program that used the function.
That is:
sum(l,2,r);
doesn't store 1+2 in r because the value in r is used to initialise the value in result and not
vice versa. You can even try
sum(l,2,result);
and it still will not work - the variable result within the function has nothing to do with the
variable result used in any other program.
P a g e | 51
The simplest way to get a value out of a function is to use the return instruction. A function
can return a value via its name - it's as if the name was a variable and had a value. The value
that is returned is specified by the instruction:
returnvalue;
which can occur anywhere within the function, not just as the last instruction - however, a
return always terminates the function and returns control back to the calling function. The
only complication is that as the function's name is used to return the value it has to be given a
data type. This is achieved by writing the data type in front of the function's name. For
example:
int sum(a,b);
So now we can at last write the correct version of the sum function:
int sum(int a, int b)
{
int result;
result = a + b;
return result;
}
and to use it you would write something like:
r=sum(1,2);
which would add 1 to 2 and store the result in r. You can use a function anywhere that you
can use a variable. For example,
r=sum(1,2)*3
is perfectly OK, as is
r=3+sum(1,2)/n-10
Obviously, the situation with respect to the number of inputs and outputs of a function isn't
equal. That is you can create as many parameters as you like but a function can return only a
single value. (Later on we will have to find ways of allowing functions to return more than
one value.)
So to summarise: a function has the general form:
P a g e | 52
P a g e | 53
{
etc...
declares the name sum to be a function that returns an integer. As long as you declare
functions before they are used you can put the actual definition anywhere you like.
By default if you don't declare a function before you use it then it is assumed to be an int
function - which is usually, but not always, correct. It is worth getting into the habit of putting
function declarations at the start of your programs because this makes them easier to convert
to full ANSI C.
What is ANSI C?
When C was first written the standard was set by its authors Kernighan and Ritche - hence
"K&R C". In 1990, an international ANSI standard for C was established which differs from
K&R C in a number of ways.
The only really important difference is the use of function prototypes. To allow the compiler
to check that you are using functions correctly ANSI C allows you to include a function
prototype which gives the type of the function and the type of each parameter before you
define the function. For example, a prototype for the sum function would be:
int sum(int,int);
meaningsum is an int function which takes two int parameters. Obviously, if you are in the
habit of declaring functions then this is a small modification. The only other major change is
that you can declare parameter types along with the function as in:
int sum(int a, int b);
{
rather than:
int sum(a,b)
int a,b;
{
was used in the original K&R C. Again, you can see that this is just a small change. Notice
that even if you are using an ANSI compiler you don't have to use prototypes and the K&R
version of the code will work perfectly well.
P a g e | 54
P a g e | 55
stdlib.h:Miscellaneous functions
1
P a g e | 56
main()
{
float a , b , c;
printf("Input two numbers... \n");
scanf("%f%f" , &a , &b);
c=a*b;
printf("%f times %f = %f\n" , a , b , c);
}
This program combines printf and scanf whereby printf displays the input from scanf.
#include $$$$stdio.h&&&&
main()
{
int i;
printf("%c\n",scanf("%i",i));
}
This program demonstrates the use of getchar and putchar.
#include $$$$stdio.h&&&&
main()
{
char ch;
printf("Enter some text (type a period to quit)...\n");
do {
ch = getchar();
putchar(ch+1);
P a g e | 57
P a g e | 58
P a g e | 59
i=i*j ;
printf("%d\n" , i);
}
}
P a g e | 60
char ch;
printf("Do you want to: \n");
printf"Add, subtract, Multiply, or Divide?\n");
/* force user to enter valid response */
do {
printf("Enter first letter: ");
ch=getchar();
printf("\n");
} while (ch!='A' && ch!='S' && ch!='M' && ch!='D');
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
if (ch=='A') printf("%d", a+b);
else if (ch=='S') printf("%d", a-b);
else if (ch=='M') printf("%d", a*b);
else if (ch=='D' && b!=0) printf("%d", a/b);
}
The switch statement is often used to process menu commands.
#include $$$$stdio.h&&&&
#include $$$$conio.h&&&&
main()
{
int a,b;
P a g e | 61
char ch;
printf("Do you want to:\n");
printf("Add, Subtract, Multipy, or Divide\n");
/* force user to enter valid response */
do (
printf("Enter first letter: ");
ch =getchar();
printf("\n");
} while (ch!='A' && ch!='S' && ch!='M' && ch!='D');
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
switch (ch) {
case 'A' : printf("%d", a+b);
break;
case 'S' : printf("%d", a-b);
break;
case 'M' : printf("%d", a*b);
break;
case 'D' : if (b!=0) printf("%d", a/b);
break;
}
}
P a g e | 62
The statement sequence associated with a case may be empty allowing two or more cases to
share a common statement sequence.
#include $$$$stdio.h&&&&
#include $$$$conio.h&&&&
main()
{
char ch;
printf("Enter the letter: ");
ch=getchar();
switch(ch) {
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
printf(" is a vowel \n");
break;
default:
printf(" is a consonant");
}
}
A simple program to show the use of the continue statement.
#include $$$$stdio.h&&&&
main()
{
Department of Computer Science & Technology, BBIT
P a g e | 63
int x ;
for ( x=0 ; x$$$$=100 ; x++) {
if (x%2) continue; /* using modulus operation */
printf("%d\n" , x);
}
This program jumps out of an infinite loop using the break statement.
#include $$$$stdio.h&&&&
main()
{
int t ;
for ( ; ; ) {
scanf("%d" , &t) ;
if ( t==10 ) break ;
}
printf("End of an infinite loop...\n");
}
P a g e | 64
int i , j;
for (i=2 ; i$$$$1000 ; i++) {
for (j=2 ; j$$$$= i/2 ; j++)
if (!(i%j)) break;
if (j&&&&i/2) printf("%d is a prime\n" , i);
}
}
This example program uses a do-while and nested if else construction.
#include $$$$stdio.h&&&&
main()
{
int a , b;
do {
printf("Enter first number: ");
scanf("%d" , &a);
printf("Enter second number: ");
scanf("%d" , &b);
if (a$$$$b)
printf("First number is less than second\n\n");
if (b$$$$a)
printf("Second number is less than first\n\n");
} while (a $$$$ 999);
}
This program uses nested for loop and if else construction.
P a g e | 65
#include $$$$stdio.h&&&&
#include $$$$conio.h&&&&
main()
{
int answer, count, chances, right;
for (count=1; count$$$$11; count++) {
printf("What is %d + %d?", count, count);
scanf("%d", &answer);
if (answer == count+count) printf("Right!\n");
else {
printf("Sorry, you're wrong \n");
printf("Try again\n");
right = 0;
/* nested for *?
for (chances=0; chances$$$$3 && ! right; chances++){
printf("\nWhat is %d + %d?",count, count);
scanf("%d", &answer);
if (answer == count+count){
printf("Right!\n");
right=1;
}
}
/* if answer still wrong, tell user */
if (!right)
P a g e | 66
#include $$$$stdio.h&&&&
main()
{
int number;
prompt(); /*function call no parameters */
scanf( "%d" , &number );
factor(number); /* function call with parameters */
}
prompt() /* function */
{
printf("Input a number... ");
}
factor(int t) /* function */
{
P a g e | 67
int sum = 1;
int i ;
for (i = 1 ; i $$$$= t ; i++)
sum = sum*i;
printf("Factorial %d is %d\n" , t , sum);
}
Here is a volume computing program using a function prototype.
#include $$$$stdio.h&&&&
/* this is volume()'s prototype */
double volume(double s1, double s2, double s3);
void main()
{
double vol;
vol = volume(12.2, 5.67. 9.03);
printf("Volume: %f", vol);
}
/* compute the volume of a cube. */
double volume(double s1, doublbe s2, double s3)
{
return s1*s2*s3;
}
Recursion when applied to a computer language means that a function can call itself. An
example follows:
#include $$$$stdio.h&&&&
void recurse(int i);
Department of Computer Science & Technology, BBIT
P a g e | 68
void main(void)
{
recurse(0);
}
void recurse(int i)
{
if (i$$$$10) {
recurse(i+1);
printf("%d ",i);
}
}
This program prints
9876543210
on the screen.
Array programs
This section contains example programs demonstrating the use of arrays.
A simple program to demonstrate the definition and use of an array.
#include $$$$stdio.h&&&&
main()
{
int i[10],j;
for ( j=0 ; j$$$$10 ; j++)
P a g e | 69
i[j] = j ;
for ( j=0 ; j$$$$10 ; j++)
printf("%d\n" , i[j]) ;
}
A program to demonstrate the use of an array.
#include $$$$stdio.h&&&&
#include $$$$stdlib.h&&&&
main()
{
int i , min_value , max_value ;
int list[10] ;
for ( i=0 ; i$$$$10 ; i++)
list[i] = rand() ;
/* Find the minimum value */
min_value = 32767 ;
for ( i=0 ; i$$$$10 ; i++)
if (list[i]$$$$min_value)
min_value=list[i] ;
printf("Minimum value generated is %d\n" , min_value) ;
/* Find the maximum value */
max_value = 0 ;
for ( i=0 ; i$$$$10 ; i++)
if (list[i]&&&&max_value)
max_value=list[i];
P a g e | 70
P a g e | 71
}
/* display sorted list */
for (t=0; t$$$$count; t++) printf("%d ", item[t]);
}
An example program using a two-dimensional array now follows.
#include $$$$stdio.h&&&&
main()
{
int twod[4][5];
int i,j;
for(i=0; i$$$$4; i++)
for(j=0; j$$$$5; j++)
twod[i][j] = i*j;
for (i=0; i$$$$4; i++) {
for (j=0; j$$$$5; j++)
printf("%d !, twod[i][j]);
printf("\n");
}
}
The program output looks like this:
00000
01234
02468
036912
P a g e | 72
Pointer programs
This section contains example programs demonstrating the use of pointers.
An example program using simple pointers.
#include $$$$stdio.h&&&&
main()
{
int balance;
int *address;
int value;
balance = 5000;
address = &balance;
value = *address;
printf("Balance is : %d\n" , value);
}
Another example using pointers.
#include $$$$stdio.h&&&&
main()
{
int *p , num;
p = #
*p = 100;
printf("%d\n" , num);
(*p)++;
printf("%d\n" , num);
P a g e | 73
(*p)--;
printf("%d\n" , num);
}
An example program demonstrating pointer Arithmetic.
#include $$$$stdio.h&&&&
main()
{
char *c , ch[10];
int *i , j[10];
float *f , g[10];
int x;
c = ch;
i = j;
f = g;
for ( x=0 ; x$$$$10 ; x++ )
printf("%p %p %p\n" , c+x , i+x , f+x);
}
An example program using pointers and arrays.
#include $$$$stdio.h&&&&
main()
{
char str[80];
char token[10];
char *p , *q;
P a g e | 74
String programs
This section contains example programs to demonstrate the use of strings.
A simple string example.
#include $$$$stdio.h&&&&
main()
{
char str[80] ;
printf("Enter a string: ") ;
gets(str) ;
printf("%s" , str);
P a g e | 75
printf("\n");
}
The follow program requests the input of two strings, then demonstrates the four string
functions with them.
#include $$$$string.h&&&&
#include $$$$stdio.h&&&&
main()
{
char str1[80], str2[80];
int i;
printf("Enter the first string: ");
getstr(str1);
printf("Enter the second string: ");
getstr(str2);
/* see how long the strings are */
printf("%s is %d chars long\n", str1, strlen(str1));
printf("%s is %d chars long\n", str2, strlen(str2));
/* compare the strings */
i= strcmp(str1, str2);
if (!i) printf("The strings are equal.\n");
else if (i$$$$0) printf ("%s is less than %s\n", str1,str2);
else printf("%s is greater than %s\n", str1, str2);
/* concatenate str2 to end of str1 if there is enough room*/
if (strlen(str1)+ strlen(str2) $$$$ 80) {
strcat(str1, str2);
Department of Computer Science & Technology, BBIT
P a g e | 76
printf("%s\n", str1);
}
/* copy str2 to str1 */
strcpy(str1, str1);
printf("%s %s\n", str1, str2);
}
Structure programs
This section contains example programs to demonstrate the use of structures.
This program stores data in a structure and displays the values.
#include $$$$stdio.h&&&&
void main(void)
{
struct s_type {
int i;
int j;
} s;
int i;
i=10;
s.i=100;
s.j=101;
printf("%d %d %d", i, s.i, s.j);
}
The variable i and the structure element i have no relationship to each other.
A function may return a structure to the calling procedure.
P a g e | 77
#include $$$$stdio.h&&&&
struct s_type {
int i;
double d;
} var1;
struct s-type f(void);
void main(void)
{
var1=f();
printf("%d %1f", var1.i, var1.d);
}
struct s_type f(void)
{
struct s_type temp;
temp.i=100;
temp.d = 123.23;
return temp;
}
This program passes a structure to a function.
#include $$$$stdio.h&&&&
struct s_type {
int i;
double d;
} var1;
P a g e | 78
P a g e | 79
P a g e | 80
P a g e | 81
P a g e | 82
P a g e | 83
}
inputs("enter name: ", list[i].name,30); if(!*list[i].name) break; /* stop entering */
inputs("enter street: ", list[i].street, 40);
inputs("enter town: ", list[i].town, 20);
inputs("enter county: ", list[i].county, 20);
inputs("enter Postal code: ", list[i].code, 10);
}
}
/**********************************************************/
/* Function find */
/**********************************************************/
find(char *name)
{
int i;
for(i=0 ; i$$$$MAX ; i++)
if(!strcmp(name ,list[i].name)) break;
if(i==MAX) return
else return i;
}
/**********************************************************/
/* Function find_free */
/**********************************************************/
find_free()
{
P a g e | 84
register int i;
for(i=0; i$$$$MAX; i++)
if(!*list[i].name) return i;
return
}
/**********************************************************/
/* Function init_list */
/**********************************************************/
init_list()
{
register int i;
for (i=0 ; i$$$$MAX ; i++)
*list[i].name = '\0'
}
/**********************************************************/
/* Function inputs */
/**********************************************************/
inputs( char *prompt , char *s , int count)
{
char str[255];
do {
printf(prompt);
gets(str);
if(strlen(str) 1; 1; ;&&&&=count) printf("\ntoo long\n");
P a g e | 85
} while(strlen(str)&&&&=count);
strcpy(s , str);
}
/**********************************************************/
/* Function load */
/**********************************************************/
load()
{
FILE *fp;
if ( (fp=fopen("mlist" , "rb")) == NULL) {
printf("cannot open file\n");
return;
}
printf("\nloading file\n");
fread(list , sizeof list , 1 , fp);
if (ferror(fp))
printf("An error occurred while reading file.\n");
fclose(fp);
}
/**********************************************************/
/* Function menu_select */
/**********************************************************/
menu_select()
{
P a g e | 86
char s[80];
int c;
printf("1. Enter a name\n") ;
printf("2. Delete a name\n") ;
printf("3. List the File \n");
printf("4. Search\n") ;
printf("5. Save the file\n") ;
printf("6. Load the file\n") ;
printf("7. Quit\n") ;
do {
printf("\nEnter your choice: ");
gets(s);
c = atoi(s);
} while(c$$$$0 || c&&&&7);
return c;
}
/**********************************************************/
/* Function save */
/**********************************************************/
save()
{
FILE *fp;
if ( (fp=fopen("mlist" , "wb")) == NULL) {
printf("cannot open file\n");
P a g e | 87
return;
}
printf("\nsaving file\n");
fwrite(list , sizeof list , 1 , fp);
if (ferror(fp))
printf("An error occurred while writing file.\n");
fclose(fp);
}
/**********************************************************/
/* Function search */
/**********************************************************/
search()
{
int i;
char name[30];
inputs("enter name to find: " , name , 30);
if ((i=find(name))$$$$0)
printf("not found\n");
else display(i);
}
/**********************************************************/
/* Function show_list */
/**********************************************************/
show_list()
P a g e | 88
{
int i;
for(i=0 ; i$$$$MAX ; i++) {
if(*list[i].name) {
display(i);
printf("\n\n");
}
}
printf("\n\n");
}
[program]
The second example program uses functions to play a simple game of tic tac toe.
#include $$$$stdio.h&&&&
#include $$$$stdlib.h&&&&
char matrix[3][3];
main()
{
char done;
printf("This is the game of tic tac toe...\n");
printf("You will be playing against the computer.\n") ;
done = ' ';
init_matrix();
do {
disp_matrix();
P a g e | 89
get_player_move();
done = check();
if (done != ' ') break;
get_computer_move();
done = check();
} while (done == ' ');
if (done == 'X') printf("\n\nYou won!!!\n");
else printf("I won!!!\n");
disp_matrix();
}
/**********************************************************/
/* fuction to initialise matrix */
/**********************************************************/
init_matrix()
{
int i , j ;
for (i=0 ; i$$$$3 ; i++)
for (j=0 ; j$$$$3 ; j++)
matrix[i][j] = ' ';
}
/**********************************************************/
/* fuction to get players move */
/**********************************************************/
get_player_move()
P a g e | 90
{
int x , y ;
printf("Enter coordinates of your X: ");
scanf("%d%d" , &x , &y);
x--; y--;
if (matrix[x][y] != ' ') {
printf("Invalid move, try again...\n");
get_player_move();
}
else matrix[x][y] = 'X';
}
/**********************************************************/
/* fuction to get computer move */
/**********************************************************/
get_computer_move()
{
int i , j ;
for (i=0 ; i$$$$3 ; i++) {
for (j=0 ; j$$$$3 ; j++)
if(matrix[i][j]==' ') break;
if (matrix[i][j] == ' ') break;
}
if (i*j == 9) {
printf("draw....\n");
P a g e | 91
exit(0);
}
else matrix[i][j] = 'O';
}
/**********************************************************/
/* fuction to display matrix */
/**********************************************************/
disp_matrix()
{
int t ;
printf(" 1 2 3\n");
for (t=0 ; t$$$$3 ; t++) {
printf(" %c | %c | %c %d" , matrix[t][0],
matrix[t][1], matrix[t][2] , t+1);
if (t!=2) printf("\n---|---|---\n");
}
printf("\n");
}
/**********************************************************/
/* fuction to check matrix */
/**********************************************************/
check()
{
int i ;
P a g e | 92
Chapter 7:
Questions
1. What is C language?
2. Who developed C language?
3. Describe about history of C programming language.
4. Where is C programming language used or uses of C language?
5. What is the difference between C and C++?
P a g e | 93
6. What is the difference between top down approach and bottom up approach in programming
languages?
7. What is the difference between C and Java?
8. C language has been developed in which language?
9. Which year C language is developed?
10. What is meant by programming language and give some examples?
11. Describe about C standards.
12. What are the key features of C language or what are the characteristics of C language?
13. What is embedded C?
14. Which level is C language belonging to?
15. What do you mean by high level, middle level and low level languages and give an example
for each?
16. What is the difference between structured oriented, object oriented and non-structure oriented
programming language?
17. What is compiler?
18. What is the difference between assembler, compiler and interpreter?
19. What is printf()?
20. What is scanf()?
21. What is meant by protocol?
22. Execution of a C program starts from which function?
23. What are all the sections that a C program may have and must have?
P a g e | 94
P a g e | 95
P a g e | 96
62. What is the difference between single equal = and double equal == operators in C?
63. What is the difference between pre increment operator and post increment operator?
64. What is the difference between pre decrement operator and post decrement operator?
65. What is & and * operators in C?
66. What will happen if break statement is not used in switch case in C?
67. Why is default statement used in switch case in C?
68. What is the use of goto statement?
69. What value will be assigned to the variable X if a = 10, b = 20, c = 30, d = 40 for the
expression X = a/b+c*d-c?
70. What is the value assigned to the following variables? int X1 = 13/3; int X2 = 13%3;
71. What is the difference between auto variable and register variable in C?
72. What is the difference between auto variable and static variable in C?
73. Where should type cast function not be used in C?
74. How many arguments can be passed to a function in C?
75. What is static function in C?
76. If you want to execute C program even after main function is terminated, which function can
be used?
77. Is it possible to call atexit() function more than once in a C program?
78. What is exit() function in C?
79. What is the difference between exit() and return() in C?
P a g e | 97
P a g e | 98
101.
Is pointer arithmetic a valid one? Which arithmetic operation supposed to be not valid
in pointer? Why?
102.
103.
104.
105.
106.
107.
108.
109.
110.
Can a pointer be freed more than once in C? What happens if we do so? Or can a
112.
How will you print the value and address of a pointer variable (example int *p) in C?
113.
How will you print the value and address of a normal variable (example int p) in C?
114.
What are library functions and their use in C language? Can we write our own
P a g e | 99
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
P a g e | 100
P a g e | 101
4. What is hashing?
To hash means to grind up, and thats essentially what hashing is all about. The heart of a
hashing algorithm is a hash function that takes your nice, neat data and grinds it into some
random-looking integer.
The idea behind hashing is that some data either has no inherent ordering (such as images) or
is expensive to compare (such as images). If the data has no inherent ordering, you cant
perform comparison searches.
P a g e | 102
Yes. Include files can be nested any number of times. As long as you use precautionary
measures, you can avoid including the same file twice. In the past, nesting header files was
seen as bad programming practice, because it complicates the dependency tracking function
of the MAKE program and thus slows down compilation. Many of todays popular compilers
make up for this difficulty by implementing a concept called precompiled headers, in which
all headers and associated dependencies are stored in a precompiled state.
P a g e | 103
sprintf() writes data to the character array whereas printf(...) writes data to the standard output
device.
13. Can you tell me how to check whether a linked list is circular?
Create two pointers, and set both to the start of the list. Update each as follows:
while (pointer1) {
pointer1 = pointer1->next;
pointer2 = pointer2->next;
if (pointer2) pointer2=pointer2->next;
if (pointer1 == pointer2) {
print ("circular");
}
}
If a list is circular, at some point pointer2 will wrap around and be either at the item just
before pointer1, or the item before that. Either way, its either 1 or 2 jumps until they meet.
P a g e | 104
16. Write down the equivalent pointer expression for referring the same element a[i][j]
[k][l] ?
a[i] == *(a+i)
a[i][j] == *(*(a+i)+j)
a[i][j][k] == *(*(*(a+i)+j)+k)
a[i][j][k][l] == *(*(*(*(a+i)+j)+k)+l)
17. Which bit wise operator is suitable for checking whether a particular bit is on or
off?
The bitwise AND operator. Here is an example:
enum {
KBit0 = 1,
KBit1,
KBit31,
};
if ( some_int & KBit24 )
printf ( Bit number 24 is ON\n );
else
printf ( Bit number 24 is OFF\n );
18. Which bit wise operator is suitable for turning off a particular bit in a number?
The bitwise AND operator, again. In the following code snippet, the bit number 24 is reset to
zero.
some_int = some_int & ~KBit24;
19. Which bit wise operator is suitable for putting on a particular bit in a number?
The bitwise OR operator. In the following code snippet, the bit number 24 is turned ON:
some_int = some_int | KBit24;
P a g e | 105
20. Does there exist any other function which can be used to convert an integer or a float
to a string?
Some implementations provide a nonstandard function called itoa(), which converts an
integer to string.
#include
char *itoa(int value, char *string, int radix);
DESCRIPTION
The itoa() function constructs a string representation of an integer.
PARAMETERS
value: Is the integer to be converted to string representation.
string: Points to the buffer that is to hold resulting string.
The resulting string may be as long as seventeen bytes.
radix: Is the base of the number; must be in the range 2 - 36.
A portable solution exists. One can use sprintf():
char s[SOME_CONST];
int i = 10;
float f = 10.20;
sprintf ( s, %d %f\n, i, f );
21. Why does malloc(0) return valid memory address ? What's the use?
malloc(0) does not return a non-NULL under every implementation. An implementation is
free to behave in a manner it finds suitable, if the allocation size requested is zero.
The implmentation may choose any of the following actions:
* A null pointer is returned.
* The behavior is same as if a space of non-zero size was requested. In this case, the usage of
return value yields to undefined-behavior.
Notice, however, that if the implementation returns a non-NULL value for a request of a
zero-length space, a pointer to object of ZERO length is returned! Think, how an object of
zero size should be represented
For implementations that return non-NULL values, a typical usage is as follows:
void
func ( void )
{
int *p; /* p is a one-dimensional array, whose size will vary during the the lifetime of the
program */
size_t c;
p = malloc(0); /* initial allocation */
if (!p)
{
perror (FAILURE );
return;
}
Department of Computer Science & Technology, BBIT
P a g e | 106
/* */
while (1)
{
c = (size_t) ; /* Calculate allocation size */
p = realloc ( p, c * sizeof *p );
/* use p, or break from the loop */
/* */
}
return;
}
Notice that this program is not portable, since an implementation is free to return NULL for a
malloc(0) request, as the C Standard does not support zero-sized objects.
P a g e | 107
The #include file include nonstandard header files that you have created for use in your
program. This is because these headers are often modified in the current directory, and you
will want the preprocessor to use your newly modified version of the header rather than the
older, unmodified version.
24. What is the benefit of using an enum rather than a #define constant?
The use of an enumeration constant (enum) has many advantages over using the traditional
symbolic constant style of #define. These advantages include a lower maintenance
requirement, improved program readability, and better debugging capability.
1) The first advantage is that enumerated constants are generated automatically by the
compiler. Conversely, symbolic constants must be manually assigned values by the
programmer.
2) Another advantage of using the enumeration constant method is that your programs are
more readable and thus can be understood better by others who might have to update your
program later.
3) A third advantage to using enumeration constants is that some symbolic debuggers can
print the value of an enumeration constant. Conversely, most symbolic debuggers cannot
print the value of a symbolic constant. This can be an enormous help in debugging your
program, because if your program is stopped at a line that uses an enum, you can simply
inspect that constant and instantly know its value. On the other hand, because most debuggers
cannot print #define values, you would most likely have to search for that value by manually
looking it up in a header file.
P a g e | 108
28. How can you determine the size of an allocated portion of memory?
You cant, really. free() can , but theres no way for your program to know the trick free()
uses. Even if you disassemble the library and discover the trick, theres no guarantee the trick
wont change with the next release of the compiler.
29. When does the compiler not implicitly generate the address of the first element of
an array?
Whenever an array name appears in an expression such as
array as an operand of the size of operator
array as an operand of & operator
array as a string literal initializer for a character array
Then the compiler does not implicitly generate the address of the address of the first element
of an array.
P a g e | 109
Using the #define method of declaring a constant enables you to declare a constant in one
place and use it throughout your program. This helps make your programs more
maintainable, because you need to maintain only the #define statement and not several
instances of individual constants throughout your program.
For instance, if your program used the value of pi (approximately 3.14159) several times, you
might want to declare a constant for pi as follows: #define PI 3.14159
Using the #define method of declaring a constant is probably the most familiar way of
declaring constants to traditional C programmers. Besides being the most common method of
declaring constants, it also takes up the least memory.
Constants defined in this manner are simply placed directly into your source code, with no
variable space allocated in memory. Unfortunately, this is one reason why most debuggers
cannot inspect constants created using the #define method.
35. Why should we assign NULL to the elements (pointer) after freeing them?
This is paranoia based on long experience. After a pointer has been freed, you can no longer
use the pointed-to data. The pointer is said to dangle; it doesnt point at anything useful.
If you NULL out or zero out a pointer immediately after freeing it, your program can no
longer get in trouble by using that pointer. True, you might go indirect on the null pointer
instead, but thats something your debugger might be able to help you with immediately.
Department of Computer Science & Technology, BBIT
P a g e | 110
Also, there still might be copies of the pointer that refer to the memory that has been
deallocated; thats the nature of C. Zeroing out pointers after freeing them wont solve all
problems.
36. What is a null pointer assignment error? What are bus errors, memory faults, and
core dumps?
These are all serious errors, symptoms of a wild pointer or subscript. Null pointer assignment
is a message you might get when an MS-DOS program finishes executing. Some such
programs can arrange for a small amount of memory to be available where the NULL
pointer points to (so to speak). If the program tries to write to that area, it will overwrite the
data put there by the compiler.
When the program is done, code generated by the compiler examines that area. If that data
has been changed, the compiler-generated code complains with null pointer assignment. This
message carries only enough information to get you worried. Theres no way to tell, just from
a null pointer assignment message, what part of your program is responsible for the error.
Some debuggers, and some compilers, can give you more help in finding the problem.
Bus error: core dumped and Memory fault: core dumped are messages you might see from a
program running under UNIX. Theyre more programmer friendly. Both mean that a pointer
or an array subscript was wildly out of bounds. You can get these messages on a read or on a
write. They arent restricted to null pointer problems. The core dumped part of the message is
telling you about a file, called core, that has just been written in your current directory. This is
a dump of everything on the stack and in the heap at the time the program was running. With
the help of a debugger, you can use the core dump to find where the bad pointer was used.
That might not tell you why the pointer was bad, but its a step in the right direction. If you
dont have write permission in the current directory, you wont get a core file, or the core
dumped message
P a g e | 111
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer:
mmm
aaaa
nnnn
Explanation: s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea.
Generally array name is the base address for that array. Here s is the base address. i is the
index number/ displacement from the base address. So, indirecting it with * is same as s[i].
i[s] may be surprising. But in the case of C it is same as s[i].
39. main()
{
float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love U");
else
printf("I hate U");
}
Answer: I hate U
Explanation: For floating point numbers (float, double, long double) the values cannot be
predicted exactly. Depending on the number of bytes, the precession with of the value
represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with
less precision than long double.
Rule of Thumb: Never compare or at-least be cautious when using floating point numbers
with relational operators (== ,>, <, <=, >=,!= ) .
40. main()
{
static int var = 5;
printf("%d ",var--);
if(var)
main();
}
Answer: 5 4 3 2 1
Explanation: When static storage class is given, it is initialized once. The change in the value
of a static variable is retained even between the function calls. Main is also treated like any
other ordinary function, which can be called recursively.
Department of Computer Science & Technology, BBIT
P a g e | 112
41. main()
{
int c[ ]={2.8,3.4,4,6.7,5};
int j,*p=c,*q=c;
for(j=0;j<5;j++) {
printf(" %d ",*c);
++q; }
for(j=0;j<5;j++){
printf(" %d ",*p);
++p; }
}
Answer: 2 2 2 2 2 2 3 4 6 5
Explanation: Initially pointer c is assigned to both p and q. In the first loop, since only q is
incremented and not c , the value 2 will be printed 5 times. In second loop p itself is
incremented. So the values 2 3 4 6 5 will be printed.
42. main()
{
extern int i;
i=20;
printf("%d",i);
}
Answer: Linker Error : Undefined symbol '_i'
Explanation: extern storage class in the following declaration,
extern int i;
specifies to the compiler that the memory for i is allocated in some other program and that
address will be given to the current program at the time of linking. But linker finds that no
other variable of name i is available in any other program with memory space allocated for it.
Hence a linker error has occurred .
43. main()
{
int i=-1,j=-1,k=0,l=2,m;
m=i++&&j++&&k++||l++;
printf("%d %d %d %d %d",i,j,k,l,m);
}
Answer: 0 0 1 3 1
P a g e | 113
Explanation: Logical operations always give a result of 1 or 0. And also the logical AND
(&&) operator has higher priority over the logical OR (||) operator. So the expression i++
&& j++ && k++ is executed first. The result of this expression is 0 (-1 && -1 && 0 = 0).
Now the expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except
for 0 || 0 combination- for which it gives 0). So the value of m is 1. The values of other
variables are also incremented by 1.
44. main()
{
char *p;
printf("%d %d ",sizeof(*p),sizeof(p));
}
Answer: 1 2
Explanation: The sizeof() operator gives the number of bytes taken by its operand. P is a
character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p)
gives a value of 1. Since it needs two bytes to store the address of the character pointer
sizeof(p) gives 2.
45. main()
{
int i=3;
switch(i)
{
default:printf("zero");
case 1: printf("one");
break;
case 2:printf("two");
break;
case 3: printf("three");
break;
}
}
Answer : Three
Explanation: The default case can be placed anywhere inside the loop. It is executed only
when all other cases doesn't match.
46. main()
{
printf("%x",-1<<4);
P a g e | 114
}
Answer: fff0
Explanation: -1 is internally represented as all 1's. When left shifted four times the least
significant 4 bits are filled with 0's.The %x format specifier specifies that the integer value be
printed as a hexadecimal value.
47. main()
{
char string[]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}
Answer: Compiler Error: Type mismatch in redeclaration of function display
Explanation: In third line, when the function display is encountered, the compiler doesn't
know anything about the function display. It assumes the arguments and return types to be
integers, (which is the default type). When it sees the actual function display, the arguments
and type contradicts with what it has assumed previously. Hence a compile time error occurs.
48. main()
{
int c=- -2;
printf("c=%d",c);
}
Answer: c=2;
Explanation: Here unary minus (or negation) operator is used twice. Same maths rules
applies, ie. minus * minus= plus.
Note: However you cannot give like --2. Because -- operator can only be applied to variables
as a decrement operator (eg., i--). 2 is a constant and not a variable.
P a g e | 115
printf("sizeof(i)=%d",sizeof(i));
}
Answer: sizeof(i)=1
Explanation: Since the #define replaces the string int by the macro char
50. main()
{
int i=10;
i=!i>14;
Printf ("i=%d",i);
}
Answer: i=0
Explanation: In the expression !i>14 , NOT (!) operator has more precedence than >
symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is false (zero).
51. #include<stdio.h>
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
Answer: 77
Explanation: p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing
to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is then
incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is incremented
by 1 and it becomes 'b'. ASCII value of 'b' is 98.
Now performing (11 + 98 32), we get 77("M"); So we get the output 77 :: "M" (Ascii is 77).
52. #include<stdio.h>
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
Department of Computer Science & Technology, BBIT
P a g e | 116
*q=***a;
printf("%d----%d",*p,*q);
}
Answer: SomeGarbageValue---1
Explanation: p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the
third 2D(which you are not declared) it will print garbage values.
*q=***a starting address of a is assigned integer pointer. Now q is pointing to starting
address of a. If you print *q, it will print first element of 3D array.
53. #include<stdio.h>
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}
Answer: Compiler Error
Explanation: You should not initialize variables in declaration
54. #include<stdio.h>
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}
Department of Computer Science & Technology, BBIT
P a g e | 117
55. main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
Answer: hai
Explanation:
\n - newline
\b - backspace
\r - linefeed
56. main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
Answer: 45545
Explanation: The arguments in a function call are pushed into the stack from left to right. The
evaluation is by popping out from the stack. And the evaluation is from right to left, hence the
result.
P a g e | 118
Explanation: the macro call square(4) will substituted by 4*4 so the expression becomes i =
64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4
= 64
58. main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}
Answer: ibj!gsjfoet
Explanation: ++*p++ will be parse in the given order
_ *p that is value at the location currently pointed by p will be taken
_ ++*p the retrieved value will be incremented
_ when; is encountered the location will be incremented that is p++ will be executed Hence,
in the while loop initial value pointed by p is h, which is changed to i by executing ++*p
and pointer moves to point, a which is similarly changed to b and so on. Similarly blank
space is converted to !. Thus, we obtain value in p becomes ibj!gsjfoet and since p
reaches \0 and p1 points to p thus p1doesnot print anything.
P a g e | 119
Answer: 100
Explanation: Preprocessor executes as a seperate pass before the execution of the compiler.
So textual replacement of clrscr() to 100 occurs. The input program to compiler looks like
this :
main()
{
100;
printf("%d\n",100);
}
Note: 100; is an executable statement but with no action. So it doesn't give any problem
61. main()
{
41printf("%p",main);
}8
Answer: Some address will be printed.
Explanation: Function names are just addresses (just like array names are addresses). main()
is also a function. So the address of function main will be printed. %p in printf specifies that
the argument is an address. They are printed as hexadecimal numbers.
62. main()
{
clrscr();
}
clrscr();
Answer: No output/error
Explanation: The first clrscr() occurs inside a function. So it becomes a function call. In the
second clrscr(); is a function declaration (because it is not inside any function).
P a g e | 120
{
printf("%d..%d..%d",BLACK,BLUE,GREEN);
return(1);
}
Answer: 0..1..2
Explanation: enum assigns numbers starting from 0, if not explicitly defined.
65. main()
{
int i=400,j=300;
printf("%d..%d");
}
Answer: 400..300
Explanation: printf takes the values of the first two assignments of the program. Any number
of printf's may be given. All of them take only the first two values. If more number of
assignments given in the program,then printf will take garbage values.
66. main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}
P a g e | 121
Answer: H
Explanation: * is a dereference operator & is a reference operator. They can be applied any
number of times provided it is meaningful. Here p points to the first character in the string
"Hello". *p dereferences it and so its value is H. Again & references it to an address and
* dereferences it to the value H.
67. main()
{
int i=1;
while (i<=5)
{
printf("%d",i);
if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}
Answer: Compiler error: Undefined label 'here' in function main
Explanation: Labels have functions scope, in other words the scope of the labels is limited to
functions. The label 'here' is available in function fun() Hence it is not visible in function
main.
68. main()
{
static char names[5][20]={"pascal","ada","cobol","fortran","perl"};
int i;
char *t;
t=names[3];
names[3]=names[4];
names[4]=t;
for (i=0;i<=4;i++)
printf("%s",names[i]);
}
P a g e | 122
71. #include<stdio.h>
main()
{
int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
Department of Computer Science & Technology, BBIT
P a g e | 123
}
Answer: Compiler Error: Constant expression required in function main.
Explanation: The case statement can have only constant expressions (this implies that we
cannot use variable names directly so an error).
Note: Enumerated types can be used in case statements.
72. main()
{
int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}
Answer: 1
Explanation: Scanf returns number of items successfully read and not 1/0. Here 10 is given as
input which should have been scanned successfully. So number of items read is 1.
74. main()
{
int i=0;
for(;i++;printf("%d",i)) ;
printf("%d",i);
}
Answer: 1
P a g e | 124
Explanation: before entering into the for loop the checking condition is "evaluated". Here it
evaluates to 0 (false) and comes out of the loop, and i is incremented (note the semicolon
after the for loop).
75. #include<stdio.h>
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
Answer: M
Explanation: p is pointing to character '\n'.str1 is pointing to character 'a' ++*p "p is pointing
to '\n' and that is incremented by one." the ASCII value of '\n' is 10. then it is incremented to
11. the value of ++*p is 11. ++*str1 "str1 is pointing to 'a' that is incremented by 1 and it
becomes 'b'. ASCII value of 'b' is 98. Both 11 and 98 is added and result is subtracted from
32. i.e. (11+98-32)=77("M");
76. #include<stdio.h>
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s=malloc(sizeof(struct xx));
printf("%d",s->x);
printf("%s",s->name);
}
Answer: Compiler Error
Explanation: Initialization should not be done for structure members inside the structure
declaration
P a g e | 125
77. #include<stdio.h>
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}
Answer: Compiler Error
Explanation: in the end of nested structure yy a member have to be declared.
78. main()
{
extern int i;
i=20;
printf("%d",sizeof(i));
}
Answer: Linker error: undefined symbol '_i'.
Explanation: extern declaration specifies that the variable i is defined somewhere else. The
compiler passes the external variable to be resolved by the linker. So compiler doesn't find an
error. During linking the linker searches for the definition of i. Since it is not found the linker
flags an error.
79. main()
{
printf("%d", out);
Department of Computer Science & Technology, BBIT
P a g e | 126
}
int out=100;
Answer: Compiler error: undefined symbol out in function main.
Explanation: The rule is that a variable is available for use from the point of declaration. Even
though a is a global variable, it is not available for main. Hence an error.
80. main()
{
extern out;
printf("%d", out);
}
int out=100;
Answer: 100
Explanation: This is the correct way of writing the previous program.
81. main()
{
show();
}
void show()
{
printf("I'm the greatest");
}
Answer: Compier error: Type mismatch in redeclaration of show.
Explanation: When the compiler sees the function show it doesn't know anything about it. So
the default return type (ie, int) is assumed. But when compiler sees the actual definition of
show mismatch occurs since it is declared as void. Hence the error.
The solutions are as follows:
1. declare void show() in main() .
2. define show() before main().
3. declare extern void show() before the use of show().
P a g e | 127
82. main( )
{
int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
printf(%u %u %u %d \n,a,*a,**a,***a);
printf(%u %u %u %d \n,a+1,*a+1,**a+1,***a+1);
}
Answer:
100, 100, 100, 2
114, 104, 102, 3
Explanation: The given array is a 3-D one. It can also be viewed as a 1-D array.
24
8 3
83. main( )
{
int a[ ] = {10,20,30,40,50},j,*p;
for(j=0; j<5; j++)
{
printf(%d ,*a);
a++;
}
p = a;
for(j=0; j<5; j++)
{
printf(%d ,*p);
p++;
}
}
Answer: Compiler error: lvalue required.
Department of Computer Science & Technology, BBIT
P a g e | 128
Explanation: Error is in line with statement a++. The operand must be an lvalue and may be
of any of scalar type for the any operator, array name only when subscripted is an lvalue.
Simply array name is a non modifiable lvalue.
84. main( )
{
static int a[ ] = {0,1,2,3,4};
int *p[ ] = {a,a+1,a+2,a+3,a+4};
int **ptr = p;
ptr++;
printf(\n %d %d %d, ptr-p, *ptr-a, **ptr);
*ptr++;
printf(\n %d %d %d, ptr-p, *ptr-a, **ptr);
*++ptr;
printf(\n %d %d %d, ptr-p, *ptr-a, **ptr);
++*ptr;
printf(\n %d %d %d, ptr-p, *ptr-a, **ptr);
}
Answer:
111
222
333
344
Explanation: Let us consider the array and the two pointers with some address
a
100 102
ptr
P a g e | 129
1000
2000
After execution of the instruction ptr++ value in ptr becomes 1002, if scaling factor for
integer is 2 bytes. Now ptr p is value in ptr starting location of array p, (1002 1000) /
(scaling factor) = 1,
*ptr a = value at address pointed by ptr starting value of array a, 1002 has a value 102 so
the value is (102 100)/(scaling factor) = 1, **ptr is the value stored in the location pointed
by the pointer of ptr = value pointed by value pointed by 1002 = value pointed by 102 = 1.
Hence the output of the firs printf is 1, 1, 1.
After execution of *ptr++ increments value of the value in ptr by scaling factor, so it
becomes1004. Hence, the outputs for the second printf are ptr p = 2, *ptr a = 2, **ptr = 2.
After execution of *++ptr increments value of the value in ptr by scaling factor, so it
becomes1004. Hence, the outputs for the third printf are ptr p = 3, *ptr a = 3, **ptr = 3.
After execution of ++*ptr value in ptr remains the same, the value pointed by the value is
incremented by the scaling factor. So the value in array p at location 1006 changes from 106
10 108,. Hence, the outputs for the fourth printf are ptr p = 1006 1000 = 3, *ptr a = 108
100 = 4, **ptr = 4.
P a g e | 130
P a g e | 131
95. What are macros? What are its advantages and disadvantages?
Macro is a Pre-processor.Major advantage of using the macro is to increase the speed of the
execution of the program.
Major disadvantage of the macros are:
(i) No type checking is performed in macro. This may cause error.
(ii) A macro call may cause unexpected results.
P a g e | 132
said to be segments and its width can be said as offset. In short,segment is a physical address
and offset is logical address.
102. How does a C program come to know about command line arguments?
When we execute our C program, operating system loads the program into memory. In case
of DOS, it first loads 256 bytes into memory, called program segment prefix. This contains
file tables,environment segment, and command line information. When we compile the C
program the compiler inserts additional code that parses the command, assigning it to the
argv array, making the arguments easily accessible within our C program.
P a g e | 133
105. Where does global, static, local, register variables and C Program instructions get
stored?
Global , static, local : In main memory
Register variable: In registers
C program : In main memory.
P a g e | 134
A linker converts an object code into an executable code by linking together the necessary
build in functions. The form and place of declaration where the variable is declared in a
program determine the
linkage of variable.
P a g e | 135
P a g e | 136
P a g e | 137
126. What are differences between sizeof operator and strlen function?
sizeof is keyword of c which can find size of a string constant including null character but
strlen is function which has been defined string.h and can find number of characters in a
string excluding null character.
P a g e | 138
P a g e | 139
When a function of body calls the same function then it is called as 'recursive function.'
Example:
Recursion()
{
printf("Recursion !");
Recursion();
}
P a g e | 140
141. Do you know, what is the meaning and use of static keyword in c?
Keyword static is used for declaring static variables in c. This modifier is used with all data
types like int, float, double, array, pointer, structure, function etc.
145. Out of fgets() and gets() which function is safe to use and why?
P a g e | 141
fgets() is safer than gets(), because we can specify a maximum input length. Neither one is
completely safe, because the compiler cant prove that programmer wont overflow the buffer
he pass to fgets ().
147. Differentiate between a for loop and a while loop? What are it uses?
For executing a set of statements fixed number of times we use for loop while when the
number of
iterations to be performed is not known in advance we use while loop.
148. What is storage class? What are the different storage classes in C?
Storage class is an attribute that changes the behavior of a variable. It controls the lifetime,
scope and linkage. The storage classes in c are auto, register, and extern, static, typedef.
P a g e | 142
P a g e | 143
P a g e | 144
Chapter 8:
Assignment
Lab
ASSIGNMENT
1. Write a program to accept the marks of a student in 3 subjects and
calculate the Total Marks and Average Marks.
2. Write a program to perform addition, subtraction, division, integer
division, multiplication of two integers.
3. Write a program to perform addition, subtraction, division, integer
division, multiplication of two floating point numbers.
4. Write a program to read a character in upper case and then print the
character in lower case.
5. Write a program to print the digits at ones place, tens place and hundreds
place.
6. Write a program to calculate the salary of an employee, given his basic
pay (to be entered by user), HRA=10% of basic pay, and TA=5% of basic
pay. Define HRA and TA as constants and use them to calculate the salary
of the employee.
7. Write a program to find whether a given year is leap or not.
8. Write a program to find the greatest of three numbers using nested if-else.
9. Write a program to enter a number from 1-7 and display the
corresponding day of the week using switch case statement.
10.Write a program that accepts a number from 1-10. Print whether the
number is even or odd using switch case construct.
P a g e | 145
P a g e | 146