C Programming AllClasses-Outline-1-98
C Programming AllClasses-Outline-1-98
1.1 Introduction
C is a general-purpose, structured programming language. Its instructions
consist of terms that resemble algebraic expressions, augmented by certain
English keywords such as if, else, for, do and while. C was the offspring of
the ‘Basic Combined Programming Language’ (BPCL) called B, developed in
the 1960’s at Cambridge University. B language was modified by Dennis
Ritchie and was implemented at Bell laboratories in 1972. The new language
was named C. Since it was developed along with the UNIX operating system,
it is strongly associated with UNIX. This operating system, which was also
developed at Bell laboratories, was coded almost entirely in C.
In C, the type of a variable determines what kinds of values it may take on.
The type of an object determines the set of values it can have and what
operations can be performed on it. This is a fairly formal, mathematical
definition of what a type is, but it is traditional (and meaningful). There are
several implications to remember:
1. The “set of values'' is finite. C's int type cannot represent all of the integers;
every version of C is accompanied by its own set of library functions, which are
written for the particular characteristics of the host computer.
A C program can be viewed as a group of building blocks called functions. A
function is a subroutine that may include one or more statements designed to
perform a specific task. To write a C program we first create functions and then
put them together. A C program may contain one or more sections shown in
Fig. 1.1.
The documentation section consists of a set of comment (remarks) lines giving
the name of the program, the author and other details which the programmer
would like to use later. Comments may appear anywhere within a program, as
long as they are placed within the delimiters /* and */ (e.g., /*this is a
comment*/). Such comments are helpful in identifying the program’s principal
features or in explaining the underlying logic of various program features.
Documentation section
Link section
Definition section
Global declaration section
main() function section
{
Declaration part
Executable part
}
Subprogram section
Function 1
Function 2
Function n
variables are called global variables and are declared in the global declaration
section that is outside of all the functions.
Every C program must have one main function section. This section contains
two parts, declaration part and executable part. The declaration part declares
all the variables used in the executable part. There is at least one statement in
the executable part. These two parts must appear between opening and
closing braces ({ and }). The program execution begins at the opening brace
and ends at the closing brace. The closing brace of the main function section
is the logical end of the program. All statements in the declaration and
executable parts end with a semicolon(;).
The subprogram section contains all the user-defined functions that are called
in the main function. User-defined functions are generally placed immediately
after the main function, although they may appear in any order.
All sections, except the main function section may be absent when they are
not required.
Self Assessment Questions
1. Using C language programmers can write their own library functions.
(True/False)
2. C is a _______ level programming language.
3. The documentation section contains a set of _________ lines.
4. Every C program must have one main() function. (True/False)
The second line says that we are defining a function named main. Most of the
time, we can name our functions anything we want, but the function name main
is special: it is the function that will be “called'' first when our program starts
running. The empty pair of parentheses indicates that our main function
accepts no arguments, that is, there isn't any information which needs to be
passed in when the function is called.
The braces { and } surround a list of statements in C. Here, they surround the
list of statements making up the function main.
The line
printf("Hello, world!\n");
is the first statement in the program. It asks that the function printf be called;
printf is a library function which prints formatted output. The parentheses
surround printf's argument list: the information which is handed to it which it
should act on. The semicolon at the end of the line terminates the statement.
printf 's first (and, in this case, only) argument is the string which it should
print. The string, enclosed in double quotes (""), consists of the words “Hello,
world!'' followed by a special sequence: \n. In strings, any two-character
sequence beginning with the backslash \ represents a single special character.
The sequence \n represents the “ 'new line'' character, which prints a carriage
return or line feed or whatever it takes to end one line of output and move down
to the next. (This program only prints one line of output, but it's still important
to terminate it.)
The second line in the main function is
return 0;
In general, a function may return a value to its caller, and main is no exception.
When main returns (that is, reaches its end and stops
functioning), the program is at its end, and the return value from main tells the
operating system (or whatever invoked the program that main is the main
function of) whether it succeeded or not. By convention, a return value of 0
indicates success.
Program 1.1: Area of a circle
Here is an elementary C program that reads in the radius of a circle,
calculates the area and then writes the calculated result.
#include <stdio.h> /* Library file access */
/* program to calculate the area of a circle */ /* Title (Comment) */
main() /* Function heading */
{
float radius, area; /*Variable declarations */
printf(“Radius=?”); /* Output statement(prompt) */
scanf(“%f”, &radius); /* Input statement */
area=3.14159*radius*radius; /* Assignment statement */
printf(“Area=%f” ,area); /* Output statement */
1.4 Constants
Constants in C refer to fixed values that do not change during the execution
of a program. C supports several types of constants as illustrated in Fig. 1.1.
Constants
Fig. 1.1
1.4.1 Integer constants
An integer constant refers to a sequence of digits. There are three types of
integers, namely decimal, octal and hexadecimal.
An octal integer constant consists of any combination of digits from the set 0
through 7, with a leading 0.
Examples: 045, 0, 0567
A sequence of digits preceded by 0x or 0X is considered as hexadecimal
integer. They may also include alphabets A through F or a through f. The letters
A through F represent numbers 10 through 15.
Examples: 0X6, 0x5B, 0Xbcd, 0X
The largest integer value that can be stored is machine-dependent. It is 32767
on 16-bit machines and 2,147,483,647 on 32-bit machines. It is also possible
to store larger integer constants on these machines by appending qualifiers
such as U, L and UL to the constants.
Examples: 54637U or 54637u (unsigned integer)
65757564345UL or 65757564345ul (unsigned long integer)
7685784L or 7685784l (long integer)
Program 1.1: Program to represent integer constants on a 16-bit
computer
/* Integer numbers on 16-bit machine */ main()
{
printf(“Integer values\n\n”);
printf(“%d %d %d\n”, 32767,32767+1,32767+10);
printf(“\n”);
printf(“Long integer values\n\n”);
printf(“%ld %ld %ld\n”, 32767L, 32767L+1L, 32767L+10L);
}
Type and execute the above program and observe the output
1.4.2 Real constants
The numbers containing fractional parts like 67.45 are called real (or floating
point) constants.
Examples: 0.0045, -8.5, +345.678
A real number may also be expressed in exponential (scientific) notation. The
general form is:
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an
integer. The exponent is an integer number with an optional plus or minus sign.
Manipal University Jaipur Page No.: 8
Programming in C Unit 1
The letter e separating the mantissa and the exponent can be written in either
lowercase or uppercase.
Examples: 04e4, 12e-2, -1.3E-2
7500000000 may be written as 7.5E9 or 75E8.
Floating point constants are normally represented as double-precision
quantities. However, the suffixes f or F may be used to force single precision
and l or L to extend double-precision further.
1.4.3 Character constants
A single character constant (or simple character constant) contains a single
character enclosed within a pair of single quote marks.
Examples: ‘6’, ‘X’, ‘;’
Character constants have integer values known as ASCII values. For example,
the statement
printf(“%d”, ‘a’);
would print the number 97, the ASCII value of the letter a. Similarly, the
statement
printf(“%c”, 97);
would print the letter a.
1.4.4 String constants
A string constant is a sequence of characters enclosed within double quotes.
The characters may be letters, numbers, special characters and blank space.
Examples: “Hello!”, “1947”, “5+3”
1.4.5 Backslash character constants
C supports some special backslash character constants that are used in output
functions. A list of such backslash character constants is given in Table 1.1.
Note that each one of them represents one character, although they consist of
two characters. These character combinations are called escape sequences.
Table 1.1: Backslash character constants
Constant Meaning
‘\b’ back space
‘\f’ form feed
‘\n’ new line
Informally, a variable (also called an object) is a place where you can store a
value so that you can refer to it unambiguously. A variable needs a name. You
can think of the variables in your program as a set of boxes, each with a label
giving its name; you might imagine that storing a value “in'' a variable consists
of writing the value on a slip of paper and placing it in the box.
Now let us see how integers and variables are declared. A declaration tells the
compiler the name and type of a variable you'll be using in your program. In its
simplest form, a declaration consists of the type, the name of the variable, and
a terminating semicolon: int i;
The above statement declares an integer variable i. long int i1, i2;
We can also declare several variables of the same type in one declaration,
separating them with commas as shown above.
The placement of declarations is significant. You can't place them just
anywhere (i.e. they cannot be interspersed with the other statements in your
program). They must either be placed at the beginning of a function, or at the
beginning of a brace-enclosed block of statements, or outside of any function.
Furthermore, the placement of a declaration, as well as its storage class,
controls several things about its visibility and lifetime, as we'll see later.
You may wonder why variables must be declared before use. There are two
reasons:
1. It makes things somewhat easier on the compiler; it knows right away what
kind of storage to allocate and what code to emit to store and manipulate
each variable; it doesn't have to try to intuit the programmer's intentions.
2. It forces a bit of useful discipline on the programmer: you cannot introduce
variables wherever you wish; you must think about them enough to pick
appropriate types for them. (The compiler's error messages to you, telling
you that you apparently forgot to declare a variable, are as often helpful as
they are a nuisance: they're helpful when they tell you that you misspelled
a variable, or forgot to think about exactly how you were going to use it.)
Most of the time, it is recommended to write one declaration per line. For the
most part, the compiler doesn't care what order declarations are in. You can
order the declarations alphabetically, or in the order that they're used, or to put
related declarations next to each other. Collecting all variables of the same
type together on one line essentially orders declarations by type, which isn't a
very useful order (it's only slightly more useful than random order).
A declaration for a variable can also contain an initial value. This initializer
consists of an equal sign and an expression, which is usually a single constant:
int i = 1;
int i1 = 10, i2 = 20;
Self Assessment Questions
10. The size of the Integers in C language is same in all the machines.
(True/False)
11. A _______ is a place where we can store values.
12. Size of int is _________ bits.
13. Which of the following tells the compiler the name and type of a variable
you'll be using in your program? ( declaration)
(a) declaration
(b) variables
(c) integers
(d) assignments
14. The _________ consists of an equal sign and an expression, which is
usually a single constant. (initializer)
15. A single declaration statement can contain variables of different types.
(True/False)
It's usually a matter of style whether you initialize a variable with an initializer
in its declaration or with an assignment expression near where you first use it.
That is, there's no particular difference between
int a = 10;
and
int a;
/* later... */ a = 10;
Self Assessment Questions
16. In C, variable names are case sensitive. (True/False)
17. A variable name in C consists of letters, numbers and ________ .
1.7 Summary
C is a general-purpose, structured programming language. Its instructions
consist of terms that resemble algebraic expressions, augmented by certain
English keywords such as if, else, for, do and while. C is characterized by the
ability to write very concise source programs, due in part to the large number
of operators included within the language. Every C program consists of one or
more functions, one of which must be called main. The program will always
begin by executing the main function. Additional function definitions may
precede or follow main.
Integers are whole numbers with a range of values supported by a particular
machine. Generally, integers occupy one word of storage, and since the word
sizes of machines vary (typically, 16 or 32 bits) the size of an integer that can
be stored depends on the computer. A variable (also called an object) is a
place where you can store a value. A declaration tells the compiler the name
and type of a variable you'll be using in your program. The assignment operator
= assigns a value to a variable.
6. A signed integer uses one bit for sign and remaining bits for the magnitude
of the number, whereas an unsigned integer uses all the bits to represent
magnitude.
7. A declaration consists of the type, the name of the variable, and a
terminating semicolon.
8. Variables (the formal term is “identifiers'') consist of letters, numbers, and
underscores. The capitalization of names in C is significant. You may not
use keywords (the words such as int and for which are part of the syntax
of the language) as the names of variables or functions (or as identifiers of
any kind).
9. The assignment operator (=) assigns a value to a variable.
1.11 Exercises
1. Explain the basic structure of a C program with an example.
2. What are the different steps in executing a C program?
3. Write a C program to convert Celsius to Fahrenheit and vice versa.
4. Write a program in C to add, subtract, multiply any 3 numbers.
Unit 2 Operators and Expressions
Structure:
2.1 Introduction
Objectives
2.2 Arithmetic Operators
2.3 Unary Operators
2.4 Relational and Logical Operators
2.5 The Conditional Operator
2.6 Library Functions
2.7 Bitwise Operators
2.8 The Increment and Decrement Operators
2.9 The Size of Operator
2.10 Precedence of operators
2.11 Summary
2.12 Terminal Questions
2.13 Answers to Self Assessment Questions
2.14 Answers to Terminal Questions
2.15 Exercises
2.1 Introduction
In the previous unit, you learned about the various features and structure of C
programs. You also learned how the variables in C are declared. In this unit,
you will learn about the operators that are available in C and how the
expressions can be formed to get the solutions of any problems.
C supports a rich set of operators. An operator is a symbol that tells the
computer to perform certain mathematical or logical manipulations. Operators
are used in programs to manipulate data and variables. They usually form a
part of the mathematical or logical expressions.
C operator can be classified into a number of categories. They include:
1. Arithmetic operators
2. Unary operator
3. Relational operators
4. Logical operators
5. Conditional operator
6. Bitwise operators
7. Increment and Decrement operators
Objectives:
After studying this subject, you should be able to:
8. explain different categories of operators
9. use operators on many operands
10. distinguish precedence and associativity of operators
11. explain library functions and their use
12. write small programs using different types of operators
days=days%30;
printf(“Months=%d Days=%d”, months,days);
}
+, -, *, and /. The relational operators take two values, look at them, and “return''
a value of 1 or 0 depending on whether the tested relation was true or false.
The complete set of relational operators in C is:
> less than
> = less than or equal
> greater than
> = greater thanor equal
== equal
!= not equal
For example, 1 < 2 is true(1), 3 > 4 is false(0), 5 == 5 is true(1), and 6 != 6 is
false(0).
The equality-testing operator is ==, not a single =, which is assignment. If you
accidentally write
if(a = 0)
(and you probably will at some point; everybody makes this mistake), it will not
test whether a is zero, as you probably intended. Instead, it will assign 0 to a,
and then perform the “true'' branch of the if statement if a is nonzero. But a will
have just been assigned the value 0, so the “true'' branch will never be taken!
(This could drive you crazy while debugging -- you wanted to do something if
a was 0, and after the test, a is 0, whether it was supposed to be or not, but
the “true'' branch is nevertheless not taken.)
The relational operators work with arbitrary numbers and generate true/false
values. You can also combine true/false values by using the Boolean
operators(also called the logical operators), which take true/false values as
operands and compute new true/false values. The three Boolean operators
are:
&& AND
|| OR
! NOT (takes one operand,“unary'')
The && (“and'') operator takes two true/false values and produces a true (1)
result if both operands are true (that is, if the left-hand side is true and the right-
hand side is true). The || (“or'') operator takes two true/false values and
produces a true (1) result if either operand is true. The ! (“not'') operator takes
a single true/false value and negates it, turning false to true and true to false
(0 to 1 and nonzero to 0). The logical operators && and || are used when we
Here we're expressing the relation “i is between 1 and 10'' as “1 is less than i
and i is less than 10.''
It's important to understand why the more obvious expression
if(1 < i < 10) /* WRONG */
would not work. The expression 1 < i < 10 is parsed by the compiler
analogously to 1 + i + 10. The expression 1 + i + 10 is parsed as (1 + i) + 10
and means “add 1 to i, and then add the result to 10.'' Similarly, the expression
1 < i < 10 is parsed as (1 < i) < 10 and means “see if 1 is less than i, and then
see if the result is less than 10.'' But in this case, “the result'' is 1 or 0,
depending on whether i is greater than 1. Since both 0 and 1 are less than 10,
the expression 1 < i < 10 would always be true in C, regardless of the value of
i!
Relational and Boolean expressions are usually used in contexts such as an if
statement, where something is to be done or not done depending on some
condition. In these cases what's actually checked is whether the expression
representing the condition has a zero or nonzero value. As long as the
expression is a relational or Boolean expression, the interpretation is just what
we want. For example, when we wrote
if(x > max)
the > operator produced a 1 if x was greater than max, and a 0 otherwise. The
if statement interprets 0 as false and 1 (or any nonzero value) as true.
But what if the expression is not a relational or Boolean expression? As far as
C is concerned, the controlling expression (of conditional statements like if)
can in fact be any expression: it doesn't have to “look like'' a Boolean
expression; it doesn't have to contain relational or logical operators. All C looks
at (when it's evaluating an if statement, or anywhere else where it needs a
true/false value) is whether the expression evaluates to 0 or nonzero. For
example, if you have a variable x, and you want to do something if x is nonzero,
where x or f() do not have obvious “Boolean'' names, you can read them as “if
x is nonzero'' or “if f() returns nonzero.''
Self Assessment Questions
3. The logical operators ___________ and _________ are used when
we want to test more than one condition and make decisions.
4. State whether the following statement is correct or not.
(Correct/Incorrect)
if(a<4<c)
b=c;
4.3 The Conditional Operator
The Conditional operator (ternary operator) pair “?:” is available in C to
construct conditional expressions of the form expr1?expr2:expr3
where expr1, expr2 and expr3 are expressions.
The operator ? : works as follows: expr1 is evaluated first. If it is
nonzero(true), then the expression expr2 is evaluated and becomes the value
of the expression. If expr1 is false, expr3 is evaluated and its value becomes
the value of the expression. For example, consider the following statements:
a=100; b=200;
c=(a>b)?a:b;
In this example, c will be assigned the value of b. This can be achieved using
the if..else statements as follows: if(a>b) c=a;
else c=b;
A typical set of library functions will include a large number of functions that
are common to most C compilers, such as those shown in table 2.1.
Function Purpose
abs(i) Return the absolute value of ( i is integer)
ceil(d) Round up to the next integer value(the smallest integer that is
greater than or equal to d)
cos(d) Return the cosine of d
exp(d) Raise e to the power d(e=Naperian constant)
fabs(d) Return the absolute value of d(d is double)
floor(d) Round down to the next integer value(the largest integer that does
not exceed d)
getchar() Enter a character from the standard input device
log(d) Return the natural logarithm of d
pow(d1,d2) Return d1 raised to the power d2
putchar(c) Send a character to the standard output device
rand() Return a random positive integer
sin(d) Return sine of d
sqrt(d) Return the square root of d
tan(d) Return the tangent of d
toascii(c) Convert value of argument to ASCII
tolower(c) Convert letter to lowercase
toupper(c) Convert letter to uppercase
Table 2.1
Program 2.2: Program to convert lowercase to uppercase
#include <stdio.h> /* Input/Output functions are available in stdio.h */
#include<ctype.h> /* Character functions are available in the file ctype.h */
main()
/* read a lowercase character and print its uppercase equivalent */ {
int lower, upper;
lower=getchar();
upper=toupper(lower);
putchar(upper);
}
Example:
x+=y+1;
This is same as the statement
x=x+(y+1);
The ++ and -- operators apply to one operand (they're unary operators). The
expression ++i adds 1 to i, and stores the incremented result back in i. This
means that these operators don't just compute new values; they also modify
the value of some variable. (They share this property -- modifying some
variable -- with the assignment operators; we can say that these operators all
have side effects. That is, they have some effect, on the side, other than just
computing a new value.)
The incremented (or decremented) result is also made available to the rest of
the expression, so an expression like k = 2 * ++i
means “add one to i, store the result back in i, multiply it by 2, and store that
result in k.'' (This is a pretty meaningless expression; our actual uses of ++
later will make more sense.)
Both the ++ and -- operators have an unusual property: they can be used in
two ways, depending on whether they are written to the left or the right of the
variable they're operating on. In either case, they increment or decrement the
variable they're operating on; the difference concerns whether it's the old or
the new value that's “returned'' to the surrounding expression. The prefix form
++i increments i and returns the incremented value. The postfix form i++
increments i, but returns the prior, nonincremented value. Rewriting our
previous example slightly, the expression k = 2 * i++
means “take i's old value and multiply it by 2, increment i, store the result of
the multiplication in k.''
The distinction between the prefix and postfix forms of ++ and -- will probably
seem strained at first, but it will make more sense once we begin using these
operators in more realistic situations.
For example,
a[i] = c;
i = i + 1;
using the ++ operator, we could simply write this as
a[i++] = c;
will behave exactly the same way and produce exactly the same results. (In
real code, postfix increment is probably more common, though prefix definitely
has its uses, too.)
printf(“%d\n”, (c<d)?1:0);
}
Execute the above program and observe the result.
Where the same operator appears twice (for example *) the first one is the
unary version.
Program 2.6: A program to illustrate evaluation of expressions
#include<stdio.h>
main()
/* Evaluation of expressions */
{
float a, b, c, x, y, z;
a=20;
b=2;
c=-23;
x = a + b / ( 3 + c * 4 - 1);
y = a - b / (3 + c) * ( 4 - 1);
Manipal University Jaipur Page No.: 31
Programming in C Unit 1
z= a - ( b / ( 3 + c ) * 2 ) - 1;
printf( “x=%f\n”, x);
printf(“y=%f\n”, y);
printf(“z=%f\n”, z);
}
Execute the above program and observe the result.
Program 2.7: Program to convert seconds to minutes and seconds
#include <stdio.h>
#define SEC_PER_MIN 60 // seconds in a minute
int main(void)
{
int sec, min, left;
2.11 Summary
C supports a rich set of operators. An operator is a symbol that tells the
computer to perform certain mathematical or logical manipulations. Operators
are used in programs to manipulate data and variables. A binary operator acts
on two operands. A unary operator acts upon a single operand to produce a
new value. Multiplication, division, and modulus all have higher precedence
than addition and subtraction. Relational and Boolean expressions are usually
used in contexts such as an if statement, where something is to be done or not
done depending on some condition. The C language is accompanied by a
number of library functions or built in functions that carry out various commonly
used operations or calculations. The size of operator is normally used to
determine the lengths of arrays and structures when their sizes are not known
to the programmer. It is also used to allocate memory space dynamically to
variables during execution of a program. Associativity is the order in which
consecutive operations within the same precedence group are carried out.
2.12 Terminal questions
1. If i=10 and j=12, what are the values of c and d after executing the
following program segment:
i++;
c=j++ + i;
d=++i + j++;
2. Suppose that x, y and z are integer variables which have been assigned
the values 2, 3 and 4, respectively. Evaluate the following expression and
determine the value of x.
x *= -2 * (y + z) / 3
3. Suppose that i is an integer variable whose value is 7 and c is a character
variable that represents the character ‘w’, evaluate the following logical
expression:
(i>=6) && (c==’w’)
4. Suppose that i is an integer variable whose value is 7 and f is a floating -
point variable whose value is 8.5. Evaluate the following expression: (i +
f) %4
5. What is meant by associativity?
3. true
4. Given expression is invalid because a floating point variable can not be
used in a modulus operation.
5. Associativity is the order in which consecutive operations within the same
precedence group are carried out.
2.15 Exercises
1. Suppose a=3, b=5, c=8 and d=4, give the output of the following:
a) x=a*b-c/d+4 b) z=a-b/d*c+10
2. Suppose i=5, j=8, k=10, then , what is the output of the following:
a) x=a++ -j b) y=k++ *j—
3. What is the precedence of operators? How expressions are evaluated
using the precedences?
4. Suppose a=7, b=11, find the output of the following:
a) x=(a>b)?b:a b) x=(a<b)?a:b
5. Explain the use of bitwise operators with suitable examples.
3.1 Introduction
In the previous unit, you learned about the operators that a C programming
language supports. You also learned how the operators are used in the
expressions of C programs. In this unit, you will learn about the data types that
are supported in C. You will also study about the Input/output operators which
makes C as the most efficient and powerful programming language. Integer is
one of the fundamental data types. All C compilers support four fundamental
data types, namely integer (int), character (char), floating point (float), and
double-precision floating point (double). Like integer data type, other data
types also offer extended data types such as long double and signed char.
C supports a rich set of operators. We have already used several of them, such
as =, +, -, *, / and %. An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations. Operators are used in programs
to manipulate data and variables. They usually form a part of the mathematical
or logical expressions.
count = 0; VARIABLES*/
while (count<N) { scanf(“%f”, &number); sum = sum + number; count
= count + 1;
}
average = sum / N;
}
Output
input the values of a,b and c
2 4 -16
Root1 = 2.00
Root2 = -4.00
input the values of a,b and c
123
roots are imaginary
3.2.1 Converting Integers to Floating-point and vice-versa
C permits mixing of constants and variables of different types in an expression,
but during evaluation it adheres to very strict rules of type conversion. We know
that the computer considers one operator at a time, involving two operands.
If the operands are of different types, the ‘lower’ type is automatically converted
to the ‘higher’ type before the operation proceeds. The result is of higher type.
Given below is the sequence of rules that are applied while evaluating
expressions.
All short type are automatically converted to int ; then
1. If one of the operands is long double, the other will be converted to
long double and the result will be long double;
2. else, if one of the operands is double, the other will be converted to
double and the result will be double;
3. else, if one of the operands is float, the other will be converted to float and
the result will be float;
4. else, if one of the operands is unsigned long int, the other will be
converted to unsigned long int and the result will be unsigned long int;
5. else if one of the operands is long int and the other is unsigned int, then:
• if unsigned int can be converted to long int, the unsigned int operand
will be converted as such and the result will be long int;
• else, both operands will be converted to unsigned long int and the
result will be unsigned long int;
6. else, if one of the operands is long int , the other will be converted to long
int and the result will be long int;
7. else, if one of the operands is unsigned int , the other will be converted to
unsigned int and the result will be unsigned int;
The final result of an expression is converted to type of the variable on the left
of the assignment sign before assigning the value to it. However, the following
changes are introduced during the final assignment:
1. float to int causes truncation of the fractional part.
2. double to float causes rounding of digits.
3. long int to int causes dropping of the excess higher order bits
y = p + m;
y = p + (double)m;
However, the second statement is preferable. It will work the same way on all
machines and is more readable.
Self Assessment Questions
6. Casting can be used to round-off a given value. (True/False)
7. The value of A in the expression A=(int)11.35/(int)14.5 is __________
8. If the value of X is 35.2, then the value of A in the expression:
A = (int)(X+0.5); is _____________ .
Note that with the format characters %d, the ASCII number of the character is
displayed. With the format character %c, the character corresponding to the
given ASCII number is displayed.
Self Assessment Questions
9. What is the format character to display the value of a char variable?
10. The output of the following C statement: printf(“%c”, 70); is .
3.5 Keywords
Keywords are the reserved words of a programming language. All the
keywords have fixed meanings and these meanings cannot be changed.
Keywords serve as basic building blocks for program statements. The list of all
keywords in ANSI C are listed in the Table 3.3.
Table 3.3: ANSI C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
c=getchar();
The first statement declares that c is a character-type variable. The second
statement causes a single character to be entered from the keyboard and then
assign to c.
A companion function is putchar(), which writes one character to the “standard
output.'' (The standard output is usually the user's screen).
The syntax of the putchar() function is written as
putchar(character variable)
where character variable refers to some previously declared character
variable.
Example: char c;
putchar(c);
The first statement declares that c is a character-type variable. The second
statement causes the current value of c to be transmitted to the user monitor
where it will be displayed.
Using these two functions, we can write a very basic program to copy the input,
a character at a time, to the output:
Program 3.6: Program to copy the input, a character at a time, to the
output
#include <stdio.h>
/* copy input to output */ main()
{
int c;
c = getchar();
while(c != EOF)
{
running forever not waiting for something, you'll have to take more drastic
measures. Under Unix, control-C (or, occasionally, the DELETE key) will
terminate the current program, almost no matter what. Under MS-DOS,
control-C or control-BREAK will sometimes terminate the current program.
Self Assessment Questions
13. getchar() function is an output function.(True/False)
14. In order to stop reading the input character, you can use a value called
%c a single character
%d a decimal integer
%i an integer
%e, %f, %g a floating-point number
%o an octal number
%s a string
%x a hexadecimal number
%p a pointer
%n an integer equal to the number of characters read so far
%u an unsigned integer
%% a percent sign
scanf() reads the input, matching the characters from format. When a control
character is read, it puts the value in the next variable. Whitespaces (tabs,
spaces, etc) are skipped. Non-whitespace characters are matched to the input,
then discarded. If a number comes between the % sign and the control
character, then only that many characters will be entered into the variable. If
scanf() encounters a set of characters, denoted by the %[] control character,
then any characters found within the brackets are read into the variable. The
return value of scanf() is the number of variables that were successfully
assigned values, or EOF if there is an error.
char c;
char str[10];
scanf(“%d %f %c %s”, &i, &f, &c, str);
printf(“%d %f %c %s”, i, f, c, str);
}
Execute this program and observe the result.
Note that for a scanf() function, the addresses of the variable are used as the
arguments for an int, float and a char type variable. But this is not true for a
string variable because a string name itself refers to the address of a string
variable.
A s-control character is used to enter strings to string variables. A string that
includes whitespace characters can not be entered. There are ways to work
with strings that include whitespace characters. One way is to use the
getchar() function within a loop. Another way is to use gets() function which
will be discussed later.
It is also possible to use the scanf() function to enter such strings. To do so,
the s-control character must be replaced by a sequence of characters enclosed
in square brackets, designated as [...]. Whitespace characters may be included
within the brackets, thus accommodating strings that contain such characters.
Example:
#include<stdio.h> main() {
char str[80];
}
This example illustrates the use of the scanf() function to enter a string
consisting of uppercase letters and blank spaces. Please note that if you want
to allow lowercase letters to be entered, all the lowercase letters (i.e. from a-z)
must be included in the list of control string.
Formatted Output
Output data can be written from the computer onto a standard output device
using the library function printf(). This function can be used to output any
combination of numerical values, single characters and strings. It is similar to
the input function scanf(), except that its purpose is to display data rather than
Manipal University Jaipur Page No.: 48
Programming in C Unit 1
It is also possible to specify the width and precision of numbers and strings as
they are inserted ; For example, a notation like %3d means to print an int in a
field at least 3 spaces wide; a notation like %5.2f means to print a float or
double in a field at least 5 spaces wide, with two places to the right of the
decimal.)
To illustrate with a few more examples: the call
printf("%c %d %f %e %s %d%%\n", '3', 4, 3.24, 66000000, "nine", 8);
would print
3 4 3.240000 6.600000e+07 nine 8%
The call
printf("%d %o %x\n", 100, 100, 100);
would print
100 144 64
Successive calls to printf() just build up the output a piece at a time, so the
calls
printf("Hello, ");
printf("world!\n");
would also print Hello, world! (on one line of output).
Earlier we learned that C represents characters internally as small integers
corresponding to the characters' values in the machine's character set
(typically ASCII). This means that there isn't really much difference between a
character and an integer in C; most of the difference is in whether we choose
to interpret an integer as an integer or a character. printf is one place where
we get to make that choice: %d prints an integer value as a string of digits
representing its decimal value, while %c prints the character corresponding to
a character set value. So the lines
char c = 'A';
int i = 97;
printf("c = %c, i = %d\n", c, i);
would print c as the character A and i as the number 97. But if, on the other
hand, we called
printf("c = %d, i = %c\n", c, i);
we'd see the decimal value (printed by %d) of the character 'A', followed by the
character (whatever it is) which happens to have the decimal value 97.
You have to be careful when calling printf(). It has no way of knowing how
many arguments you've passed it or what their types are other than by looking
for the format specifiers in the format string. If there are more format specifiers
(that is, more % signs) than the arguments, or if the arguments have the wrong
types for the format specifiers, printf() can misbehave badly, often printing
nonsense numbers or (even worse) numbers which mislead you into thinking
that some other part of your program is broken.
#include<stdio.h>
main()
{
char line[80];
gets(line);
puts(line);
}
This program uses gets() and puts() functions rather than scanf() and printf(),
to transfer the line of text into and out of the computer.
3.10 Summary
Floating point(or real) numbers are stored in 32 bit (on all 16 bit and 32 bit
machines), with 6 digits of precision. Floating point numbers are defined in C
by the keyword float. When the accuracy provided by a float number is not
sufficient, the type double can be used to define the number. Characters are
usually stored in 8 bits (one byte) of internal storage. Like integer data type
other data types also offer extended data types such as long double and
signed char. C permits mixing of constants and variables of different types in
an expression, but during evaluation it adheres to very strict rules of type
conversion. When one of the operands is real and the other is integer, the
expression is called a mixed-mode arithmetic expression. There are instances
when we want to force a type conversion in a way that is different from the
automatic conversion. That is, by using type cast operator. All keywords have
fixed meanings and these meanings cannot be changed.
getchar(), putchar(), scanf(), printf(), gets() and puts() are the commonly
used input/output functions in C. These functions are used to transfer of
information between the computer and the standard input/output devices.
getchar() and putchar() are the two functions to read and write single
character. scanf() and printf() are the two formatted input/output functions.
These functions can handle characters, numerical values and strings as well.
gets() and puts() functions are used to handle strings. scanf(), printf(), gets()
and puts() functions are used in interactive programming.
7. 0
8. 35
9. %c
10. False
11. Lowercase
12. False
13. False
14. EOF
15. Control
16. %x
17. True
18. 64, 12, 4B
19. %o
20. a
21. False
22. String
23. False
3.14 Exercises
1. Represent the following numbers using scientific notation:
a) 0.001 b) -1.5
2. Represent the following scientific numbers into decimal notation: a)
1.0E+2 b) 0.001E-2
3. What is unsigned char? Explain.
4. What is short char? Explain.
5. Distinguish between float and double data types.
6. Write a program to print the factors of a given number.
7. Given the length of a side, write a C program to compute surface area
and volume of a cube.
8. Write a program to reverse a number and find sum of the digits.
9. Write a program to print the multiplication table for any given number.
10. Write a program to check whether a given number is palindrome.
4.1 Introduction
In the previous unit, you studied about the data types that are supported in C
and the types of Input/output operators available in C. This unit will enable you
to use the various types of control statements for making a decision in C.
Statements are the “steps'' of a program. Most statements compute and assign
values or call functions, but we will eventually meet several other kinds of
statements as well. By default, statements are executed in sequence, one after
another. We can, however, modify that sequence by using control flow
constructs such that a statement or group of statements is executed only if
some condition is true or false. This involves a kind of decision making to see
whether a particular condition has occurred or not and then direct the computer
to execute certain statements accordingly.
C language possesses such decision making capabilities and supports the
following statements known as the control or decision making statements.
• if statement
• switch statement
• goto statement
• conditional operator statement
You will also study about the loops in this unit. Loops generally consist of two
parts: one or more control expressions which control the execution of the loop,
and the body, which is the statement or set of statements which is executed
over and over.
As far as C is concerned, a true/false condition can be represented as an
integer. (An integer can represent many values; here we care about only two
values: “true'' and “false.'' The study of mathematics involving only two values
is called Boolean algebra, after George Boole, a mathematician who refined
this study.) In C, “false'' is represented by a value of 0 (zero), and “true'' is
represented by any value that is nonzero. Since there are many nonzero
values (at least 65,534, for values of type int), when we have to pick a specific
value for “true,'' we'll pick 1.
Do...while loop is used in a situation where we need to execute the body of the
loop before the test is performed. The for loop is used to execute the body of
the loop for a specified number of times. The break statement is used to exit
any loop.
Objectives:
After studying this unit, you should be able to:
• control the flow of execution of statements using two-way decision and
multipath decision.
• branch unconditionally from one point to another in the program.
• evaluate the conditional expressions.
• repeat the execution of statements by checking the condition before the
loop body is executed and by checking the condition at the end of the loop.
• exit from the loop depending on some condition.
• break the current iteration and continue with next iteration of loop.
4.2 The goto statement
C supports the goto statement to branch unconditionally from one point to
another in the program. Although it may not be essential to use the goto
statement in a highly structured language like C, there may be occasions when
the use of goto might be desirable.
The goto requires a label in order to identify the place where the branch is to
be made. A label is any valid variable name, and must be followed by a colon.
The label is placed immediately before the statement where the control is to
be transferred. The general forms of goto and label statements are shown
below:
The label can be anywhere in the program either before the goto or after the
goto label; statement.
During execution of the program when a statement like
goto first;
is met, the flow of control will jump to the statement immediately following the
label first. This happens unconditionally.
Note that a goto breaks the normal sequential execution of the program. If the
label is before the statement goto label; a loop will be formed and some
statements will be executed repeatedly. Such a jump is known as a backward
jump. On the other hand, if the label is placed after the goto label; some
statements will be skipped and the jump is known as the forward jump.
A goto is often used at the end of a program to direct the control to go to the
input statement, to read further data. Consider the following example:
Program 4.1: Program showing unconditional branching
main()
{
double a, b;
read:
printf(“enter the value of a\n”);
Manipal University Jaipur Page No.: 59
Programming in C Unit 1
scanf(“%f”, &a);
if (a<0) goto read;
b=sqrt(a);
printf(“%f %f \n”,a, b);
goto read;
}
This program is written to evaluate the square root of a series of numbers read
from the terminal. The program uses two goto statements, one at the end,
after printing the results to transfer the control back to the input statements and
the other to skip any further computation when the number is negative.
Due to the unconditional goto statement at the end, the control is always
transferred back to the input statement. In fact, this program puts the computer
in a permanent loop known as an infinite loop.
Self Assessment Questions
1. The goto requires a ________ in order to identify the place where the
branch is to be made.
2. goto is an unconditional branching statement. (True/False)
if( expression )
{
statement 1;
statement 2;
statement n;
}
As a general rule, anywhere the syntax of C calls for a statement, you may
write a series of statements enclosed by braces. (You do not need to, and
should not, put a semicolon after the closing brace, because the series of
statements enclosed by braces is not itself a simple expression statement.)
When you have one if statement (or loop) nested inside another, it's a very
good idea to use explicit braces {}, as shown, to make it clear (both to you and
to the compiler) how they're nested and which else goes with which if. It's also
a good idea to indent the various levels, also as shown, to make the code more
readable to humans. Why do both? You use indentation to make the code
visually more readable to yourself and other humans, but the compiler doesn't
pay attention to the indentation (since all whitespace is essentially equivalent
and is essentially ignored). Therefore, you also have to make sure that the
punctuation is right.
The condition of a switch statement is a value. The case says that if it has the
value of whatever is after that case then do whatever follows the colon. The
break is used to break out of the case statements. break is a keyword that
breaks out of the code block, usually surrounded by braces, which it is in. In
this case, break prevents the program from falling through and executing the
code in all the other case statements. An important thing to note about the
switch statement is that the case values may only be constant integral
expressions. It isn't legal to use case like this: int a = 10; int b = 10; int c = 20;
switch ( a ) { case b:
/* Code */
break;
case c:
/* Code */
break;
default:
/* Code */ break;
}
The default case is optional, but it is wise to include it as it handles any
unexpected cases. It can be useful to put some kind of output to alert you to
the code entering the default case if you don't expect it to. Switch statements
serve as a simple way to write long if statements when the requirements are
met. Often it can be used to process input from a user.
Example: Below is a sample program, in which not all of the proper functions
are actually declared, but which shows how one would use switch in a program.
#include <stdio.h>
void playgame(); void loadgame(); void playmultiplayer(); int main()
{
int input;
printf( "1. Play game\n" );
printf( "2. Load game\n" );
printf( "3. Play multiplayer\n" );
printf( "4. Exit\n" );
printf( "Selection: " );
scanf( "%d", &input );
switch ( input ) {
executing the body of the loop, the condition is tested. Therefore it is called an
entry-controlled loop. The following example repeatedly doubles the number
2 (2, 4, 8, 16, ...) and prints the resulting numbers as long as they are less than
1000:
int x = 2;
You use a while loop when you have a statement or group of statements which
may have to be executed a number of times to complete their task. The
controlling expression represents the condition “the loop is not done'' or
“there's more work to do.'' As long as the expression is true, the body of the
loop is executed; presumably, it makes at least some progress at its task.
When the expression becomes false, the task is done, and the rest of the
program (beyond the loop) can proceed. When we think about a loop in this
way, we can see an additional important property: if the expression evaluates
Manipal University Jaipur Page No.: 68
Programming in C Unit 1
to “false'' before the very first trip through the loop, we make zero trips through
the loop. In other words, if the task is already done (if there's no work to do)
the body of the loop is not executed at all. (It's always a good idea to think
about the “boundary conditions'' in a piece of code, and to make sure that the
code will work correctly when there is no work to do, or when there is a trivial
task to do, such as sorting an array of one number. Experience has shown that
bugs at boundary conditions are quite common.)
Program 4.5: Program to find largest of n numbers main() { int num, large,
n, i;
clrscr();
printf("enter number of numbers \n");
scanf(“%d”,&n);
large=0;
i=0;
while(i<n)
{
printf("\n enter number ");
scanf(“%d”, &num);
if(large<num)
large=num;
i++;
} printf("\n large = %d”, large);
}
scanf(“%f”, &acc);
sum=x;
term=x;
while ((fabs(term))>acc)
{
term=-term*x*x/((2*i)*(2*i+1));
sum+=term;
i++;
} printf"\nsum of sine series is %f", sum); }
Self Assessment Questions
8. A ____________ loop starts out like an if statement .
9. while is an entry-controlled loop. (True/False)
2 4 6 8 ........... .................. 20
3 6 9 12 ............ .................. 30
4 .................. 40
10 100
// Program to print multiplication table main() {
int rowmax=10,colmax=10,row,col,x;
printf(" Multiplication table\n");
printf(" ................................... \n");
row=1;
do
{
col=1;
do
{
x=row*col;
printf(“%4d”, x);
col=col+1;
}
while (col<=colmax);
printf(“\n”);;
row=row+1;
}
while(row<=rowmax);
Printf(" .........................................................................................................\
n");
}
It's also worth noting that a for loop can be used in more general ways than the
simple, iterative examples we've seen so far. The “control variable'' of a for
loop does not have to be an integer, and it does not have to be incremented
by an additive increment. It could be “incremented'' by a multiplicative factor
(1, 2, 4, 8, ...) if that was what you needed, or it could be a floating-point
variable, or it could be another type of variable which we haven't met yet which
would step, not over numeric values, but over the elements of an array or other
data structure. Strictly speaking, a for loop doesn't have to have a “control
variable'' at all; the three expressions can be anything, although the loop will
make the most sense if they are related and together form the expected
initialize, test, increment sequence.
The powers-of-two example using for is:
int x;
for(x = 2; x < 1000; x = x * 2) printf("%d\n", x);
There is no earth-shaking or fundamental difference between the while and
for loops. In fact, given the general for loop
for(expr1; expr2; expr3)
statement
you could usually rewrite it as a while loop, moving the initialize and increment
expressions to statements before and within the loop:
expr1;
while(expr2)
{
statement
expr3;
}
Similarly, given the general while loop while(expr) statement
you could rewrite it as a for loop:
for(; expr; )
statement
Another contrast between the for and while loops is that although the test
expression (expr2) is optional in a for loop, it is required in a while loop. If you
leave out the controlling expression of a while loop, the compiler will complain
about a syntax error. (To write a deliberately infinite while loop, you have to
supply an expression which is always nonzero. The most obvious one would
simply be while(1) .)
If it's possible to rewrite a for loop as a while loop and vice versa, why do they
both exist? Which one should you choose? In general, when you choose a for
loop, its three expressions should all manipulate the same variable or data
structure, using the initialize, test, increment pattern. If they don't manipulate
the same variable or don't follow that pattern, wedging them into a for loop
buys nothing and a while loop would probably be clearer. (The reason that one
loop or the other can be clearer is simply that, when you see a for loop, you
expect to see an idiomatic initialize/ test/increment of a single variable, and if
the for loop you're looking at doesn't end up matching that pattern, you've been
momentarily misled.)
Program 4.8: A Program to find the factorial of a number
void main()
{
int M,N;
long int F=1;
clrscr();
printf(“enter the number\n”)";
scanf(“%d”,&N);
if(N<=0)
F=1;
else
{
for(M=1;M<=N;M++)
F*=M;
}
printf(“the factorial of the number is %ld”,F); getch();
}
for(i=1;i<10;i++)
{
for(j=1;j<5;j++)
{
4.9 The break statement and continue statement
The purpose of break statement is to break out of a loop (while, do while, or
for loop) or a switch statement. When a break statement is encountered
inside a loop, the loop is immediately exited and the program continues with
the statement immediately following the loop. When the loops are nested, the
break would only exit from the loop containing it. That is, the break would exit
only a single loop.
Syntax : break;
The above program displays the numbers from 1to 4 and prints the message
“Broke out of loop when 5 is encountered.
Syntax: continue;
Program 4.10: Program to illustrate the use of continue statement.
void main ( ) {
int x;
for (x=1; x<=10; x++)
{ if (x==5)
continue; /* skip remaining code in loop only if x == 5 */
printf (“%d\n”, x);
} printf(“\nUsed continue to skip”);
}
The above program displays the numbers from 1to 10, except the number 5.
4. Write the output that will be generated by the following C program: void
main()
{
if (i%5 == 0)
{
x+=i;
printf(“%d\t”, i);
}
i++;
}
printf(“\nx=%d”; x);
5. Write the output that will be generated by the following C program: void
main()
if (i%5 == 0)
{
x++;
printf(“%d\t”, x);
}
++i;
} while (i<20);
printf(“\nx=%d”, x);
printf(“enter a number\n”);
scanf(“%d”,&no);
if (no%2==0)
printf(“even number\n”);
else printf(“odd number\n”);
}
4. 0 5 10 15
x = 30
5. 1 2 3 4
x=4
4.14 Exercises
1. Explain different types of if statements with examples.
2. Explain the syntax of switch statement with an example.
3. Write a program to check whether a given number is odd or even using
switch statement.
4. Write a program to find the smallest of 3 numbers using if-else statement.
5. Write a program to find the roots of a quadratic equation.
6. Compare the following statements
a) while and do...while
b) break and continue
7. Write a program to compute the sum of digits of a given number using
while loop.
8. Write a program that will read a positive integer and determine and print
its binary equivalent using do...while loop.
9. The numbers in the sequence
1 1 2 3 5 8 13 ............
are called Fibonacci numbers. Write a program using do.while loop to
calculate and print the first n Fibonacci numbers.
10. Find errors, if any, in each of the following segments. Assume that all the
variables have been declared and assigned values.
(a)
while (count !=10);
{
count = 1;
sum = sum + x;
count = count + 1;
}
(b)
do;
total = total + value;
scanf(“%f”, &value);
while (value ! =999);
11. Write programs to print the following outputs using for loops.
(a) 1 b) 1
22 2 2
333 3 3 3
4444 4 4 4 4
12. Write a program to read the age of 100 persons and count the number of
persons in the age group 50 to 60. Use for and continue statements.
13. Write a program to print the multiplication table using nested for loops.
Unit 5 Functions
Structure:
5.1 Introduction
Objectives
5.2 Function Basics
5.3 Function Prototypes
5.4 Recursion
5.5 Function Philosophy
5.6 Summary
5.7 Terminal Questions
5.8 Answers for Self Assessment Questions
5.9 Answers for Terminal Questions
5.10 Exercises
5.1 Introduction
In the previous unit, you studied about the control statements and its usage in
C. You also studied how those control statements are helpful in making
decisions when various types of conditions and options are available in the
problem. In this unit, you will study about what a function is.
A function is a “black box'' that we've locked part of our program into. The idea
behind a function is that it compartmentalizes part of the program, and in
particular, that the code within the function has some useful properties:
It performs some well-defined task, which will be useful to other parts of the
program. It might be useful to other programs as well; that is, we might be able
to reuse it (and without having to rewrite it).
The rest of the program doesn't have to know the details of how the function is
implemented. This can make the rest of the program easier to think about.
The function performs its task well. It may be written to do a little more than is
required by the first program that calls it, with the anticipation that the calling
program (or some other program) may later need the extra functionality or
improved performance. (It's important that a finished function do its job well,
otherwise there might be a reluctance to call it, and it therefore might not
achieve the goal of reusability.)
By placing the code to perform the useful task into a function, and simply calling
the function in the other parts of the program where the task must be
performed, the rest of the program becomes clearer: rather than having some
large, complicated, difficult-to-understand piece of code repeated wherever the
task is being performed, we have a single simple function call, and the name
of the function reminds us which task is being performed.
Since the rest of the program doesn't have to know the details of how the
function is implemented, the rest of the program doesn't care if the function is
re-implemented later, in some different way (as long as it continues to perform
its same task, of course!). This means that one part of the program can be
rewritten, to improve performance or add a new feature (or simply to fix a bug),
without having to rewrite the rest of the program.
Functions are probably the most important weapon in our battle against
software complexity. You'll want to learn when it's appropriate to break
processing out into functions (and also when it's not), and how to set up
function interfaces to best achieve the qualities mentioned above: reusability,
information hiding, clarity, and maintainability.
Objectives:
After studying this unit, you should be able to:
• explain the importance of functions
• implement the concepts of formal arguments and actual arguments
• explain function declaration(function prototypes) and function definition
• use the concept of recursion
• explain how the concept of functions reduces software complexity
(statements) for carrying out the task the function is supposed to perform; and
it may give you back a return value, of a particular type.
In general terms, the first line can be written as
data-type name(data-type parameter 1, data-type parameter 2, ..., data-type
parameter n)
Example 5.1: Here is a very simple function, which accepts one argument,
multiplies it by 4, and hands that value back.
int multbyfour(int x)
{
int retval;
retval = x * 4;
return retval;
}
On the first line we see the return type of the function (int), the name of the
function (multbyfour), and a list of the function's arguments, enclosed in
parentheses. Each argument has both a name and a type; multbyfour accepts
one argument, of type int, named x. The name x is arbitrary, and is used only
within the definition of multbyfour. The caller of this function only needs to
know that a single argument of type int is expected; the caller does not need
to know what name the function will use internally to refer to that argument. (In
particular, the caller does not have to pass the value of a variable named x.)
Next we see, surrounded by the familiar braces, the body of the function itself.
This function consists of one declaration (of a local variable retval) and two
statements. The first statement is a conventional expression statement, which
computes and assigns a value to retval, and the second statement is a return
statement, which causes the function to return to its caller, and also specifies
the value which the function returns to its caller.
In general term, a return statement is written as
return expression
The return statement can return the value of any expression, so we don't really
need the local retval variable; this function can also be written as
int multbyfour(int x)
{
return x * 4;
}
How do we call a function? We've been doing so informally since day one, but
now we have a chance to call one that we've written, in full detail. The
arguments in the function call are referred to as actual arguments or actual
parameters, in contrast to the formal arguments that appear in the first line of
the function definition.
Here is a tiny skeletal program to call multbyfour:
#include <stdio.h>
extern int multbyfour(int);
int main()
{
int i, j;
i = 5;
j = multbyfour(i);
printf("%d\n", j);
return 0;
}
This looks much like our other test programs, with the exception of the new line
extern int multbyfour(int);
This is an external function prototype declaration. It is an external declaration,
in that it declares something which is defined somewhere else. (We've already
seen the defining instance of the function multbyfour, but may be the compiler
hasn't seen it yet.) The function prototype declaration contains the three pieces
of information about the function that a caller needs to know: the function's
name, return type, and argument type(s). Since we don't care what name the
multbyfour function will use to refer to its first argument, we don't need to
mention it. (On the other hand, if a function takes several arguments, giving
them names in the prototype may make it easier to remember which is which,
so names may optionally be used in function prototype declarations.) Finally,
to remind us that this is an external declaration and not a defining instance, the
prototype is preceded by the keyword extern.
The presence of the function prototype declaration lets the compiler know that
Manipal University Jaipur Page No.: 85
Programming in C Unit 1
}
int max(int a, int b)
{
int c;
c=(a>=b)?a:b;
return c;
}
Please execute this program and observe the result.
Function calls can span several levels within a program; function A can call
function B, which can call function C and so on.
Program 5.2: Program to check whether a given integer is a perfect
square or not.
#include<stdio.h>
main()
{
int psquare(int);
int num;
printf(“ Enter the number:”);
scanf(“%d”, &num);
if(psquare(num)) /* main() calls the function psquare() */
{ printf(“%d is a perfect square\n”);
else
printf(“%d is not a perfect square\n”);
}
}
int psquare(int x)
{
int positive(int);
float sqr;
if(positive(x)) /* psquare() in turn calls the function positive() */ { sqr=sqrt(x));
if(sqr-int(sqr))==0)
return 1;
else
return 0;
}
int positive(int m) {
if(m>0)
return 1;
else return 0;
}
Execute the above program and observe the result.
In the above program the main function calls the function psquare() and it in
turn calls the function positive() to check whether the number to be checked
for perfect square is a positive or not before checking.
The return statement can be absent altogether from a function definition,
though this is generally regarded as a poor programming practice. If a
function reaches end of the block without encountering a return statement,
control simply reverts back to the calling portion of the program without
returning any information. Using an empty return statement(without the
accompanying expressions) is recommended.
Example 5.2: The following function accepts two integers and determines
the larger one, which is then written out. The function doesn’t return any
information to the calling program.
void max(int x, int y)
{
int m;
m=(x>=y)?x:y;
printf(“ The larger integer is=%d\n”, m); return;
}
Self Assessment Questions
1. The function main() is optional in a C program. (True/False)
2. If the function is defined elsewhere (not in the same program where it is
called), the function prototype must be preceded by the keyword
other standard library functions we call, there will be other “header files'' to
include.) Finally, one more thing about external function prototype declarations:
we've said that the distinction between external declarations and defining
instances of normal variables hinges on the presence or absence of the
keyword extern. The situation is a little bit different for functions. The “defining
instance'' of a function is the function, including its body (that is, the brace-
enclosed list of declarations and statements implementing the function). An
external declaration of a function, even without the keyword extern, looks
nothing like a function declaration. Therefore, the keyword extern is optional
in function prototype declarations. If you wish, you can write
int multbyfour(int);
and this is just like an external function prototype declaration as
extern int multbyfour(int);
(In the first form, without the extern, as soon as the compiler sees the
semicolon, it knows it's not going to see a function body, so the declaration
can't be a definition.) You may want to stay in the habit of using extern in all
external declarations, including function declarations, since “extern = external
declaration'' is an easier rule to remember.
Program 5.3: Program to illustrate that the function prototype is optional
in the caller function. The program is to convert a character from
lowercase to uppercase.
#include<stdio.h>
char lower_to_upper(char ch) /* Function definition precedes main()*/
{
char c;
c=(ch>=’a’ && ch<=’z’) ? (‘A’+ch-‘a’):ch;
return c;
}
main()
{
char lower, upper;
/* char lower_to_upper(char lower); */ /* Function prototype is
optional here*/
printf(“Please enter a lowercase character:”);
scanf(“%c”, &lower);
upper=lower_to_upper(lower);
printf(“\nThe uppercase equivalent of %c is %c\n”, lower, upper);
}
z=fun(x, y);
5.4 Recursion
Recursion is a process by which a function calls itself repeatedly, until some
specified condition has been met. The process is used for repetitive
computations in which each action is stated in terms of a previous result. Many
repetitive problems can be written in this form.
In order to solve a problem recursively, two conditions must be satisfied. First,
the problem must be written in a recursive form, and the second, the problem
statement must include a stopping condition.
Example 5.3: Factorial of a number. Suppose we wish to calculate the
factorial of a positive integer, n. We would normally express this problem as
n!=1 x 2 x 3 x ... x n.
This can also be written as n!=n x (n-1)!. This is the recursive statement of the
problem in which the desired action(the calculation of n!) is expressed in terms
of a previous result (the value of (n-1)! which is assumed to be known). Also,
we know that 0!=1 by definition. This expression provides stopping condition
for the recursion.
Thus the recursive definition for finding factorial of positive integer n can be
written as:
fact(n)={ 1 if n=0
n x fact(n-1) otherwise}
Program 5.4: Program to find factorial of a given positive integer
#include<stdio.h> main() {
int n;
long int fact(int);
/* Read in the integer quantity*/ scanf(“%d”, &n);
/*calaculate and display the factorial*/ printf(“n!=%ld\n”, fact(n));
}
long int fact(int n)
{
if(n==0)
return(1);
else
return (n*fact(n-1));
}
Please execute this program and observe the result.
Example 5.4: The Towers of Hanoi. The Towers of Hanoi is a game played
with three poles and a number of different sized disks. Each disk has a hole in
the center, allowing it to be stacked around any of the poles. Initially, the disks
are stacked on the leftmost pole in the order of decreasing size, i.e, the largest
on the bottom, and the smallest on the top as illustrated in Figure 5.1.
#include<stdio.h>
main()
Manipal University Jaipur Page No.: 95
Programming in C Unit 1
{
int n=5;
int fun(int n);
printf(“%d\n”, fun(n));
}
int fun(int n)
{
if(n==0)
return 0;
else
return (n+fun(n-1));
}
5.5 Function Philosophy
What makes a good function? The most important aspect of a good “building
block'' is that have a single, well-defined task to perform. When you find that a
program is hard to manage, it's often because it has not been designed and
broken up into functions cleanly. Two obvious reasons for moving code down
into a function are because:
1. It appeared in the main program several times, such that by making it a
function, it can be written just once, and the several places where it used
to appear can be replaced with calls to the new function.
2. The main program was getting too big, so it could be made (presumably)
smaller and more manageable by lopping part of it off and making it a
function.
These two reasons are important, and they represent significant benefits
of well-chosen functions, but they are not sufficient to automatically identify
a good function. As we've been suggesting, a good function has at least
these two additional attributes:
3. It does just one well-defined task, and does it well.
4. Its interface to the rest of the program is clean and narrow.
Attribute 3 is just a restatement of two things we said above. Attribute 4 says
that you shouldn't have to keep track of too many things when calling a
function. If you know what a function is supposed to do, and if its task is simple
and well-defined, there should be just a few pieces of information you have to
give it to act upon, and one or just a few pieces of information which it returns
to you when it's done. If you find yourself having to pass lots and lots of
information to a function, or remember details of its internal implementation to
make sure that it will work properly this time, it's often a sign that the function
is not sufficiently well-defined. (A poorly-defined function may be an arbitrary
chunk of code that was ripped out of a main program that was getting too big,
such that it essentially has to have access to all of that main function's local
variables.)
The whole point of breaking a program up into functions is so that you don't
have to think about the entire program at once; ideally, you can think about just
one function at a time. We say that a good function is a “black box,'' which is
supposed to suggest that the “container" it's in is opaque - callers can't see
inside it (and the function inside can't see out). When you call a function, you
only have to know what it does, not how it does it. When you're writing a
function, you only have to know what it's supposed to do, and you don't have
to know why or under what circumstances its caller will be calling it. (When
designing a function, we should perhaps think about the callers just enough to
ensure that the function we're designing will be easy to call, and that we aren't
accidentally setting things up so that callers will have to think about any internal
details.)
Some functions may be hard to write (if they have a hard job to do, or if it's
hard to make them do it truly well), but that difficulty should be
compartmentalized along with the function itself. Once you've written a “hard''
function, you should be able to sit back and relax and watch it do that hard
work on call from the rest of your program. It should be pleasant to notice (in
the ideal case) how much easier the rest of the program is to write, now that
the hard work can be deferred to this workhorse function.
(In fact, if a difficult-to-write function's interface is well-defined, you may be able
to get away with writing a quick-and-dirty version of the function first, so that
you can begin testing the rest of the program, and then go back later and
rewrite the function to do the hard parts. As long as the function's original
interface anticipated the hard parts, you won't have to rewrite the rest of the
program when you fix the function.)
The functions are important for far more important reasons than just saving
typing. Sometimes, we'll write a function which we only call once, just because