Sunteți pe pagina 1din 146

Page |1

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

Department of Computer Science & Technology, BBIT

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.

C for Personal Computers


With regards to personal computers Microsoft C for IBM (or clones) PC's. And Borlands C
are seen to be the two most commonly used systems. However, the latest version of Microsoft
C is now considered to be the most powerful and efficient C compiler for personal computers.
We hope we have now managed to convince you to continue with this online C course and
hopefully in time become a confident C programmer.

Running C Programs
Objectives

Department of Computer Science & Technology, BBIT

Page |3

Having read this section you should be able to:


1. Edit, link and run your C programs

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

Department of Computer Science & Technology, BBIT

Page |4

The Edit-Compile-Link-Execute Process


Developing a program in a compiled language such as C requires at least four steps:
1. editing (or writing) the program
2. compiling it
3. linking it
4. executing it

We will now cover each step separately.


Editing
You write a computer program with words and symbols that are understandable to human
beings. This is the editing part of the development cycle. You type the program directly into a
window on the screen and save the resulting text as a separate file. This is often referred to as
the source file (you can read it with the TYPE command in DOS or the cat command in
unix). The custom is that the text of a C program is stored in a file with the extension .c for C
programming language
Compiling
You cannot directly execute the source file. To run on any computer system, the source file
must be translated into binary numbers understandable to the computer's Central Processing
Unit (for example, the 80*87 microprocessor). This process produces an intermediate object
file - with the extension .obj, the .obj stands for Object.
Linking
The first question that comes to most peoples minds is Why is linking necessary? The main
reason is that many compiled languages come with library routines which can be added to
your program. Theses routines are written by the manufacturer of the compiler to perform a
variety of tasks, from input/output to complicated mathematical functions. In the case of C
the standard input and output functions are contained in a library (stdio.h) so even the most
basic program will require a library function. After linking the file extension is .exe which
are executable files.
Executable files
Thus the text editor produces .c source files, which go to the compiler, which produces .obj
object files, which go to the linker, which produces .exe executable file. You can then run
.exe files as you can other applications, simply by typing their names at the DOS prompt or
run using windows menu.

Department of Computer Science & Technology, BBIT

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!

Department of Computer Science & Technology, BBIT

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

Department of Computer Science & Technology, BBIT

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.

C's Character Set


C does not use, nor requires the use of, every character found on a modern computer
keyboard. The only characters required by the C Programming Language are as follows:
1. A - Z
2. a -z
3. 0 - 9
4. space . , : ; ' $ "
5. # % & ! _ {} [] () $$$$ &&&& |
6. + - / * =

The use of most of this set of characters will be discussed throughout the course.

The form of a C Program


All C programs will consist of at least one function, but it is usual (when your experience
grows) to write a C program that comprises several functions. The only function that has to
be present is the function called main. For more advanced programs the main function will
act as a controlling function calling other functions in their turn to do the dirty work! The
main function is the first function that is called when your program executes.
C makes use of only 32 keywords which combine with the formal syntax to the form the C
programming language. Note that all keywords are written in lower case - C, like UNIX, uses

Department of Computer Science & Technology, BBIT

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.

The layout of C Programs


The general form of a C program is as follows (don't worry about what everything means at
the moment - things will be explained later):
pre-processor directives
global declarations
main()
{
local variables to function main ;
statements associated with function main ;
}
f1()
{
local variables to function 1 ;
statements associated with function 1 ;
}
f2()
{
local variables to function f2 ;
statements associated with function 2 ;
}
.
.
.

Department of Computer Science & Technology, BBIT

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&&&&

Department of Computer Science & Technology, BBIT

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.

Your First Program


Objectives
Having read this section you should have an understanding of:
1. a pre-processor directive that must be present in all your C programs.
2. a simple C function used to write information to your screen.
3. how to add comments to your programs

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");
}

Department of Computer Science & Technology, BBIT

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

Add Comments to a Program


A comment is a note to yourself (or others) that you put into your source code. All comments
are ignored by the compiler. They exist solely for your benefit. Comments are used primarily
to document the meaning and purpose of your source code, so that you can remember later
how it functions and how to use it. You can also use a comment to temporarily remove a line
of code. Simply surround the line(s) with the comment symbols.
In C, the start of a comment is signalled by the /* character pair. A comment is ended by */.
For example, this is a syntactically correct C comment:
/* This is a comment. */
Comments can extend over several lines and can go anywhere except in the middle of any C
keyword, function name or variable name. In C you can't have one comment within another
comment. That is comments may not be nested. Lets now look at our first program one last
time but this time with comments:
main() /* main function heading */
{

Department of Computer Science & Technology, BBIT

P a g e | 12

printf("\n Hello, World! \n"); /* Display message on */


} /* the screen */
This program is not large enough to warrant comment statements but the principle is still the
same.

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.

Department of Computer Science & Technology, BBIT

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.

Integer Number Variables


The first type of variable we need to know about is of class type int - short for integer. An int
variable can store a value in the range -32768 to +32767. You can think of it as a largish
positive or negative whole number: no fractional part is allowed. To declare an int you use
the instruction:
intvariable name;
For example:
int a;
declares that you want to create an int variable called a.
To assign a value to our integer variable we would use the following C statement:
a=10;
The C programming language uses the "=" character for assignment. A statement of the form
a=10; should be interpreted as take the numerical value 10 and store it in a memory location
associated with the integer variable a. The "=" character should not be seen as an equality
otherwise writing statements of the form:
a=a+10;
will get mathematicians blowing fuses! This statement should be interpreted as take the
current value stored in a memory location associated with the integer variable a; add the
numerical value 10 to it and then replace this value in the memory location associated with a.

Decimal Number Variables


As described above, an integer variable has no fractional part. Integer variables tend to be
used for counting, whereas real numbers are used in arithmetic. C uses one of two keywords
to declare a variable that is to be associated with a decimal number: float and double. They
are each offer a different level of precision as outlined below.

Department of Computer Science & Technology, BBIT

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".

Department of Computer Science & Technology, BBIT

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?

Department of Computer Science & Technology, BBIT

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.

More On Initialising Variables


You can assign an initial value to a variable when you declare it. For example:
int i=1;
sets the int variable to one as soon as it's created. This is just the same as:
int i;
i=l;
but the compiler may be able to speed up the operation if you initialise the variable as part of
its declaration. Don't assume that an uninitialised variable has a sensible value stored in it.
Some C compilers store 0 in newly created numeric variables but nothing in the C language
compels them to do so.
Summary
Variable names:
1. should be lowercase for local variables
2. should be UPPERCASE for symbolic constants (to be discussed later)
3. only the first 31 characters of a variables name are significant
4. must begin with a letter or _ (under score) character

Input and Output Functions


Objectives
Having read this section you should have a clearer idea of one of C's:
1. input functions, called scanf
2. output functions, called printf

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:

Department of Computer Science & Technology, BBIT

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.

Input and Output Functions in More


Detail
One of the advantages of C is that essentially it is a small language. This means that you can
write a complete description of the language in a few pages. It doesn't have many keywords
or data types for that matter. What makes C so powerful is the way that these low-level
facilities can be put together to make higher level facilities.
The only problem with this is that C programmers have a tendency to reinvent the wheel each
time they want to go for a ride. It is also possible to write C programs in a variety of styles
which depend on the particular tricks and devices that a programmer chooses to use. Even
Department of Computer Science & Technology, BBIT

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);

Department of Computer Science & Technology, BBIT

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.

The % Format Specifiers


The % specifiers that you can use in ANSI C are:
Usual variable type Display
%c char single character
%d (%i) int signed integer
%e (%E) float or double exponential format
%f float or double signed decimal
%g (%G) float or double use %f or %e as required
%o int unsigned octal value
%p pointer address stored in pointer
%s array of char sequence of characters
%u int unsigned decimal
%x (%X) int unsigned hex value

Formatting Your Output


The type conversion specifier only does what you ask of it - it convert a given bit pattern into
a sequence of characters that a human can read. If you want to format the characters then you
need to know a little more about the printf function's control string.
Each specifier can be preceded by a modifier which determines how the value will be printed.
The most general modifier is of the form:
flag width.precision
The flag can be any of:

Department of Computer Science & Technology, BBIT

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")

Department of Computer Science & Technology, BBIT

P a g e | 23

will print Hello,


printf("%25s ,Hello")
will print 25 characters with Hello right justified and
printf("%25.3s,Hello")
will print Hello right justified in a group of 25 spaces.
Also notice that it is fine to pass a constant value to printf as in printf("%s,Hello").
Finally there are the control codes:
\b backspace
\f formfeed
\n new line
\r carriage return
\t horizontal tab
\' single quote
\0 null
If you include any of these in the control string then the corresponding ASCII control code is
sent to the screen, or output device, which should produce the effect listed. In most cases you
only need to remember \n for new line.
scanf
Now that we have mastered the intricacies of printf you should find scanf very easy. The
scanf function works in much the same way as the printf. That is it has the general form:
scanf(control string,variable,variable,...)
In this case the control string specifies how strings of characters, usually typed on the
keyboard, should be converted into values and stored in the listed variables. However there
are a number of important differences as well as similarities between scanf and printf.
The most obvious is that scanf has to change the values stored in the parts of computers
memory that is associated with parameters (variables).

Department of Computer Science & Technology, BBIT

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:

Department of Computer Science & Technology, BBIT

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.

Department of Computer Science & Technology, BBIT

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

form of the if statement.


In this case statement1 is carried out if the condition is true and statement2 if the condition
is false.
Notice that it is certain that one of the two statements will be obeyed because the condition
has to be either true or false! You may be puzzled by the semicolon at the end of the if part of
the statement. The if (condition) statement1 part is one statement and the else statement2
part behaves like a second separate statement, so there has to be semi-colon terminating the
first statement

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)

&&&&= (for greater than or equal to )


$$$$=

(for less than or equal to)

==

(to test for equality)

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&&&&

Department of Computer Science & Technology, BBIT

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.

True and False in C


Now we come to an advanced trick which you do need to know about, but if it only confuses
you, come back to this bit later. Most experienced C programmers would wince at the
expression if(a!=0).
The reason is that in the C programming language dosen't have a concept of a Boolean
variable, i.e. a type class that can be either true or false. Why bother when we can use
numerical values. In C true is represented by any numeric value not equal to 0 and false is
represented by 0. This fact is usually well hidden and can be ignored, but it does allow you to
write
if(a != 0) just as if(a)
because if a isn't zero then this also acts as the value true. It is debatable if this sort of
shortcut is worth the three characters it saves. Reading something like
if(!done)
as 'if not done' is clear, but if(!total) is more dubious.

Department of Computer Science & Technology, BBIT

P a g e | 30

Using break and continue Within Loops


The break statement allows you to exit a loop from any point within its body, bypassing its
normal termination expression. When the break statement is encountered inside a loop, the
loop is immediately terminated, and program control resumes at the next statement following
the loop. The break statement can be used with all three of C's loops. You can have as many
statements within a loop as you desire. It is generally best to use the break for special
purposes, not as your normal loop exit. break is also used in conjunction with functions and
case statements which will be covered in later sections.
The continue statement is somewhat the opposite of the break statement. It forces the next
iteration of the loop to take place, skipping any code in between itself and the test condition
of the loop. In while and do-while loops, a continue statement will cause control to go
directly to the test condition and then continue the looping process. In the case of the for
loop, the increment part of the loop continues. One good use of continue is to restart a
statement sequence when an error occurs.
#include $$$$stdio.h&&&&
main()
{
int x ;
for ( x=0 ; x$$$$=100 ; x++) {
if (x%2) continue;
printf("%d\n" , x);
}
}

Here we have used C's modulus operator: %. A expression:


a%b
produces the remainder when a is divided by b; and zero when there is no remainder.
Here's an example of a use for the break statement:
#include $$$$stdio.h&&&&
main()
Department of Computer Science & Technology, BBIT

P a g e | 31

{
int t ;
for ( ; ; ) {
scanf("%d" , &t) ;
if ( t==10 ) break ;
}
printf("End of an infinite loop...\n");
}

Select Paths with switch


While if is good for choosing between two alternatives, it quickly becomes cumbersome
when several alternatives are needed. C's solution to this problem is the switch statement.
The switch statement is C's multiple selection statement. It is used to select one of several
alternative paths in program execution and works like this: A variable is successively tested
against a list of integer or character constants. When a match is found, the statement sequence
associated with the match is executed. The general form of the switch statement is:
switch(expression)
{
caseconstant1: statement sequence; break;
caseconstant2: statement sequence; break;
caseconstant3: statement sequence; break;
.
.
.
default: statement sequence; break;
}
Each case is labelled by one, or more, constant expressions (or integer-valued constants). The
default statement sequence is performed if no matches are found. The default is optional. If
all matches fail and default is absent, no action takes place.
Department of Computer Science & Technology, BBIT

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 and Flowchart

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.

Department of Computer Science & Technology, BBIT

P a g e | 34
2. There are some standard graphics that are used in flowchart as
following:

Figure: Start/Stop terminal box

Figure: Input/Output box

Figure: Process/Instruction box

Figure: Lines or Arrows

Figure: Decision box

Figure: Connector box

Figure: Comment box

Department of Computer Science & Technology, BBIT

P a g e | 35

Figure: Preparation box

Figure: Separate box


Q. Make a flowchart to input temperature, if temperature is less than 32 then print "below freezing"
otherwise print "above freezing"?
Ans.

Figure: Flowchart example of C program

Flowchart for prime number


Q.Draw the flowchart diagram for check a
number is prime number or not.
Ans.
Department of Computer Science & Technology, BBIT

P a g e | 36

Flowchart for check a number is prime or


not as following:

Figure: Flowchart for check given number is


prime number or not

Flowchart is a diagrammatic representation of an algorithm. Flowchart are very helpful in


writing program and explaining program to others.

Symbols Used In Flowchart


Different symbols are used for different states in flowchart, For example: Input/Output and
decision making has different symbols. The table below describes all the symbols that are
used in making flowchart
Symbol

Purpose

Description

Flow line

Used to indicate the flow of logic by connecting symbols.

Terminal(Stop/Start)

Used to represent start and end of flowchart.

Input/Output

Used for input and output operation.

Processing

Used for airthmetic operations and data-manipulations.

Department of Computer Science & Technology, BBIT

P a g e | 37

Symbol

Purpose

Description

Desicion

Used to represent the operation in which there are two


alternatives, true and false.

On-page Connector

Used to join different flowline

Off-page Connector

Used to connect flowchart portion on different page.

Predefined
Process/Function

Used to represent a group of statements performing one


processing task.

Examples of flowcharts in programming


Draw a flowchart to add two numbers entered by user.

Department of Computer Science & Technology, BBIT

P a g e | 38

Draw flowchart to find the largest among three different numbers entered by user.

Draw a flowchart to find all the roots of a quadratic equation ax2+bx+c=0

Department of Computer Science & Technology, BBIT

P a g e | 39

Draw a flowchart to find the Fibonacci series till term1000.

Department of Computer Science & Technology, BBIT

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.

Data Types Part II


Objectives
So far we have looked at local variable now we switch our attention to other types of
variables supported by the C programming language:
1. Global Variables

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.

Constant Data Types

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

Department of Computer Science & Technology, BBIT

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

Department of Computer Science & Technology, BBIT

P a g e | 42

35. Having read this section you should have a good understanding of the use of arrays in
C.

Advanced Data Types


Programming in any language takes a quite significant leap forwards as soon as you learn
about more advanced data types - arrays and strings of characters. In C there is also a third
more general and even more powerful advanced data type - the pointer but more about that
later. In this section we introduce the array, but the first question is, why bother?
There are times when we need to store a complete list of numbers or other data items. You
could do this by creating as many individual variables as would be needed for the job, but this
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
Department of Computer Science & Technology, BBIT

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.

Advanced Data Types


Programming in any language takes a quite significant leap forwards as soon as you learn
about more advanced data types - arrays and strings of characters. In C there is also a third
more general and even more powerful advanced data type - the pointer but more about that
later. In this section we introduce the array, but the first question is, why bother?
There are times when we need to store a complete list of numbers or other data items. You
could do this by creating as many individual variables as would be needed for the job, but this

Department of Computer Science & Technology, BBIT

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];

Department of Computer Science & Technology, BBIT

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

Department of Computer Science & Technology, BBIT

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.

Functions and Prototypes


Objectives
Having read this section you should be able to:
1. program using correctly defined C functions
2. pass the value of local variables into your C functions

Functions - C's Building Blocks


Some programmers might consider it a bit early to introduce the C function - but we think
you can't get to it soon enough. It isn't a difficult idea and it is incredibly useful. You could
say that you only really start to find out what C programming is all about when you start
using functions.
C functions are the equivalent of what in other languages would be called subroutines or
procedures. If you are familiar with another language you also need to know that C only has
functions, so don't spend time looking for the definition of subroutines or procedures - in C
the function does everything!
A function is simply a chunk of C code (statements) that you have grouped together and
given a name. The value of doing this is that you can use that "chunk" of code repeatedly
simply by writing its name. For example, if you want to create a function that prints the word
"Hello" on the screen and adds one to variable called total then the chunk of C code that you
want to turn into a function is just:
printf("Hello");
total = total + l;
To turn it into a function you simply wrap the code in a pair of curly brackets to convert it
into a single compound statement and write the name that you want to give it in front of the
brackets:
demo()
{
printf("Hello");

Department of Computer Science & Technology, BBIT

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."

Functions and Local Variables


Now that the philosophy session is over we have to return to the details - because as it stands
the demo function will not work. The problem is that the variable total isn't declared
anywhere. A function is a complete program sub-unit in its own right and you can declare
variables within it just as you can within the main program. If you look at the main program
we have been using you will notice it is in fact a function that just happens to be called
"main"! So to make demo work we have to add the declaration of the variable total:
demo()
{
int total;
printf("Hello");
total=total+1;
}
Now this raises the question of where exactly total is a valid variable. You can certainly use
total within the function that declares it - this much seems reasonable - but what about other
Department of Computer Science & Technology, BBIT

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.

Making The Connections


Functions are isolated, and whats more nothing survives after they have finished. Put like this
a function doesn't seem to be that useful because you can't get data values in, you can't get
data values out, and they don't remember anything that happens to them!
To be useful there has to be a way of getting data into and out of a function, and this is the
role of the curved brackets. You can define special variables called parameters which are
used to carry data values into a function. Parameters are listed and declared in between the ()
brackets in the function's definition. For example:
sum( int a, int b)
{
int result;
result=a + b;
}
defines a function called sum with two parameters a and b, both integers. Notice that the
result variable is declared in the usual way within the body of the function. Also, notice that
the parameters a and b are used within the function in the same way as normal variables which indeed they are. What is more, they are still local variables and have nothing at all to
do with any variables called a andb defined in any other function.

Department of Computer Science & Technology, BBIT

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.

Department of Computer Science & Technology, BBIT

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:

Department of Computer Science & Technology, BBIT

P a g e | 52

type FunctionName(type declared parameter list)


{
statements that make up the function
}
and of course a function can contain any number of return statements to specify its return
value and bring the function to an end.
There are some special cases and defaults we need to look at before moving on. You don't
have to specify a parameter list if you don't want to use any parameters - but you still need
the empty brackets! You don't have to assign the function a type in which case it defaults to
int. A function doesn't have to return a value and the program that makes use of a function
doesn't have to save any value it does return. For example, it is perfectly OK to use:
sum(1,2);
which simply throws away the result of adding 1 to 2. As this sort of thing offends some
programmers you can use the data type void to indicate that a function doesn't return a value.
For example:
void demo();
is a function with no parameters and no return value.
void is an ANSI C standard data type.
The break statement covered in a previous section can be used to exit a function. The break
statement is usually linked with an if statement checking for a particular value. For example:
if (x==1) break;
If x contained 1 then the fuction would exit and return to the calling program.

Functions and Prototypes


Where should a function's definition go in relation to the entire program - before or after
main()? The only requirement is that the function's type has to be known before it is actually
used. One way is to place the function definition earlier in the program than it is used - for
example, before main(). The only problem is that most C programmers would rather put the
main program at the top of the program listing. The solution is to declare the function
separately at the start of the program. For example:
int sum();
main()
Department of Computer Science & Technology, BBIT

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&AMPR 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.

Department of Computer Science & Technology, BBIT

P a g e | 54

The Standard Library Functions


Some of the "commands" in C are not really "commands" at all but are functions. For
example, we have been using printf and scanf to do input and output, and we have used
rand to generate random numbers - all three are functions.
There are a great many standard functions that are included with C compilers and while these
are not really part of the language, in the sense that you can re-write them if you really want
to, most C programmers think of them as fixtures and fittings. Later in the course we will
look into the mysteries of how C gains access to these standard functions and how we can
extend the range of the standard library. But for now a list of the most common libraries and a
brief description of the most useful functions they contain follows:
1. stdio.h: I/O functions:
1. getchar() returns the next character typed on the keyboard.
2. putchar() outputs a single character to the screen.
3. printf() as previously described
4. scanf() as previously described
2. string.h: String functions

strcat() concatenates a copy of str2 to str1

strcmp() compares two strings

strcpy() copys contents of str2 to str1

ctype.h: Character functions


1

isdigit() returns non-0 if arg is digit 0 to 9

isalpha() returns non-0 if arg is a letter of the alphabet

isalnum() returns non-0 if arg is a letter or digit

islower() returns non-0 if arg is lowercase letter

isupper() returns non-0 if arg is uppercase letter

math.h: Mathematics functions


1

acos() returns arc cosine of arg

asin() returns arc sine of arg

atan() returns arc tangent of arg

Department of Computer Science & Technology, BBIT

P a g e | 55

cos() returns cosine of arg

exp() returns natural logarithim e

fabs() returns absolute value of num

sqrt() returns square root of num

time.h: Time and Date functions


1

time() returns current calender time of system

difftime() returns difference in secs between two times

clock() returns number of system clock cycles since program execution

stdlib.h:Miscellaneous functions
1

malloc() provides dynamic memory allocation, covered in future sections

rand() as already described previously

srand() used to set the starting point for rand()

End of the Course


You've now reached the end of this online tutorial. We have covered a lot of ground - but this
has been a first course in C and there is still plenty to learn. However, as long as you keep in
mind that C is an essentially simple language and how new features are built from this
simplicity you shouldn't have many problems.
You also need to be aware of the fact that C is a very low-level language and as a result
allows programmers to confuse data types and muck around with the bit patterns of the data
in a way that higher level languages would disown! You probably need to make sure that you
understand binary and the way that values are represented to get the best from C.
The final question is, where should you go next? If you have enjoyed learning C then you
probably need to move on to C++ the language most likely to reign supreme in the future!
Without any recommendation try these C++ tutorials:

Input and Output programs


This section contains example programs demonstrating the input and output functions.
This program uses the scanf function.
#include $$$$stdio.h&&&&

Department of Computer Science & Technology, BBIT

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);

Department of Computer Science & Technology, BBIT

P a g e | 57

} while (ch != '.');


printf("\n\n");
printf("Enter some text (type a period to quit)...\n");
while ( (ch = getchar()) != '.') putchar(ch-1);
printf("\n\n");
}

Control Loop programs


This section contains example programs demonstrating the loop construction.
Program using char data type and simple for loop:
#include $$$$stdio.h&&&& /* library header */
main()
{
char ch;
for (ch = 'A' ; ch $$$$= 'z' ; ch++) printf("%c\n" , ch);
}
This program demonstrates the while loop.
#include $$$$stdio.h&&&&
main()
{
int lower , upper , step;

Department of Computer Science & Technology, BBIT

P a g e | 58

float fahr , celsius;


lower = 0 ;
upper = 300;
step = 20 ;
fahr = lower;
while ( fahr $$$$= upper ) {
celsius = (5.0 / 9.0) * (fahr - 32.0);
printf("%4.0f %6.1f\n" , fahr , celsius);
fahr = fahr + step;
}
}
This program uses do-while and for loop constructions and standard library mathematical
functions.
#include $$$$stdio.h&&&&
#include $$$$math.h&&&&
main()
{
int i , j , k;
double a=10.0 , b=.0;
do {
printf("%f\n" , pow(a,b)); /* standard function */
b++;
} while (b$$$$100);
i = 2;
for (j=2 ; j$$$$100 ; j=j+2) {
Department of Computer Science & Technology, BBIT

P a g e | 59

i=i*j ;
printf("%d\n" , i);
}
}

Conditional Execution programs


This section contains example programs demonstrating if else and select statements (also
break and continue statements).
This program demonstrates the if else statement.
#include $$$$stdio.h&&&&
main()
{
int a , b;
printf("Enter two numbers: ");
scanf("%d%d" , &a , &b);
if (b) printf("%d\n" , a/b);
else printf("... cannot divide by zero\n");
}
Another example of if else statement.
#include $$$$stdio&&&&
#include $$$$conio&&&&
main()
{
int a,b;

Department of Computer Science & Technology, BBIT

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;

Department of Computer Science & Technology, BBIT

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;
}
}

Department of Computer Science & Technology, BBIT

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");
}

Structure and Nesting programs


This section contains example programs demonstrating nested block structures.
This program uses nested for loop construction.
#include $$$$stdio.h&&&&
main()
{

Department of Computer Science & Technology, BBIT

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.

Department of Computer Science & Technology, BBIT

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)

Department of Computer Science & Technology, BBIT

P a g e | 66

printf("the answer is %d.\n", count+count);


} /* end of else part */
} /* end of outter for loop */
}

Functions and Prototype programs


This section contains example programs to demonstrate the use of functions.
This is a program to demonstrate the use of functions
1. with no parameters
2. with parameters

#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 */
{

Department of Computer Science & Technology, BBIT

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++)

Department of Computer Science & Technology, BBIT

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];

Department of Computer Science & Technology, BBIT

P a g e | 70

printf("Maximum value generated is %d\n" , max_value) ;


}
This program uses a bubble sort.
#include $$$$stdio.h&&&&
include $$$$stdlib.h&&&&
main()
{
int item[100];
int a,b,t;
int count;
/* read in numbers */
printf("How many numbers ?");
scanf("%d", &count);
for (a=0;a$$$$count;a++) scanf("%d", &item[a]);
/* now sort using bubble sort */
for (a=1; a$$$$count; a++)
for (b=count-1; b&&&&=a; --b) {
/* compare adjacent elements */
if (item[b-1] &&&& item[b]) {
/* exchange elements */
t= item[b-1];
item[b-1] - item[b];
item[b] = t;
}

Department of Computer Science & Technology, BBIT

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

Department of Computer Science & Technology, BBIT

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);

Department of Computer Science & Technology, BBIT

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;

Department of Computer Science & Technology, BBIT

P a g e | 74

printf("Enter a sentence: ");


gets(str);
p = str;
while (*p) {
q = token;
while (*p != ' ' && *p) {
*q = *p;
q++ ; p++;
}
if (*p) p++;
*q = '\0';
printf("%s\n" , token);
}
}

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);

Department of Computer Science & Technology, BBIT

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.

Department of Computer Science & Technology, BBIT

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;

Department of Computer Science & Technology, BBIT

P a g e | 78

void f(struct s_type temp);


void main(void)
{
var1.i=99;
var1.d = 98.6;
f(var1);
}
void f(struct s_type temp)
{
printf("%d %1f", temp.i, temp.d);
}
The following program illustrates how to use a pointer to a structure.
#include $$$$stdio.h&&&&
#include $$$$string.h&&&&
strct s_type {
int i;
char str[80];
} s, *p;
void main(void)
{
p= &s;
s.i = 10; /* this is functionally the same */
p -&&&&i=10; /* as this */
strcpy(p-&&&&str, "I like structures");

Department of Computer Science & Technology, BBIT

P a g e | 79

printf("%d %d %s", s.i, p-&&&&1, p-&&&&str);


}

Department of Computer Science & Technology, BBIT

P a g e | 80

Complex programs combining sections


This example program creates and accesses a simple database.
/**********************************************************/
/* A simple Data Base Program */
/**********************************************************/
# include $$$$stdio.h&&&&
# include $$$$stdlib.h&&&&
# include $$$$string.h&&&&
# define MAX 100 /* constant*/
struct addr { /*struct called list*/
char name[30] ;
char street[40] ;
char town[20] ;
char county[20] ;
char code[10] ;
} list[MAX]; /* 100 records*/
main()
{
int choice;
init_list(); /* initialze the list */
for(;;) {
choice = menu_select(); /* get user's selection*/ switch(choice) {
case 1: enter(); /* enter a new entry */
break;

Department of Computer Science & Technology, BBIT

P a g e | 81

case 2: del(); /* delete an entry */


break;
case 3: show_list(); /* display the list */
break;
case 4: search(); /* find an entry */
break;
case 5: save(); /* save to disk */
break;
case 6: load(); /* read from disk */
break;
case 7: exit(0);
}
}
}
/*********************************************************/
/* Function del */
/*********************************************************/
del()
{
int i;
char str[255];
inputs("enter name: " , str , 30);
i = find(str);
if (i&&&&=0) *list[i].name = '\0' ;

Department of Computer Science & Technology, BBIT

P a g e | 82

else printf("not found\n") ;


}
/**********************************************************/
/* Function display */
/**********************************************************/
display(int i)
{
printf("%s\n" , list[i].name);
printf("%s\n" , list[i].street);
printf("%s\n" , list[i].town);
printf("%s\n" , list[i].county);
printf("%s\n" , list[i].code);
}
/**********************************************************/
/* Function enter */
/**********************************************************/
enter()
{
int i;
for(;;) {
i = find_free(); /* find a free structure */
if(i$$$$0) {
printf("list full\n");
return;

Department of Computer Science & Technology, BBIT

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()
{

Department of Computer Science & Technology, BBIT

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");

Department of Computer Science & Technology, BBIT

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()
{

Department of Computer Science & Technology, BBIT

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");

Department of Computer Science & Technology, BBIT

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()

Department of Computer Science & Technology, BBIT

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();

Department of Computer Science & Technology, BBIT

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()

Department of Computer Science & Technology, BBIT

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");

Department of Computer Science & Technology, BBIT

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 ;

Department of Computer Science & Technology, BBIT

P a g e | 92

for (i=0 ; i$$$$3 ; i++)


if(matrix[i][0] == matrix[i][1] && matrix[i][0] == matrix[i][2])
return matrix[i][0];
for (i=0 ; i$$$$3 ; i++)
if(matrix[0][i] == matrix[1][i] && matrix[0][i] == matrix[2][i])
return matrix[0][i];
if(matrix[0][0] == matrix[1][1] && matrix[1][1] == matrix[2][2])
return matrix[0][0];
if(matrix[0][2] == matrix[1][1] && matrix[1][1] == matrix[2][0])
return matrix[0][2];
return ' ';
}

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++?

Department of Computer Science & Technology, BBIT

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?

Department of Computer Science & Technology, BBIT

P a g e | 94

24. What is IDE?


25. List out some of C compilers.
26. What is header file in C language?
27. Is C language case sensitive?
28. What is Macro? Why do we use macro?
29. What is data type in C?
30. What is the difference between int, char, float and double data types?
31. What is the use of sizeof() function in C?
32. What is modifier in C?
33. What are different types of modifiers in C?
34. What is enum in C?
35. What is void in C?
36. What is token in C?
37. What are the types of C tokens?
38. What is identifier in C?
39. What is keyword in C?
40. List out some keywords available in C language.
41. What is constant in C?
42. What are the types of constants in C?

Department of Computer Science & Technology, BBIT

P a g e | 95

43. What is variable in C?


44. What is the difference between constant and variable in C?
45. Can variable name start with numbers?
46. What is the difference between variable declaration and variable definition in C?
47. What are the different types of variable in C?
48. What is local variable in C?
49. What is global variable in C?
50. What is environment variable in C?
51. What is operator in C?
52. What are the different types of operator in C?
53. What is the syntax for ternary operator in C?
54. What is arithmetic operator in C?
55. What is assignment operator in C?
56. What is the relational operator in C?
57. What is the logical operator in C?
58. What is the bitwise operator in C?
59. What are all decision control statements in C?
60. What are all loop control statements in C?
61. What is the difference between while and do-while loops in C?

Department of Computer Science & Technology, BBIT

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?

Department of Computer Science & Technology, BBIT

P a g e | 97

80. What is the use of #define in C?


81. What is the syntax for comments in C?
82. What is ## operator in C?
83. What is pragma in C? Or how will you execute functions before and after main function in C
program?
84. How will you override an existing macro in C?
85. How will you check whether macro is defined or not in a C program?
86. What is the difference between memcpy() and strcpy() functions in C?
87. What is the difference between memcpy() and memmove() functions in C?
88. Is there any inbuilt library function in C to remove leading and trailing spaces from a
string? How will you remove them in C?
89. What is the difference between strcpy() and strncpy() functions in C?
90. Can array subscripts have negative value in C?
91. What is the difference between array and string in C?
92. What is pointer in C?
93. What is null pointer in C?
94. What is NULL in C?
95. What is void pointer in C?
96. What is dangling pointer in C?
97. What is wild pointer in C?

Department of Computer Science & Technology, BBIT

P a g e | 98

98. What is file pointer in C?


99. When can void pointer and null pointer be used in C?
100.

What is const pointer in C?

101.

Is pointer arithmetic a valid one? Which arithmetic operation supposed to be not valid

in pointer? Why?
102.

Is void pointer arithmetic a valid one? Why?

103.

What is the difference between null and zero?

104.

What is the difference between null pointer and uninitialized pointer in C?

105.

Can array size be declared at run time?

106.

What is memory leak in C?

107.

What happens when we try to access null pointer in C?

108.

What is meant by segmentation fault or memory fault in C?

109.

What is meant by core dump in C?

110.

Can a pointer be freed more than once in C? What happens if we do so? Or can a

pointer be freed twice in C?


111.

What is the size of int pointer and char pointer in C?

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

functions and include them in C library?


115.

Can variable name be start with underscore in C?

Department of Computer Science & Technology, BBIT

P a g e | 99

116.

Can variable name have special symbols in C?

117.

What is inline function in C?

118.

Is it possible to print Hello World without semicolon in C? How?

119.

What is the scope of local, global and environment variables in C?

120.

Why are we using pointers in C?

121.

What is static variable in C?

122.

What is extern and static function in C?

123.

What is the difference between pointer and array in C?

124.

Can a variable be both volatile and constant in C?

125.

What is the use of main () function in C?

Department of Computer Science & Technology, BBIT

P a g e | 100

Question with Answer


What is C language?
The C programming language is a standardized programming language developed in the early
1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It has
since spread to many other operating systems, and is one of the most widely used
programming languages. C is prized for its efficiency, and is the most popular programming
language for writing system software, though it is also used for writing applications.

2. What does static variable mean?


There are 3 main uses for the static.
1. If you declare within a function: It retains the value between function calls
2. If it is declared for a function name: By default function is extern..so it will be visible from
other files if the function declaration is as static..it is invisible for the outer files
3. Static for global variables: By default we can use the global variables from outside files If
it is static global..that variable is limited to with in the file.
#include <stdio.h>
int t = 10;
main(){
int x = 0;
void funct1();
funct1();
printf("After first call \n");
funct1();
printf("After second call \n");
funct1();
printf("After third call \n");
}
void funct1()
{
static int y = 0;
int z = 10;
printf("value of y %d z %d",y,z);
y=y+10;
}

Department of Computer Science & Technology, BBIT

P a g e | 101

value of y 0 z 10 After first call


value of y 10 z 10 After second call
value of y 20 z 10 After third call

3. What are the different storage classes in C?


C has three types of storage: automatic, static and allocated. Variable having block scope and
without static specifier have automatic storage duration.
Variables with block scope, and with static specifier have static scope. Global variables (i.e,
file scope) with or without the the static specifier also have static scope. Memory obtained
from calls to malloc(), alloc() or realloc() belongs to allocated storage class.

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.

5. Can static variables be declared in a header file?


You cant declare a static variable without defining it as well (this is because the storage class
modifiers static and extern are mutually exclusive). A static variable can be defined in a
header file, but this would cause each source file that included the header file to have its own
private copy of the variable, which is probably not what was intended.

6. Can a variable be both constant and volatile?


Yes. The const modifier means that this code cannot change the value of the variable, but that
does not mean that the value cannot be changed by means outside this code.
The function itself did not change the value of the timer, so it was declared const. However,
the value was changed by hardware on the computer, so it was declared volatile. If a variable
is both const and volatile, the two modifiers can appear in either order.

7. Can include files be nested?


Department of Computer Science & Technology, BBIT

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.

8. What is a null pointer?


There are times when its necessary to have a pointer that doesnt point to anything. The
macro NULL, defined in , has a value thats guaranteed to be different from any valid pointer.
NULL is a literal zero, possibly cast to void* or char*.
Some people, notably C++ programmers, prefer to use 0 rather than NULL.
The null pointer is used in three ways:
1) To stop indirection in a recursive data structure.
2) As an error value.
3) As a sentinel value.

9. What is the output of printf("%d") ?


When we write printf("%d",x); this means compiler will print the value of x. But as here,
there is nothing after %d so compiler will show in output window garbage value.

10. What is the difference between calloc() and malloc() ?


calloc(...) allocates a block of memory for an array of elements of a certain size. By default
the block is initialized to 0. The total number of memory allocated will be
(number_of_elements * size).
malloc(...) takes in only a single argument which is the memory required in bytes. malloc(...)
allocated bytes of memory and not blocks of memory like calloc(...).
malloc(...) allocates memory blocks and returns a void pointer to the allocated space, or
NULL if there is insufficient memory available.
calloc(...) allocates an array in memory with elements initialized to 0 and returns a pointer to
the allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode
function to set the new handler mode.

11. What is the difference between printf() and sprintf() ?

Department of Computer Science & Technology, BBIT

P a g e | 103

sprintf() writes data to the character array whereas printf(...) writes data to the standard output
device.

12. How to reduce a final size of executable?


Size of the final executable can be reduced using dynamic linking for libraries.

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.

14. Advantages of a macro over a function?


Macro gets to see the Compilation environment, so it can expand __ __TIME__ __FILE__
#defines. It is expanded by the preprocessor.
For example, you cant do this without macros
#define PRINT(EXPR) printf( #EXPR =%d\n, EXPR)
PRINT( 5+6*7 ) // expands into printf(5+6*7=%d, 5+6*7 );
You can define your mini language with macros:
#define strequal(A,B) (!strcmp(A,B))

15. What is the difference between strings and character arrays?


A major difference is: string will have static storage duration, whereas as a character array
will not, unless it is explicity specified by using the static keyword.
Actually, a string is a character array with following properties:
* the multibyte character sequence, to which we generally call string, is used to initialize an
array of static storage duration. The size of this array is just sufficient to contain these
Department of Computer Science & Technology, BBIT

P a g e | 104

characters plus the terminating NUL character.


* it not specified what happens if this array, i.e., string, is modified.
* Two strings of same value[1] may share same memory area.

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;

Department of Computer Science & Technology, BBIT

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.

22. Difference between const char* p and char const* p


In const char* p, the character pointed by p is constant, so u cant change the value of
character pointed by p but u can make p refer to some other location.
In char const* p, the ptr p is constant not the character referenced by it, so u cant make p
to reference to any other location but u can change the value of the char pointed by p.

23. What is the result of using Option Explicit?


When writing your C program, you can include files in two ways. The first way is to
surround the file you want to include with the angled brackets < and >. This method of
inclusion tells the preprocessor to look for the file in the predefined default location. This
predefined default location is often an INCLUDE environment variable that denotes the path
to your include files.
For instance, given the INCLUDE variable
INCLUDE=C:\COMPILER\INCLUDE;S:\SOURCE\HEADERS; using the #include version
of file inclusion, the compiler first checks the C:\COMPILER\INCLUDE directory for the
specified file. If the file is not found there, the compiler then checks the
S:\SOURCE\HEADERS directory. If the file is still not found, the preprocessor checks the
current directory.
The second way to include files is to surround the file you want to include with double
quotation marks. This method of inclusion tells the preprocessor to look for the file in the
current directory first, then look for it in the predefined locations you have set up. Using the
#include file version of file inclusion and applying it to the preceding example, the
preprocessor first checks the current directory for the specified file. If the file is not found in
the current directory, the C:COMPILERINCLUDE directory is searched. If the file is still not
found, the preprocessor checks the S:SOURCEHEADERS directory.
The #include method of file inclusion is often used to include standard headers such as
stdio.h or stdlib.h.
Department of Computer Science & Technology, BBIT

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.

25. What is the quickest sorting method to use?


The answer depends on what you mean by quickest. For most sorting problems, it just
doesnt matter how quick the sort is because it is done infrequently or other operations take
significantly more time anyway. There are three sorting methods in this authors toolbox that
are all very fast and that are useful in different situations. Those methods are quick sort,
merge sort, and radix sort.

26. When should the volatile modifier be used?


The volatile modifier is a directive to the compilers optimizer that operations involving this
variable should not be optimized in certain ways. There are two special cases in which use of
the volatile modifier is desirable. The first case involves memory-mapped hardware (a device
such as a graphics adaptor that appears to the computers hardware as if it were part of the
computers memory), and the second involves shared memory (memory used by two or more
programs running simultaneously).

Department of Computer Science & Technology, BBIT

P a g e | 108

27. When should the register modifier be used?


The register modifier hints to the compiler that the variable will be heavily used and should
be kept in the CPUs registers, if possible, so that it can be accessed faster.

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.

30. Why n++ executes faster than n+1 ?


The expression n++ requires a single machine instruction such as INR to carry out the
increment operation whereas, n+1 requires more instructions to carry out this operation.

31. Why doesn't the following statement work?


char str[ ] = "Hello" ;
strcat ( str, '!' ) ;
Answer: The string function strcat( ) concatenates strings and not a character. The basic
difference between a string and a character is that a string is a collection of characters,
represented by an array of characters whereas a character is a single character. To make the
above statement work writes the statement as shown below:
strcat ( str, "!" ) ;

32. What is the benefit of using #define to declare a constant?

Department of Computer Science & Technology, BBIT

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.

33. What is the purpose of main( ) function ?


The function main( ) invokes other functions within it.It is the first function to be called when
the program starts execution.
It is the starting function
It returns an int value to the environment that called the program
Recursive call is allowed for main( ) also.
It is a user-defined function
Program execution ends when the closing brace of the function main( ) is reached.
It has two arguments 1)argument count and 2) argument vector (represents strings passed).
Any user-defined name can also be used as parameters for main( ) instead of argc and argv

34. How can I search for data in a linked list?


Unfortunately, the only way to search a linked list is with a linear search, because the only
way a linked lists members can be accessed is sequentially.
Sometimes it is quicker to take the data from a linked list and store it in a different data
structure so that searches can be more efficient.

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

37. Predict the output or error(s) for the following programmes:


void main()
{
int const * p=5;
printf("%d",++(*p));
}
Answer: Compiler error: Cannot modify a constant value.
Explanation: p is a pointer to a "constant integer". But we tried to change the value of the
"constant integer".
38. main()
{
char s[ ]="man";
int i;
Department of Computer Science & Technology, BBIT

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

Department of Computer Science & Technology, BBIT

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);

Department of Computer Science & Technology, BBIT

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.

49. #define int char


main()
{
int i=65;

Department of Computer Science & Technology, BBIT

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

Answer: Compiler Error


Explanation: The structure yy is nested within structure xx. Hence, the elements are of yy are
to be accessed through the instance of structure xx, which needs an instance of yy to be
known. If the instance is created after defining the structure the compiler will not know about
the instance relative to xx. Hence for nested structure yy you have to declare member.

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.

57. #define square(x) x*x


main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Answer: 64

Department of Computer Science & Technology, BBIT

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.

59. #include <stdio.h>


#define a 10
main()
{
#define a 50
printf("%d",a);
}
Answer: 50
Explanation: The preprocessor directives can be redefined anywhere in the program. So the
most recently assigned value will be taken.

60. #define clrscr() 100


main()
{
clrscr();
printf("%d\n",clrscr());
}
Department of Computer Science & Technology, BBIT

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).

63. enum colors {BLACK,BLUE,GREEN}


main()
Department of Computer Science & Technology, BBIT

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.

64. void main()


{
char far *farther,*farthest;
printf("%d..%d",sizeof(farther),sizeof(farthest));
}
Answer: 4..2
Explanation: The second pointer is of char type and not a far pointer

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);
}

Department of Computer Science & Technology, BBIT

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]);
}

Department of Computer Science & Technology, BBIT

P a g e | 122

Answer: Compiler error: Lvalue required in function main


Explanation: Array names are pointer constants. So it cannot be modified.

69. void main()


{
int i=5;
printf("%d",i++ + ++i);
}
Answer: Output Cannot be predicted exactly.
Explanation: Side effects are involved in the evaluation of i

70. void main()


{
int i=5;
printf("%d",i+++++i);
}
Answer: Compiler Error
Explanation: The expression i+++++i is parsed as i ++ ++ + i which is an illegal combination
of operators.

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.

73. #define f(g,g2) g##g2


main()
{
int var12=100;
printf("%d",f(var,12));
}
Answer: 100

74. main()
{
int i=0;
for(;i++;printf("%d",i)) ;
printf("%d",i);
}
Answer: 1

Department of Computer Science & Technology, BBIT

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

Department of Computer Science & Technology, BBIT

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().

Department of Computer Science & Technology, BBIT

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

100 102 104 106 108 110 112 114 116


118 120 122

thus, for the first printf statement a, *a,


**a give address of first element. since the indirection ***a gives the value. Hence, the first
line of the output.
for the second printf a+1 increases in the third dimension thus points to value at 114, *a+1
increments in second dimension thus points to 104, **a +1 increments the first dimension
thus points to 102 and ***a+1 first gets the value at first location and then increments it by 1.
Hence, the output.

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 104 106 108

100 102

104 106 108

1000 1002 1004 1006 1008

ptr

Department of Computer Science & Technology, BBIT

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.

85. What is dangling pointer in c?


If any pointer is pointing the memory address of any variable but after some variable has
deleted from that memory location while pointer is still pointing such memory location. Such
pointer is known as dangling pointer and this problem is known as dangling pointer problem.

86. What are merits and demerits of array in c?


Merits:
(a) We can easily access each element of array.
(b) Not necessity to declare too many variables.
(c) Array elements are stored in continuous memory location.
Demerits:
(a) Wastage of memory space. We cannot change size of array at the run time.
(b) It can store only similar type of data

Department of Computer Science & Technology, BBIT

P a g e | 130

87. Where are the auto variables stored?


Auto variables are stored in main memory and their default value is a garbage value.

88. Why Preincrement operator is faster than Postincrement?


Evaluation of any expression is from left to right. Preincrement is faster because it doesn't
need to save the current value for next instruction whereas Postincrement needs to saves
current value to be incremented after execution of current instruction.

89. Difference between arrays and linked list?


Major differences between arrays and linked lists are: (i) In array consecutive elements are
stored in consecutive memory locations whereas in linked list it not so. (ii) In array address
of next element is consecutive and whereas in linked list it is specified in the address part of
each node.(iii) Linked List makes better use of memory than arrays.(iv) Insertion or deletion
of an element in array is difficult than insertion or deletion in linked list

90. What is the use of typedef?


(i)It increases the portability.
(ii) It simplify the complex declaration and improve readability of the program.

91. What are library Functions?


Library Functions are predefined functions and stored in .lib files.

92. What is a structure?


Structure is a collection of heterogeneous (i.e. related data items which can be of different
types) held together to a single unit. The data items enclosed within a structure are called its
members which may be of data type int, float, char, array etc.
93. What is a pointer?
Pointer is a variable that contains address of another variable in the memory. Pointers are
quite useful in creation of linked data structures (such as linked lst, trees graphs), managing
object allocated memory dynamically, optimize the program to execute faster and use less
memory.

Department of Computer Science & Technology, BBIT

P a g e | 131

94. What are the techniques you use for debugging?


(i)Using compilers features
(ii)Read The Fine Module
(iii)printf( ) debugging
(iv)Code grinding
(v)Assertion

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.

96. What is difference between Structure and Unions?


(i) In structure every member has its own memory whereas in union its members share the
same member space.
(ii) In structure, it is possible to initialize all the members at the same time which is not
possible in case of union.
(iii) A structure requires more space than union(for the same type of members).
(iv) In union different interpretations of the same memory space are possible which is not so
in case of structures.

97. What are the advantages of using Unions?


(i) Efficient use of memory as it it does not demand memory space for its all members rather
it require memory space for its largest member only.
(ii) Same memory space can be interpreted differently for different members of the union.

98. What is the difference between ordinary variable and pointer in C?


An ordinary variable is like a container it can hold any value and we can change the value of
ordinary variable at a time throughout the program .A pointer is a variable that stores the
address of another Variable.

99. What are segment and offset addresses?


When paging technique is performed, the page will breaks into segments and its sequence is
Department of Computer Science & Technology, BBIT

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.

100. When should a type cast be used?


There are two situations in which to use a type cast. The first use is to change the type of an
operand to an arithmetic operation so that the operation will be performed properly.
The second case is to cast pointer types to and from void * in order to interface with functions
that expect or return void pointers. For example, the following line type casts the return value
of the call to malloc() to be a pointer to a foo structure.
struct foo *p = (struct foo *) malloc(sizeof(struct foo));

101. What is the difference between %d and %*d in c language?


%d give the original value of the variable and %*d give the address of the variable.
eg:-int a=10,b=20;
printf("%d%d",a,b);
printf("%*d%*d",a,b);
Result is 10 20 1775 1775 .Here 1775 is the starting address of the memory allocation for the
integer.a and b having same address because of contagious memory allocation.

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.

103. How are pointer variables initialized?


Pointer variable are initialized by one of the following two ways
- Static memory allocation
- Dynamic memory allocation

104. What is modular programming?


If a program is large, it is subdivided into a number of smaller
programs that are called modules or subprograms. If a complex

Department of Computer Science & Technology, BBIT

P a g e | 133

problem is solved using more modules, this approach is known as


modular programming

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.

106. Where are the auto variables stored?


Auto variables are stored in main memory and their default value is a garbage value.

107. What is an lvalue?


An lvalue is an expression to which a value can be assigned. The lvalue
expression is located on the left side of an assignment statement,
whereas an rvalue is located on the right side of an assignment
statement. Each assignment statement must have an lvalue and an
rvalue. The lvalue expression must reference a storable variable in
memory. It cannot be a constant

108. What is an argument? Differentiate between formal arguments and


actual arguments?
An argument is an entity used to pass the data from calling function to
the called function. Formal arguments are the arguments available in
the function definition. They are preceded by their own data types.
Actual arguments are available in the function call.

109. When is a switch statement better than multiple if statements?


A switch statement is generally best to use when you have more than two conditional
expressions based on a single variable of numeric type.

110. Differentiate between a linker and linkage?

Department of Computer Science & Technology, BBIT

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.

111. Define Operator, Operand, and Expression in 'C'?


Operators are symbols which take one or more operands or expressions and perform
arithmetic or logical computations.
Operands are variables or expressions which are used in operators to evaluate the expression.
Combination of operands and operators form an expression.

112. What will be the result of the following code?


#define TRUE 0 // some code
while(TRUE)
{
// some code
}
Answer: This will not go into the loop as TRUE is defined as 0.

113. What will be printed as the result of the operation below:


main()
{
int a=0;
if(a==0)
printf(Cisco Systemsn);
printf(Cisco Systemsn);
}
Answer: Two lines with Cisco Systems will be printed.

114. Do you know pragma directives in c?


Pragma is implementation specific directive i.e each pragma directive has different
implementation rule and use. If compiler does not recognize particular pragma it simply
ignore that pragma statement without showing any error or warning message and execute the
whole program assuming this pragma statement is not present.

Department of Computer Science & Technology, BBIT

P a g e | 135

115. Predict the output or error


main()
{
clrscr();
}
clrscr();
Ans: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).

116. Predict the output or error


enum colors {BLACK,BLUE,GREEN}
main()
{
printf("%d..%d..%d",BLACK,BLUE,GREEN);
return(1);
}
Answer: 0..1..2
Explanation: enum assigns numbers starting from 0, if not explicitly defined.

117. Predict the output or error


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.

118. what will be the position of the file marker?


a: fseek(ptr,0,SEEK_SET);
b: fseek(ptr,0,SEEK_CUR);
Ans: a: The SEEK_SET sets the file position marker to the starting of the file.
b: The SEEK_CUR sets the file position marker to the current position
of the file.
Department of Computer Science & Technology, BBIT

P a g e | 136

119. Predict the output or error


main()
{
main();
}
Ans: Runtime error : Stack overflow.
Explanation: main function calls itself again and again. Each time the function is called its
return address is stored in the call stack. Since there is no condition to terminate the function
call, the call stack overflows at runtime. So it terminates the program and results in an error.

120. Predict the output or error


main()
{
int i=5,j=6,z;
printf("%d",i+++j);
}
Answer:11
Explanation:the expression i+++j is treated as (i++ + j)

121. Predict the output or error


main()
{
int k=1;
printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");
}
Ans: 1==1 is TRUE
Explanation: When two strings are placed together (or separated by white-space) they are
concatenated (this is called as "stringization" operation). So the string is as if it is given as
"%d==1 is %s". The conditional operator( ?: ) evaluates to "TRUE".

122. What is use of void data type?


Void is an empty data type normally used as a return type in C/C++, C#, Java
functions/methods to declare that no value will be return by the function.
The another used of void is to declare the pointer in C/C++ where It is not sure what data
type is addressed by the pointer.

Department of Computer Science & Technology, BBIT

P a g e | 137

123. four type of scope in c:


Block scope.
Function scope.
File scope.
Program scope.

124. Tell any five properties of auto variables?


auto variables are defined inside a function. A variable declared inside the function without
storage class name is, by default, an auto variable. These functions are declared on the stack.
The stack provides temporary storage.

125. What is automatic type promotion in c?


In c if two operands are of different data type in a binary operation then before performing
any operation compiler will automatically convert the operand of lower data type to higher
data type .This phenomenon is known as automatic type conversion. For example:
int a=10,c;
float b=5.5f;
c=a+b;
Here a int variable while b is float variable. So before performing addition operation value of
the variable a (Lower data type) will automatically convert into float constant (higher data
type) then it will perform addition operation.

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.

127. What is command line argument?


Getting the arguments from command prompt in c is known as command line arguments. In
c main function has three arguments.
They are:
Argument counter
Argument vector
Environment vector

Department of Computer Science & Technology, BBIT

P a g e | 138

128. void main(){


int x=5,y=10,z=15,val;
val=sum(x,(y=0,z=0,y),z);
clrscr();
printf("%d",val);
getch();
}
sum(int x,int y,int z){
return x+y+z;
}
Answer:20
Explanation: In the above program comma after Y=0 &Z=0 are behaving as operator.

129. what is nested structure?


A structure is a collection of one or more variables, possibly of different data types, grouped
together under a single name for convenient handling. Structures can contain other structures
as members; in other words, structures can nest.

130. What is slack byte in structure?


To store any type of data in structure there is minimum fixed byte which must be reserved by
memory. This minimum byte is known as word boundary. Word boundary depends upon
machine. TURBO C is based on 8086 microprocessor which has two byte word boundary. So
any data type reserves at least two byte space.

131.What is prototype of printf function?


Prototype of printf function is:
int printf( const char *format ,)

132.What is difference between declaration and definition?


During declaration we just specify the type and no memory is allocated to the variable. But
during the
definition an initial value is assigned and memory is allocated to the variable.

133. What is function recursion?

Department of Computer Science & Technology, BBIT

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();
}

134. What is self referential structure ?


A self-referential structure is one of the data structures which refer to the pointer to (points) to
another structure of the same type.

135. What is far pointer?


The pointer which can point or access whole the residence memory of RAM i.e. which can
access all 16 segments is known as far pointer.

136. What is pascal and cdecl keyword in c language?


There are two types of parameters passing conventions in c:
1. pascal: In this style function name should (not necessary ) in the uppercase .First parameter
of function call is passed to the first parameter of function definition and so on.
2. cdecl: In this style function name can be both in the upper case or lower case. First
parameter of function call is passed to the last parameter of function definition. It is default
parameter passing convention.

137. What is use of #pragma inline directive in c language?


#pragma inline only tells the compiler that source code of program contain inline assembly
language code .In c we can write assembly language program with help of asm keyword.

138. What is the meaning of multilevel pointers in c?


A pointer is pointer to another pointer which can be pointer to others pointers and so on is
known as multilevel pointers. We can have any level of pointers.

Department of Computer Science & Technology, BBIT

P a g e | 140

139. What is huge pointer in c?


The pointer which can point or access whole the residence memory of RAM i.e. which can
access all the 16 segments is known as huge pointer.

140. Is it possible to rename any function in c?


Yes, we can rename any function using typedef keyword. It is useful when function
declaration is too complex and we have to give any simple name or if we have to create more
numbers of function of the same type.

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.

142. What is difference between .com program and .exe program?


Both .com and .exe program are executable program but .com program execute faster than
.exe program. All drivers are .com program. .com file has higher preference than .exe For
example:

143. Difference between TSR and TSO program


TSO means terminate but stay outside. It is that program, which release the main memory
after the execution of the program. Example ms paint, notepad, turbo c compilers etc.
TSR means terminate but stay residence .It is those program, which after the execution of the
program does not release the RAM (main memory).e.g. antivirus.

144. Describe turbo c compiler?


Turbo c is an IDE of c programming language created by Borland. Turbo C 3.0 is based on
MS DOS operation system. It is one of the most popular c compilers. It uses 8086
microprocessor which is 16 bit microprocessor. It has 20 address buses and 16 data bus. Its
word length is two byte.

145. Out of fgets() and gets() which function is safe to use and why?

Department of Computer Science & Technology, BBIT

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 ().

146. Difference between strdup and strcpy?


Both copy a string. strcpy wants a buffer to copy into. strdup allocates a buffer using
malloc().
Unlike strcpy(), strdup() is not specified by ANSI .

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.

149. What are the uses of a pointer?


(i)It is used to access array elements
(ii)It is used for dynamic memory allocation.
(iii)It is used in Call by reference
(iv)It is used in data structures like trees, graph, linked list etc.

150.In header files whether functions are declared or defined?


Functions are declared within header file. That is function prototypes exist in a header file,not
function bodies. They are defined in library (lib).

151. Difference between pass by reference and pass by value?


Pass by reference passes a pointer to the value. This allows the callee to modify the variable
directly.Pass by value gives a copy of the value to the callee. This allows the callee to modify
the value without modifying the variable. (In other words, the callee simply cannot modify
the variable, since it lacks a reference to it.)
Department of Computer Science & Technology, BBIT

P a g e | 142

152. What are enumerations?


They are a list of named integer-valued constants. Example:enum color { black ,
orange=4,yellow, green, blue, violet };This declaration defines the symbols black,
orange, yellow, etc. to have the values 1, 4, 5, etc. The difference between an
enumeration and a macro is that the enum actually declares a type, and therefore can be type
checked.

153. Are pointers integer?


No, pointers are not integers. A pointer is an address. It is a positive number.

154. What is static memory allocation?


Compiler allocates memory space for a declared variable. By using the address of operator,
the reserved address is obtained and this address is assigned to a pointer variable. This way of
assigning pointer value to a pointer variable at compilation time is known as static memory
allocation.

155. What is dynamic memory allocation?


A dynamic memory allocation uses functions such as malloc() or calloc() to get memory
dynamically. If these functions are used to get memory dynamically and the values returned
by these function are assigned to pointer variables, such a way of allocating memory at run
time is known as dynamic memory allocation.

156. What modular programming?


If a program is large, it is subdivided into a number of smaller programs that are called
modules or subprograms. If a complex problem is solved using more modules, this approach
is known as modular programming

157. What is a function?


A large program is subdivided into a number of smaller programs or subprograms. Each
subprogram specifies one or more actions to be performed for the larger program. Such sub
programs are called functions.

Department of Computer Science & Technology, BBIT

P a g e | 143

158. Difference between formal argument and actual argument?


Formal arguments are the arguments available in the function definition. They are preceded
by their own data type. Actual arguments are available in the function call. These arguments
are given as constants or variables or expressions to pass the values to the function.

159. what are C tokens?


There are six classes of tokens: identifier, keywords, constants, string literals, operators and
other separators.

160. What are C identifiers?


These are names given to various programming element such as variables, function, arrays.It
is a combination of letter, digit and underscore.It should begin with letter. Backspace is not
allowed.

161. Difference between syntax vs logical error?


Syntax Error
These involves validation of syntax of language.
compiler prints diagnostic message.
Logical Error
logical error are caused by an incorrect algorithm or by a statement mistyped in such a way
that it doesnt violet syntax of language.
difficult to find.

162. What are the facilities provided by preprocessor?


file inclusion
substitution facility
conditional compilation

163.What do the functions atoi(), itoa() and gcvt() do?


atoi() is a macro that converts integer to character.
itoa() It converts an integer to string
gcvt() It converts a floating point number to string

Department of Computer Science & Technology, BBIT

P a g e | 144

164. What is FILE?


FILE is a predefined data type. It is defined in stdio.h file.

165. What is a file?


A file is a region of storage in hard disks or in auxiliary storage devices.It contains bytes of
information .It is not a data type.

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.

Department of Computer Science & Technology, BBIT

P a g e | 145

11.Write a program to print the following patterns using for loop


a. *
**
***
****
*****
b. *
**
***
****
*****
c. 1
12
123
1234
12345
12.Write a program to print all the prime numbers between 1 to 100.
13.Write a program to print Fibonacci Series.
14.Write a program to calculate factorial of a number using for loop
15.Write a program to enter a three digit number and print its reverse and
then calculate the sum of its digits.
16.Write a program to determine whether a given number is an Armstrong
number or not.
17.Write a program to sum the following series
a. 1 + + 1/3 + 1/n
b. 1/12 + 2 + 1/n2
c. + 1/3 + . n/(n+1)
18.A company decides to give bonus to all its employees on Diwali. A 5%
bonus on salary is given to the male worker and 10% bonus on salary to
female workers. Write a program to enter the salary and sex of the
employee. If the salary is less than 10,000 then the employee gets an
extra 2% bonus on salary. Calculate the bonus and display the salary that
the employee will get.
19.Write a program to calculate area of circle using function.
20.Write a program to calculate area of triangle using function.
21.Write a program to calculate factorial of a number using function.
22.Write a program to calculate add two numbers using function.
23.Write a program to find largest of n numbers using array.
24.Write a program to find the position of smallest of n numbers using array.
25.Write a program to find the sum of all elements in an array.
Department of Computer Science & Technology, BBIT

P a g e | 146

26. Write a program to sort a given array.


27.Write a program to concatenate two strings.
28.Write a program to copy a string into another string.
29.Write a program to compare two strings.
30.Write a program to extract a sub string from a string.

Department of Computer Science & Technology, BBIT

S-ar putea să vă placă și