Computer Programming PDF
Computer Programming PDF
C PROGRAMMING
Revision 4
July 2013
L. V. NARASIMHA PRASAD
Professor and Head
E. KRISHNARAO PATRO
Associate Professor
You type in your program as C source code, compile it (or try to run it from your
programming editor, which will typically compile and build automatically) to turn it into
object code, and then build the program using a linker program to create an executable
program that contains instructions written in machine code, which can be understood
and run on the computer that you are working on.
S o u rc e C o d e O b j ect C o d e M a c hin e C o d e
C o m pile b uild ( E x e c ut a ble )
( C Pro gra m ) (in b e t we e n )
Fi g 1. 0. C o m pilat ion P r oc es s
Study material 1
To compile a C program that you have typed in using C/C++ Editor, do one of the
following:
When creating your programs, here are a few guidelines for getting a program that can
be easily read and debugged by you (when you come back to it later) and others (who
may have to change your program later).
• A well-structured program should indent (i.e. move to the right by pressing
the tab key once) all instructions inside each block (i.e. following an opening
curly brace – { ). Therefore, a block inside another block will be indented
twice etc. This helps to show which instructions will be executed, and also
helps to line up opening and closing curly braces.
• Another useful technique that helps the readability inside each instruction is to
put spaces after commas when listing parameters (i.e. data) to be given to a
function. This helps identify where each parameter starts and makes the
program easier to read. Spaces before and after brackets, assignments (=)
and operators (+ - * / < > == != etc.) can also help make things more
readable – but this is up to you.
• If you create a new function, put a comment before it showing what data goes
in, and what comes out, and the purpose of the function.
• If a part of your code is quite difficult to follow, or you wish to explain why
you have written it the way you have, or even if you wish to say that it could
be improved (and how) but you haven't the time to do it better yet, then use
a comment.
1.3. FLOWCHARTING:
Note: In the examples below, assume that variables A and I are integers
Terminal Activity -
Start, Stop or End START
{
Study material 2
Assignment of a value ADD 1 to I
to a variable, either or
directly or as the result I =I +1
of a calculation.
I = I + 1;
Softcopy - screen
output to a video
display. The answer is: A
Hardcopy - document
output from a printer. The answer is: A
Decision based on a
condition. F
A <0
T
if (A < 0)
{
statements;
}
else
{
statements;
}
To repeat a statement/s
a known number of I =0
I <5
times. I++
Connectors:
On-page (left) & L R
Off-page (right).
Used to either:
1. Continue a flowchart
at a different place
either on or off the
same piece of paper.
2. Close a selection
branch or loop.
Study material 3
Flow of Control Arrows
indicating the sequence
of steps ("flow of
control").
A = 0;
/* Reset A */
General Input/Output of
Data Write the next
value to disk
fprintf (filename, data);
printf(“Message”);
scanf(“%d”, &I);
Symbols can be of any size (height or width) necessary to hold the symbol's contents.
The shapes of most symbols imply the process. It is redundant to put the word "print" in
a hardcopy symbol for example.
Always put an arrowhead on each line connecting symbols to indicate the "flow of
control". The only symbols that may receive more than one incoming arrow are
connectors. Never enter any other symbols using more than one arrow. If you want to
do that, put a connector in front of the symbol and let the multiple arrows enter the
connector.
The switch statement involves a special use of the diamond symbol. A flowchart for the
following switch statement is shown to its right. Notice that the diamond contains only
the name of the single variable to be evaluated. The "legs" that exit the decision
diamond are each labeled with the unique values from a limited set of possible values for
the variable answer, including the "else" (default) option.
switch (ANS)
{
case 'Y':
case 'y':
X = 1;
break;
case 'N':
case 'n':
X =-1;
break;
default:
X = 0;
}
Study material 4
1.4. Algorithm
Algorithm is a finite sequence of instructions, each of which has a clear meaning and can
be performed with a finite amount of effort in a finite length of time. No matter what the
input values may be, an algorithm terminates after executing a finite number of
instructions.
Most of the commands can be activated directly without going through the main menu.
These operations are activated by using hot keys and can be used whenever needed.
Study material 5
C Help about the item upon which the cursor
Ctrl F1
is present
Ctrl F2 Reset program
Ctrl F3 Show function call stack
Ctrl F4 Evaluate an expression
Ctrl F7 Set a watch expression
Ctrl F8 Set or clear a break point
Ctrl F9 Execute program
Study material 6
2. Then type: CTRL - KW
It asks for file name to move the block
3. To Read a block in: CTRL – KR
You are prompted for the file name and the contents come to the current
cursor location.
1.7. Characteristics of C:
We briefly list some of C's characteristics that define the language and also have lead to
its popularity as a programming language. Naturally we will be studying many of these
aspects throughout the course.
• Small size
• Extensive use of function calls
• Loose typing
• Structured language
• Low level (Bitwise) programming readily available
• Pointer implementation - extensive use of pointers for memory, array, structures
and functions.
C has now become a widely used professional language for various reasons.
Its main drawback is that it has poor error detection, which can make it off putting to
the beginner. However diligence in this matter can pay off handsomely since having
learned the rules of C we can break them. Not many languages allow this. This if done
properly and carefully leads to the power of C programming.
Study material 7
1.8. Compiling & Executing C Program:
E d it or
So urc e C o d e Pr e pr oc e s s or He a d e r F i l e s
C o mp i l e r
A s s e mb l e r
O b j ec t C o d e
O b j ec t F i l e s L i n k er L i br ar i e s
E x ec ut a b l e f i l e s
St a g e s of C o mp i l a t i o n a n d E x ec ut i o n
2. C compiler: This program translates the C language source code into the
machine assembly language.
3. Assembler: The assembler accepts the C – compiler output and creates object
code. If the program does not contain any external function calls, this code is
directly executable.
Study material 8
1.9. Keywords in C:
Total keywords: 32
In C, comments begin with the sequence /* and are terminated by */. Any thing that is
between the beginning and ending comments symbols is ignored by the compiler.
Example:
/* sample program */
In C, blank lines are permitted and have no effect on the program. A non-trivial C
application typically has following general portions on it:
So urc e c o d e:
He a d e r F i l e s:
# i nc l u d e s
M a n if e st c o n st a nt s:
# d ef i n e s
U s e r s u p p l i e d f u nc t i o n pr ot ot y p e s
Gl o b a l v ar i a b l e d ef i n it i o n s
i nt ma i n (v o i d)
{
L oc a l v ar i a b l e d ef i n it i o n s
-- b o dy of t h e pr o gr a m --
}
U s e r w r it t e n f u nc t i o n s
Study material 9
Header Files (.h):
Header files contains declaration information for function or constants that are
referred in programs. They are used to keep source-file size to a minimum and to reduce
the amount of redundant information that must be coded.
# includes:
An include directive tells the preprocessor to include the contents of the specified file at
the point in the program. Path names must either be enclosed by double quotes or angle
brackets.
Example:
1: # include <stdio.h>
2: # include “mylib.h”
3: # include “mine\include\mylib.h”
In the example (1) above, the <> tells the preprocessor to search for the included file in
a special known \include directory or directories.
In the example (2), the double quotes (“ ”) indicate that the current directory should be
checked for the header file first. If it is not found, the special directory (or directories)
should be checked.
The example (3) is similar, but the named relative directory \mine\include is checked for
the header file mylib.h.
Relative paths can also be proceeded by the .\ or ..\ notation; absolute paths always
begin with a \.
# defines:
ANSI C allows you to declare constants. The # define directive is used to tell the
preprocessor to perform a search-and-replace operation.
Example:
# define Pi 3.14159
# define Tax-rate 0.0735
In the example above, the preprocessor will search through the source file and replace
every instance of the token Pi with 3.14159
After performing the search and replace operation, the preprocessor removes the
# define line.
Declares the user-written functions actually defined later in the source file. A function
prototype is a statement (rather than an entire function declaration) that is placed a
head of a calling function in the source code to define the function's label before it is
used. A function prototype is simply a reproduction of a function header (the first line of
a function declaration) that is terminated with a semi-colon.
Study material 10
Global variable definitions:
main () The main function is the entry point in the C program. All C programs
begin execution by calling the main () function. When the main function
returns, your program terminates execution and control passes back to
the operating system.
Every C/C++ program must have one and only one main function.
{ The next line consists of a single curly brace which signifies the start of
main () function.
int age ; The first line of code inside function main () is declaration of variables. In
C all variables must be declared before they are used.
User-written functions:
Divide the application into logical procedural units and factor out commonly used code to
eliminate repetition.
Study material 11
The syntax of the simple type specifier:
Short Int
Const Signed
Long
UnSigned
Char
Float
Double
Long
Currently the three char data types are guaranteed to be 1 byte in length, but the other
data types are machine architecture dependent. Unsigned can be used with all char and
int types.
The C language defines the names that are used to reference variables, functions, labels,
and various other user-defined objects as identifiers.
An identifier can vary from one to several characters. The first character must be a letter
or an underscore with subsequent characters being letters, numbers or under-score.
Example:
Correct: Count, test23, High_balances, _name
In-correct: 1 count, hil there, high..balance
In turbo C, the first 32 characters of an identifier name are significant. If two variables
have first 32 characters in common and differ only on the 33rd, TC will not be able to tell
then apart. In C++ identifiers may be any length.
In C, upper and lower case characters are treated as different and distinct.
Example:
count, Count, COUNT are three separate identifiers.
Example:
int i, j, k;
float x, y, z;
char ch;
Study material 12
Uppe r c a s e
l et t er s
Uppe r c a s e
L o w er c a s e l et t er s
l et t er s
L o w er c a s e
U n d e r sc or e ( _ ) l et t er s
Di g i t
U n d e r sc or e ( _ )
Variables are declared in three basic places: inside functions, in the definition of function
parameters and outside of the functions. If they are declared inside functions, they are
called as local variables, if in the definition of functions then formal parameters and out
side of all functions, then global variables.
Global variables are known throughout the program. The variables hold their values
throughout the programs execution. Global variables are created by declaring them
outside of any function.
main()
{
It is also possible to pre-initialise global variables using the = operator for assignment.
Example:
float sum;
int bigsum;
char letter;
main()
{
Study material 13
sum = 0.0;
bigsum = 0;
letter =`A';
}
is more efficient.
a = b = c = d = 3;
a = 3;
b = 3;
c = 3;
d = 3;
This kind of assignment is only possible if all the variable types in the statement are the
same.
Variable that are declared inside a function are called “local variables”. These variables
are referred to as “automatic variables”. Local variables may be referenced only by
statements that are inside the block in which the variables are declared.
Local variables exist only while the block of code in which they are declared is executing,
i.e. a local variable is created upon entry into its block & destroyed upon exit.
Example:
The integer variable x is declared twice, once in func1 () & once in func2 (). The x in
func1 () has no bearing on or relationship to the x in func2 (). This is because each x is
only known to the code with in the same block as variable declaration.
Study material 14
In the example above, the preprocessor will search through the source file and replace
every instance of the token Pi with 3.14159
After performing the search and replace operation, the preprocessor removes the
# define line.
The following are two purposes for defining and using manifest constants:
1.15. Constants:
ANSI C allows you to declare constants. When you declare a constant it is a bit like a
variable declaration except the value cannot be changed.
Example:
int const a = 1;
const int a =2;
You can declare the const before or after the type. Choose one and stick to it. It is usual
to initialise a const with a value as it cannot get a value any other way.
The difference between a const variable and a manifest constant is that the # define
causes the preprocessor to do a search-and—replace operation through out code. This
sprinkles the literal through your code wherever it is used. On the other hand, a const
variable allows the compiler to optimize its use. This makes your code run faster
(compiler optimization is outside the scope of this course).
Code Meaning
\n New line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\b Backspace
\’ Single quote
\” Double quote
\\ Back slash
\a Alert (bell)
\f Form feed
Study material 15
1.17. Operators:
There are three general classes of operators: arithmetic, relational and logical and
bitwise.
Increment ++, Decrement -- which are more efficient than their long hand equivalents.
X = 10;
Y = ++X;
In this case, Y will be set to 11 because X is first incremented and then assigned to Y.
However if the code had been written as
X = 10;
Y = X++;
Y would have been set to 10 and then X incremented. In both the cases, X is set to 11;
the difference is when it happens.
RULE: If both arguments of / are integer then do integer division. So make sure you do
this. The correct (for division) answer to the above is x = 3.0 / 2 or x= 3 / 2.0 or
(better) x = 3.0 / 2.0.
Study material 16
There is also a convenient shorthand way to express computations in C.
We can rewrite i = i + 3 as i += 3
and x = x * (y + 2) as x *= y + 2.
The relational operators are used to determine the relationship of one quantity to
another. They always return 1 or 0 depending upon the outcome of the test. The
relational operators are as follows:
Operator Action
== equal to
!= not equal to
< Less than
<= less than or equal to
> Greater than
>= Greater than or equal to
If the values of x and y, are 1 and 2 respectively then the various expressions and their
results are:
if (i = j) .....
This is a perfectly LEGAL C statement (syntactically speaking) which copies the value in
"j" into "i", and delivers this value, which will then be interpreted as TRUE if j is non-
zero. This is called assignment by value -- a key feature of C.
Other operators < (less than), > (grater than), <= (less than or equals), >= (greater
than or equals) are as usual.
Study material 17
1.17.3. Logical (Comparison) Operators:
Logical operators are usually used with conditional statements. The three basic logical
operators are && for logical AND, || for logical OR and ! for not.
The truth table for the logical operators is shown here using one’s and zero’s. (the idea
of true and false under lies the concepts of relational and logical operators). In C true is
any value other than zero, false is zero. Expressions that use relational or logical
operators return zero for false and one for true.
P Q P && q P || q !p
0 0 0 0 1
0 1 0 1 1
1 1 1 1 0
1 0 0 1 0
Example:
(i) x == 6 && y == 7
This while expression will be TRUE (1) if both x equals 6 and y equals 7, and FALSE (0)
otherwise.
Bitwise operators
& AND
| OR
^ XOR
~ One's Compliment
<< Left shift
>> Right Shift
The truth table for Bitwise operators AND, OR, and XOR is shown below. The table uses
1 for true and 0 for false.
P Q P AND q P OR q P XOR q
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
DO NOT confuse & with &&: & is bit wise AND, && logical AND. Similarly for | and ||.
Study material 18
~ is a unary operator: it only operates on one argument to right of the operator. It finds
1’s compliment (unary). It translates all the 1 bits into O’s and all O’s into 1’s
Example:
12 = 00001100
~12 = 11110011 = 243
The shift operators perform appropriate shift by operator on the right to the operator on
the left. The right operator must be positive. The vacated bits are filled with zero (i.e.
when shift operation takes places any bits shifted off are lost).
Example:
NOTE: Shifting is much faster than actual multiplication (*) or division (/) by 2. So if
you want fast multiplications or division by 2 use shifts.
The bit wise AND operator (&) returns 1 if both the operands are one, otherwise it
returns zero. For example, if y = 29 and z = 83, x = y & z the result is:
0 0 0 1 1 1 0 1 29 in binary
&
0 1 0 1 0 0 1 1 83 in binary
0 0 0 1 0 0 0 1 Result
The bit wise or operator (|) returns 1 if one or more bits have a value of 1, otherwise it
returns zero. For example if, y = 29 and z = 83, x = y | z the result is:
0 0 0 1 1 1 0 1 29 in binary
|
0 1 0 1 0 0 1 1 83 in binary
0 1 0 1 1 1 1 1 Result
The bit wise XOR operator (^) returns 1 if one of the operand is 1 and the other is zero,
otherwise if returns zero. For example, if y = 29 and z = 83, x = y ^ z the result is:
0 0 0 1 1 1 0 1 29 in binary
^
0 1 0 1 0 0 1 1 83 in binary
0 1 0 0 1 1 1 0 Result
Study material 19
1.17.5. Conditional Operator:
(x > 7) ? 2 : 3
What this says is that if x is greater than 7 then the expression value is 2. Otherwise the
expression value is 3.
Evaluation of this expression begins with the evaluation of the sub-expression ‘a’. If the
value of ‘a’ is true then the while condition expression evaluates to the value of the sub-
expression ‘b’. If the value of ‘a’ is FALSE then the conditional expression returns the
value of the sub-expression ‘C’.
In situation where you need to incorporate the size of some object into an expression
and also for the code to be portable across different machines the size of unary operator
will be useful. The size of operator computes the size of any object at compile time. This
can be used for dynamic memory allocation.
Example:
sizeof (char) = 1
sizeof (int) = 2
sizeof (float) = 4
sizeof (double) = 8
Some of the special operators used in C are listed below. These are reffered as
separators or punctuators.
Ampersand:
Ampersand ( & ) also referred as address of operator usually precedes the identifier
name, which indicates the memory allocation (address) of the identifier.
Comma:
Comma ( , ) operator is used to link the related expressions together. Comma used
expressions are linked from left to right and the value of the right most expression is the
value of the combined expression. The comma operator has the lowest precedence of all
operators. For example:
Study material 20
Sum = (x = 12, y = 8, x + y);
The comma operator is also used to separate variables during declaration. For example:
int a, b, c;
Asterick:
Ellipsis:
Ellipsis ( … ) are three successive periods with no white space in between them. It is
used in function prototypes to indicate that this function can have any number of
arguments with varying types. For example:
The above declaration indicates that fun () is a function that takes at least three
arguments, a char, an int and a float in the order specified, but can have any number of
additional arguments of any type.
Hash:
Hash (#) also referred as pound sign is used to indicate preprocessor directives, which is
discussed in detail already.
Parenthesis:
Parenthesis () also referred as function call operator is used to indicate the opening and
closing of function prototypes, function calls, function parameters, etc., Parenthesis are
also used to group expressions, and there by changing the order of evaluation of
expressions.
Semicolon:
c = a + b;
b = 5;
Study material 21
All operators have a priority, and high priority operators are evaluated before lower
priority ones. Operators of the same priority are evaluated from left to right, so that:
a-b-c
is evaluated as: (a - b) - c
From high priority to low priority the order for all C operators (we have not met all of
them yet) is:
Highest ( ) [ ] -> .
! ~ - (type) * & sizeof ++ --
*/%
+-
<< >>
< <= >= >
== !=
&
^
|
&&
||
?:
= += -= *= /= etc.
Lowest , (comma)
Thus: a < 10 && 2 * b < c is interpreted as: (a < 10) && ((2 * b) < c)
Turbo C++ editor will find the companion delimiters for the following pairs:
To find the matching delimiter, place the cursor on the delimiter you wish to match and
press CTRL – Q [ for a forward match and CTRL – Q ] for a reverse match. The editor will
move the cursor to the matching delimiter.
int a = 3;
int b = 2;
float c;
c = b * (a / b);
printf ("2 * (3 / 2) = %f\n", c);
doesn't behave as you might expect. Because the first (a/b) is performed with integer
arithmetic it gets the answer 1 not 1.5. Therefore the program prints:
2 * (3/2) = 2.000
Study material 22
The best way round this is what is known as a cast. We can cast a variable of one type
to another type like so:
int a = 3;
int b = 2;
float c;
c = b * ( (float) a / b);
The (float) a construct tells the compiler to switch the type of variable to be a float. The
value of the expression is automatically cast to float . The main use of casting is when
you have written a routine which takes a variable of one type and you want to call it with
a variable of another type. For example, say we have written a power function with a
prototype like so:
We might well have a float that we want to find an approximate power of a given
number n. Your compiler should complain bitterly about your writing:
float n= 4.0;
int squared;
squared= pow (n, 2);
The compiler will not like this because it expects n to be of type int but not float.
However, in this case, we want to tell the compiler that we do know what we're doing
and have good reason for passing it a float when it expects an int (whatever that reason
might be). Again, a cast can rescue us:
float n = 4.0;
int squared;
squared = pow ((int) n, 2); /* We cast the float down to an int*/
IMPORTANT RULE: To move a variable from one type to another then we use a cast
which has the form (variable_type) variable_name.
CAUTION: It can be a problem when we downcast – that is cast to a type which has less
precision than the type we are casting from. For example, if we cast a double to a float
we will lose some bits of precision. If we cast an int to a char it is likely to overflow
[recall that a char is basically an int which fits into 8 binary bits].
Console I/O refers to operations that occur at the keyboard and screen of your
computer.
The simplest of the console I/O functions are getche (), which reads a character from the
keyboard, and putchar (), which prints a character to the screen. The getche () function
waits until a key is pressed and then returns its value. The key pressed is also echoed to
the screen automatically. The putchar () function will write its character argument to the
screen at the current cursor position. The prototypes for getche () and putchar () are
shown here:
Study material 23
The following programs inputs characters from the keyboard and prints them in reverse
case. That is, uppercase prints as lowercase, the lowercase prints as uppercase. The
program halts when a period is typed. The header file CTYPE.H is required by the
islower() library function, which returns true if its argument is lowercase and false if it is
not.
# include <stdio.h>
# include <conio.h>
# include <ctype.h>
main(void)
{
char ch;
printf (“enter chars, enter a period to stop\n”);
do
{
ch = getche ();
if ( islower (ch) )
putchar (toupper (ch));
else
putchar (tolower (ch));
} while (ch! = ‘.’); /* use a period to stop */
return 0;
}
• The first is getchar(), which is the original, UNIX-based character input function.
The trouble with getchar() is that it buffers input until a carriage return is
entered. The reason for this is that the original UNIX systems line-buffered
terminal input, i.e., you had to hit a carriage return for anything you had just
typed to actually be sent to the computer.
On the next step, the functions gets() and puts() enable us to read and write strings of
characters at the console.
The gets() function reads a string of characters entered at the keyboard and places them
at the address pointed to by its argument. We can type characters at the keyboard until
we strike a carriage return. The carriage return does not become part of the string;
instead a null terminator is placed at the end and gets() returns. Typing mistakes can be
corrected prior to striking ENTER. The prototype for gets() is:
Where, str is a character array that receives the characters input by the user. Its
prototype is found in STDIO.H. The following program reads a string into the array str
and prints its length.
Study material 24
# include <stdio.h>
# include <string.h>
main(void)
{
char str[80];
gets (str);
printf (“length is %d”, strlen(str));
return 0;
}
The puts() function writes its string argument to the screen followed by a newline. Its
prototype is.
It recognizes the same backslash codes as printf(), such as “\t” for tab. It cannot output
numbers or do format conversions. Therefore, puts() takes up less space and runs faster
than printf(). Hence, the puts() function is often used when it is important to have highly
optimized code. The puts() function returns a non negative value if successful, EOF
otherwise. The following statement writes “hello” on the screen.
puts (“hello”);
Function Operation
getchar() Reads a character from the keyboard and waits for carriage return
getche() Reads a character with echo and does not waits for carriage return
Reads a character from the keyboard with out echo and not waits for
getch()
carriage return
Putchar() Writes a character to the screen
gets() Reads a string from the keyboard
puts() Writes a string to the screen
getchar() gets()
Used to receive a single character. Used to receive a single string, white
spaces and blanks.
Does not require any argument. It requires a single argument.
All data that is entered into a C program by using the scanf function enters the computer
through a special storage area in memory called the standard input buffer (or stdin).
A user's keystrokes (including the new line character \n generated when the Enter key is
pressed) are stored in this buffer, which can then be read using functions such as scanf.
When numbers are read from this area, the function converts the keystrokes stored in
Study material 25
the buffer (except for the \n) into the type of data specified by the control string (such
as "%f") and stores it in the memory location indicated by the second parameter in the
scanf function call (the variable's address). The \n remains in the buffer. This can cause
a problem if the next scanf statement is intended to read a character from the buffer.
The program will mistakenly read the remaining \n as the character pressed by the user
and then proceed to the next statement, never even allowing the user to enter a
character of their own.
You can solve this problem when writing C statements to read character data from the
keyboard by adding a call to a special function named fflush that clears all characters
(including \n's) from the given input buffer. The statement would be place ahead of each
statement in your program used to input characters, such as:
The pre-written function printf() is used to output most types of data to the screen and
to other devices such as disks. The C statement to display the word "Hello" would be:
printf("Hello");
The printf() function can be used to display "prompts" (messages urging a user to enter
some data) as in:
When executed, this statement would leave the cursor on the same line as the prompt
and allow the user to enter a response following it on the same line. A space was
included at the end of the prompt (before the closing quote mark) to separate the
upcoming response from the prompt and make the prompt easier to read during data
entry.
If you want a carriage return to occur after displaying a message, simply include the
special escape sequence \n at the end of the of the message before the terminating
quote mark, as in the statement.
All data output by the printf() function is actually produced as a string of characters (one
symbol after another). This is because display screens are character-based devices. In
order to send any other type of data (such as integers and floats) to the screen, you
must add special symbols called conversion specifiers to the output command to convert
data from its stored data format into a string of characters. The C statement to display
the floating point number 123.456 would be:
printf ("%f",123.456);
Study material 26
The "%f" is a conversion specifier. It tells the printf() function to convert the floating
point data into a string of characters so that it can be sent to the screen. When
outputting non-string data with the printf() function you must include two parameters
(items of data) within the parentheses following printf(). The first parameter is a quoted
control string containing the appropriate conversion specifier for the type of non-string
data being displayed and optionally any text that should be displayed with it. The second
parameter (following a comma) should be the value or variable containing the value. The
C statement to display the floating point number 123.456 preceded by the string "The
answer is: " and followed by a carriage return would be:
Notice that the value does not get typed inside of the quoted control string, but rather as
a separate item following it and separated by a comma. The conversion specifier acts as
a place holder for the data within the output string.
The following table lists the most common conversion specifiers and the types of data
that they convert:
Study material 27
1.24.4. Output Field Width and Rounding:
When displaying the contents of a variable, we seldom know what the value will be. And
yet, we can still control the format of the output field (area), including the:
amount of space provided for output (referred to as the output's "field width")
alignment of output (left or right) within a specified field and rounding of floating point
numbers to a fixed number of places right of the decimal point
Output formatting is used to define specific alignment and rounding of output, and can
be performed in the printf() function by including information within the conversion
specifier. For example, to display the floating point number 123.456 right-aligned in an
eight character wide output field and rounded to two decimal places, you would expand
basic conversion specifier from "%f" to "%8.2f". The revised statement would read:
The 8 would indicate the width, and the .2 would indicating the rounding. Keep in mind
that the addition of these specifiers as no effect on the value itself, only on the
appearance of the output characters.
The value 123.456 in the statement above could be replaced by a variable or a symbolic
constant of the same data type. The 8 in the statement above specifies the width of the
output field. If you include a width in the conversion specifier, the function will attempt
to display the number in that width, aligning it against the rightmost character position.
Unused positions will appear as blank spaces (padding) on the left of the output field. If
you want the value to be left-aligned within the field, precede the width with a minus
sign (-). If no width is specified, the number will be displayed using only as many
characters as are necessary without padding. When a values is too large to fit in a
specified field width, the function will expand the field to use as many characters as
necessary.
The .2 in the statement above specifies the decimal precision (i.e., the number of place
that you want to appear to the right of the decimal point) and would be used only in
situations where you are outputting floating point values. The function will round the
output to use the specified number of places (adding zeros to the end if necessary). Any
specified field width includes the decimal point and the digits to its right. The default
decimal precision (if none is specified) is 6 places.
In situations where you want floating point values displayed in scientific notation,
formatting also is used to define specific alignment and rounding of output in the printf
function by including information within the conversion specifier %e. For example, to
display the floating point number 123.456 in scientific notation in a twelve character
wide output field with its mantissa (significant digits) rounded to two decimal places, you
would expand basic conversion specifier from "%e" to "%12.2e". The resulting output
would be:
Notice that values displayed in scientific notation always place the decimal point after the
first significant digit and use the exponent (digits shown following the letter e) to
express the power of the number. The C statement to produce the output above would
be:
The 12 would indicate the overall field width (following any message) including the
decimal point and the exponential information. The .2 would indicating the rounding of
the digits following the decimal point. The exponential information is always expressed in
Study material 28
5 characters: the first one an "e", then a sign (- or +), followed by the power in three
characters (with leading zeros if needed).
Review the following examples of formatted output statements paying close attention to
the format of the resulting output beside them. Each box indicates one character position
on the screen. All output starts in the leftmost box, although some output might be
"padded" with blank spaces to align it to the right edge of the field. "X"'s indicated
unused positions.
1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
printf ("%3c",'A'); A X X X X X X X X X X X X X X X X X
printf ("%-3c",'A'); A X X X X X X X X X X X X X X X X X
printf ("%8s","ABCD"); A B C D X X X X X X X X X X X X
printf ("%d",52); 5 2 X X X X X X X X X X X X X X X X X X
printf ("%8d",52); 5 2 X X X X X X X X X X X X
printf ("%-8d",52); 5 2 X X X X X X X X X X X X
printf ("%f",123.456); 1 2 3 . 4 5 6 0 0 0 X X X X X X X X X X
printf ("%10f",123.456); 1 2 3 . 4 5 6 0 0 0 X X X X X X X X X X
printf ("%10.2f",123.456); 1 2 3 . 4 6 X X X X X X X X X X
printf ("%-10.2f",123.456); 1 2 3 . 4 6 X X X X X X X X X X
printf ("%.2f",123.456); 1 2 3 . 4 6 X X X X X X X X X X X X X X
printf ("%10.3f",-45.8); - 4 5 . 8 0 0 X X X X X X X X X X
printf ("%10f",0.00085); 0 . 0 0 0 8 5 0 X X X X X X X X X X
printf ("%10.2e",123.89); 1 . 2 4 e + 0 0 2 X X X X X X X X X X
puts() printf()
They can display any number of
They can display only one string at a time.
characters, integers or strings a time.
All data types of considered as characters. Each data type is considered
separately depending upon the
conversion specifications.
Study material 29
1.23. scanf () function:
scanf() is the general purpose console input routine. It can read all the built-in data
types of automatically convert numbers into the proper internal format. It is much like
the reverse of printf(). The f in scanf stands for formatted.
# include <stdio.h>
int main()
{
int num;
printf (“Enter a number: “);
scanf(“%d”, &num);
printf(“The number you have entered was %d\n”, num);
return 0;
}
The above program requires a variable in which to store the value for num. The
declaration, int num; provides a temporary storage area called num that has a data type
of integer (whole number). The scanf function requires a Format String, which is
provided by the %d character pair. The percent sign is an introducer and is followed by a
conversion character, d, which specifies that the input is to be an integer. The input is
stored in the variable, num. The scanf function requires the address of the variable, and
this is achieved by prefixing the variable name with an ampersand (eg. &num).
The printf statement also uses the format string to relay the information. The printf
function does not require the address of the variable and so the ampersand is not
required. The prototype for scanf() is in STDIO.H.
Code Meaning
%c Read a single character
%d Read a decimal integer
%i Read a decimal integer, hexa decimal or octal integer
%h Read a short integer
%e Read a floating-point number
%f Read a floating-point number
%g Read a floating-point number
%o Read an octal number
%s Read a string
%x Read a hexadecimal number
%p Read a pointer
%n Receives an integer value equal to the number of characters read so far
%u Read an unsigned integer
%[..] Scan for a string of words
Study material 30
Distinguishing between scanf() and gets() functions:
scanf() gets()
Strings with spaces cannot be accessed Strings with any number of spaces can
until ENTER key is pressed. be accessed.
Only character data type can be
All data types can be accessed.
accessed.
Spaces and tabs are not acceptable as a Spaces and tabs are perfectly acceptable
part of the input string. of the input string as a part.
Only one string can be received at a
Any number of characters, integers. time. Strings, floats can be received at a
time.
The list of terms below is provided to supplement or elaborate on the boldfaced terms
and definitions provided in the course textbook. Students are advised to also review the
textbook to develop a fuller understanding of these and other important terms related.
ASCII is the American Standard Code for Information Interchange; a language for
representing text on computers.
Binary is a word with two meanings in programming. The first and most common
meaning relates to the numbering system known as "Base-2" in which all values are
represented using only "two (bi) numerals (nary) ". The second meaning relates to the
use of operators such as the minus sign (-) in a formula. When the symbol appears
between two items (such as the values 5 and 2 in the formula 5-2), it is referred to as a
"binary operator". When the symbol appears preceding only one item (such as the value
2 in the formula -2), it is referred to as a "unary operator".
Bits are binary digits (0 or 1) that represent the settings of individual switches or
circuits inside a computer (OFF or ON). Data is represented as standardized patterns of
bits.
A byte is the unit of measure of storage space used to represent a single character.
There are typically 8 bits in a byte.
Decimal is another word with two meanings in programming. The first and most
common meaning relates to the numbering system known as "Base-10" in which all
values are represented using ten digits (0-9). The second meaning relates to the use of
a decimal point when writing numbers with fractional parts, such as one half in 8.5 or
one tenth in 4.1. Numbers written containing a decimal point are often referred to as
"decimal numbers", however this is technically incorrect, as it implies that the numbers
are also written using the Base-10 numbering system (which may not be the case). A
more precise way to talk about numbers that contain fractional parts is to call them
"floating point numbers" or more simply "floats".
Bug: A bug is an error in a program. These can be split into syntax errors and semantic
errors. A Syntax error is where the language rules of the C programming language have
been broken, and can be easily picked up by the C Compiler – e.g. a missing semi-colon.
A semantic error is harder-to find, and refers to an error where the syntax of the
program is correct, but the meaning of the program is not what was intended – e.g. int
three_cubed=3*3; when you actually meant int three_cubed=3*3*3;
Study material 31
Breakpoint: This is a line of source code, marked in some way, where the program
execution stops temporarily for you to examine what is happening – e.g. the contents of
variables etc. Once stopped, you can usually step through the execution of the program
line-by-line to see how variables change, and to follow the flow of execution in the
program.
Build: This is the step following compilation. It takes one or a number of object code
files generated by one or more compiled programs, and links them together to form an
executable file that comprises instructions that are understood by the computer on which
the application is to run.
Execution: This means running a program – i.e. starting the executable file going so
that we can see the program working.
Debugging: Debugging refers to the task of removing bugs from a program. This is
often attained with the help of tools in the IDE, such as creating breakpoints, stepping
through line-by-line etc.
Executable: The name given to a file on your computer that contains instructions
written in machine code. These are typically applications that do some task on your
computer – e.g. Microsoft Word has an executable file (winword.exe) that you can
execute in order to start the application.
IDE: Integrated Development Environment. The application used to edit your source
code, perform debugging tasks, compile and build your application, and organize your
projects. It acts as a complete set of tools in which to create your C programs.
Program: This is a generic name for an application on your computer that performs a
task. An application such as Microsoft Word may be referred to as a program.
Sometimes also used to refer rather vaguely as the source code that, when compiled,
will generate the executable application.
Run: When we refer to running a program, we are referring to the execution (starting)
of the executable version of the program so that we can see the program working.
Machine Code: The language that each type of computer understands. All PCs
understand instructions based on microprocessors such as the Intel 8086 through to the
latest Pentium processors, Macintoshes understand instructions based on the 68000 and
upwards processors, and Sun servers understand instructions based on Sun's Sparc
processor.
Syntax: The syntax refers to the structure of a C program. It refers to the rules that
determine what is a correct C program. A Syntax Error is where a part of the program
breaks these rules in some way – e.g. a semi-colon omitted from the end of a C
instruction.
Source Code: The C Program that you type in using a text editor, containing a list of C
instructions that describe the tasks you wish to perform. The source code is typically
fairly independent of the computer that you write it on – the compile and build stages
convert it to a form that is understood by your computer.
Study material 32
Object code is machine language that resulted from a compiling operation being
performed. Files containing C object code typically end with a filename extension of
".obj".
Text Editor: An application program, rather like a word-processor, that you use to type
out your C source code instructions to create a C program. These can be as simple as
the notepad text editor supplied with Microsoft Windows, to the sophisticated editor that
comes part of an IDE, typically including features such as bookmarks, integrated
debugging, and syntax highlighting.
A header file is a file containing useful blocks of pre-written C source code that can be
added to your source code using the "# include" compiler directive. Header files typically
end with a filename extension of ".h".
White space is any character or group of characters that a program normally interprets
as a separator of text, including: spaces ( ), form feeds (\f), new-lines (\n), carriage
returns (\r), horizontal tabs (\t), and vertical tabs (\v). In C source code, all of these
characters are interpreted as the same unless they are quoted. In other words, one
space is interpreted the same as three blank lines.
The declaration part of a program defines its identifiers, such as: symbolic constants
and variable names and data types.
The body of a program contains the statements that represent the steps in the main
algorithm.
A constant (also called as literal) is an actual piece of data (also often referred to as a
"value") such as the number 5 or the character 'A'.
Symbolic Constants are aliases (nicknames) used when coding programs in place of
values that are expected to be the same during each execution of a program, but might
need to be changed someday. Symbolic constants are defined within C source code using
the "#define" compiler directive at the top of the program to allow easy location and
revision later.
A keyword is a reserved word within a program that can NOT be redefined by the
programmer.
Identifiers are labels used to represent such items such as: constants, variables, and
functions. Identifiers are case-sensitive in C, meaning that upper and lowercase
appearances of the same name are treated as being different identifiers. Identifiers that
are defined within a function (see below) are local to that function, meaning that they
will not be recognized outside of it. Identifiers that are defined outside of all functions
are global, meaning that they will be recognized within all functions.
Addresses are numeric designations (like the numbers on mailboxes) that distinguish
one data storage location from another. Prior to the use of identifiers, programmers had
to remember the address of stored data rather than its identifier. In C, addresses are
referred to by preceding an identifier with an ampersand symbol (&) as in &X which
refers to the address of storage location X as opposed to its contents.
Study material 33
Integer data is a numeric type of data involving a whole number (i.e. it CANNOT HAVE
a fractional portion). An example of an integer constant is 5 (written without a decimal
point). The most common type identifier (reserved word used in a declaration) for
integer data is int.
Floating point data is a numeric type of data that CAN HAVE a fractional portion.
Mathematicians call such data a real number. An example of a floating point constant is
12.567 (written without a decimal point). The most common type identifiers for floating
point data are float (for typical numbers) and double (for numbers such as
1.2345678901234E+205 that involve extreme precision or magnitude).
Character data is a type of data that involves only a single symbol such as: 'A', '4', '!', or
' ' (a blank space). The type identifier for character data is char.
String data is a type of data involving multiple symbols such as words or sentences.
The C language stores strings as a collection of separate characters (see above).
Boolean data is a logical type of data involving only two values: True or False. The
identifier used in C to declare Boolean data is bool.
A sample softcopy is program documentation that precisely demonstrates all video (or
other intangible) output required of a program.
Pseudocode is an algorithm written in English, but as clearly stated logical items that
can be easily translated by a programmer into C or other high-level programming
languages.
A desk check is a manual test of a program algorithm that is performed prior to writing
the source code. It must follow the algorithm exactly and typically produces two items of
documentation: the tracing chart showing what values are stored in memory during
program execution, and any test outputs (softcopy and hardcopy) showing that the
algorithm will produce the output specified earlier in the samples.
A logic error is caused by a mistake in the steps used to design the program algorithm.
A syntax error is caused by a grammatical error in the language of the source code.
Comments can be included within C source code, enclosed in the symbols /* and */.
The inclusion of comments in source code neither causes the program to run more
slowly, nor causes the object code to take up more space, since comments are not
translated.
Study material 34
Blank spaces in C code act as separators and are not allowed in an identifier. Multiple
blank spaces are treated the same as one, except in string constants (text inside of
double quotes).
Escape sequences are special strings typed within C output statements to produce
characters that would otherwise be interpreted as having special meaning to the
compiler.
printf is the name of a function in C that will display formatted output on the screen.
scanf is the name of a function in C that will store input from a keyboard into a variable
and then advance the cursor to the next line when the user presses the Enter key.
Study material 35
Order of Precedence is a term used to describe which operations precede others when
groups of operators appear in an expression. For example, C compilers see the
expression A+B/C as A+(B/C) as opposed to (A+B)/C. The division operation will
preceed the addition because division has a higher order of precedence.
Casting is the process of converting data from one data type to another. For example, if
you try to divide two integer variables A and B and store the result in a floating point
variable C, the result will have any decimal fraction truncated (chopped-off) because
both operands are integers. To prevent this, cast either of the operands as floats before
the division operation is performed, as in either of the following examples:
C = (float) A / B;
C = A / (float) B;
Trying to cast the result instead of the operands would be pointless because the
truncation would have already taken place. So it would be ineffective to try:
C = (float) (A / B);
Boolean data is a logical type of data with only two values: True and False. Boolean
data can be represented in two ways in C. When you want to store Boolean data for
fututre use, a variable can be declared to have data type of _Bool (notice the leading
underscore and capitalization). A common alternative approach is to represent the true
and false values using the integer values of 1 for true and 0 for false. Many functions in
C use the latter approach and return a 1 or a 0 to indicate if a condition is true or false.
In C, any non-zero integer value is interpreted as true.
Ordinal data is a type of data in which all of the values within the set are known and in
a predictable order. Ordinal data types include: all integer data types and char data, but
not floating point or string data.
Relational operators are those used to evaluate the relationships between items of
data, including:
== for Equal to, the opposite of which is written in C as != (or not equal to).
> - Greater than, the opposite of which is written in C as <= (less than or equal to).
< - Less than, the opposite of which is written in C as >= (greater than or equal to).
Logical operators such as && for "and", || for "or" and ! for "not" are those used to
combine conditions into logical expressions such as (X==0 && Y>10) to produce a single
boolean result.
Branching is the act of breaking out of the normal sequence of steps in an algorithm to
allow an alternative process to be performed or to allow the repetition of process(es).
Study material 36
Chapter
2
This deals with the various methods that C can control the flow of logic in a program.
Control statements can be classified as un-conditional and conditional branch
statements and loop or iterative statements. The Branch type includes:
1. Un-conditional:
• goto
• break
• return
• continue
2. Conditional:
• if
• if – else
• Nested if
• switch case statement
3. Loop or iterative:
• for loop
• while loop
• do-while loop
Sometimes we want a program to select an action from two or more alternatives. This
requires a deviation from the basic sequential order of statement execution. Such
programs must contain two or more statements that might be executed, but have
some way to select only one of the listed options each time the program is run. This is
known as conditional execution.
2.1.1. if statement:
if (condition)
statement_to_execute_if_condition_is_true;
or
if (condition)
{
statement 1;
statement 2;
_ _ _ _;
}
Flowchart Segment:
if T
(Condition) Statement 1
The if statement is used to execute only one action. If there are two statements to be
executed alternatively, then if-else statement is used. The if-else statement is a two
way branching. The general syntax of simple if - else statement is:
if (condition)
statement_to_execute_if_condition_is_true;
else
statement_to_execute_if_condition_is_false;
Where, statement may be a single statement, a block, or nothing, and the else
statement is optional. The conditional statement produces a scalar result, i.e., an
integer, character or floating point type.
F if T
Statement 2 (Condition) Statement 1
Example:
main()
{
int num;
printf(“ Enter a number : “);
scanf(“%d”,&num);
if (num % 2 == 0)
printf(“ Even Number “);
else
printf(“ Odd Number “);
}
The ANSI standard specifies that 15 levels of nesting must be supported. In C, an else
statement always refers to the nearest if statement in the same block and not already
associated with if.
Example:
main()
{
int num;
printf(“ Enter a number : “);
scanf(“%d”,&num);
if( num > 0 )
{
if( num % 2 == 0)
printf(“Even Number“);
else
printf(“Odd Number“);
}
else
{
if( num < 0 )
printf(“Negative Number“);
else
printf(“ Number is Zero“);
}
}
T
Condition 1
T
F Condition 2 Statement
When faced with a situation in which a program must select from many processing
alternatives based on the value of a single variable, an analyst must expand his or her
use of the basic selection structure beyond the standard two processing branches
offered by the if statement to allow for multiple branches. One solution to this is to
use an approach called nesting in which one (or both) branch(es) of a selection
contain another selection. This approach is applied to each branch of an algorithm until
enough additional branches have been created to handle each alternative. The general
syntax of a nested if statement is:
if (expression)
statement1
else if (expression)
statement2
..
..
else
statement3
Example:
#include <stdio.h>
void main (void)
{
int N; /* Menu Choice */
printf ("MENU OF TERMS\n\n");
printf ("1. Single\n");
printf ("2. Double\n");
printf ("3. Triple\n");
printf ("4. Quadruple\n\n");
printf ("Enter the numbe (1-4): ");
scanf ("%d", &N);
if (N == 1) printf ("one");
else if (N == 2) printf ("two");
else if (N == 3) printf ("three");
else if (N == 4) printf ("four");
else printf ("ERROR");
T F
ONE N=2
T F
TWO N=3
T F
THREE N=4
FOUR ERROR
The ? (ternary condition) operator is a more efficient form for expressing simple if
statements. It has the following form:
Example:
if (a > b)
z = a;
else
z = b;
switch (expression)
{
case constant1:
statement;
break;
case constant2:
statement;
break;
default:
statement;
break;
}
In this construct, the expression whose value is being compared may be any valid
expression, including the value of a variable, an arithmetic expression, a logical
comparison rarely, a bit wise expression, or the return value from a function call, but
not a floating-point expression. The expression’s value is checked against each of the
specified cases and when a match occurs, the statements following that case are
executed. When a break statement is encountered, control proceeds to the end of the
switch - case statement.
The break statements inside the switch statement are optional. If the break statement
is omitted, execution will continue on into the next case statements even though a
match has already taken place until either a break or the end of the switch is reached.
The keyword case may only be constants, they cannot be expressions. They may be
integers or characters, but not floating point numbers or character string.
The last case is a special keyword default. The default statement is executed if no
matches are found. The default is optional and if it is not present, no action takes place
if all matches fail.
1. The switch differs from the if in that switch can only test for equality
whereas if can evaluate any type of relational or logical expression.
2. No two case constants in the same switch can have identical values. But, a
switch statement enclosed by an outer switch may have case constants and
either same.
In the example below, five possible paths might be followed depending on the value
stored in the character storage location X. Each path is selected based on the individual
value(s) that might be stored in X.
switch
(expression)
N
case 1 Y
Statement Break
match ?
N
Y
case 2 Statement Break
match ?
N
Y
case n Statement Break
match ?
N
Default
Statement
Next
Statement
Example 1:
main()
{
char gender;
printf (“Enter Gender code:(M/F)“);
scanf (“%c”, &gender);
switch (gender)
{
case ‘M’ : printf (“ Male“);
break;
case ‘F’ : prrintf (“Female”);
break;
default : printf (“Wrong code“);
}
}
We can also have null statements by just including a “;” or let the switch statement fall
through by omitting any statements (see example below).
Example 2:
switch (letter)
{
case `A':
case `E':
case `I' :
In the above example if the value of letter is `A', `E', `I', `O' or `U' then
numberofvowels is incremented. If the value of letter is ` ' then numberofspaces is
incremented. If none of these is true then the default condition is executed, that is
numberofconstants is incremented.
• for statement
• while statement
• do-while statement
The for loop statement is useful to repeat a statement/s a known number of times.
The general syntax is as follows:
The initialization is generally an assignment statement that is used to set the loop
control variable.
The Operation defines how the loop control variable changes each time the loop is
repeated.
We must separate these three major sections by semicolon.
The for loop continues to execute as long as the condition is true. Once the condition
becomes false, program execution resumes on the statement following the for. The
control flow of the for statement is as follows:
1 is ODD
2 is EVEN
3 is ODD
4 is EVEN
5 is EVEN
Example 2:
Initialization
Condition
Increment
Statement in
The loop
Next
Statement
All the following are legal for statements in C. The practical application of such
statements is not important here, we are just trying to illustrate peculiar features that
may be useful:
The second example shows that multiple expressions can be separated by a , (comma).
Example:
main()
{
int j ;
double degC, degF;
clrscr ();
printf (“\n Table of Celsius and Fahrenheit degrees \n\n”);
printf (“Celsius Degree \t Fahrenheit Degree \n“)
degC = -20.0;
for (j = 1; j <= 6; j++)
{
degC = degC + 20.0;
degF = (degC * 9.0/5.0) + 32.0;
printf (“\n %7.2lf\t\ %7.2lf “, degC, degF);
}
}
Output:
Nested loops consist of one loop placed inside another loop. An example of a nested for
loop is:
for (initialization; condition; operation)
{
for (initialization; condition; operation)
{
statement;
}
statement;
}
Example:
void main()
{
int i, j, k, temp;
printf("I\tI^2\tI^3\tI^4 \n");
printf("--------------------------------\n");
for ( i = 1; i < 10; i ++) /* Outer loop */
{
for (j = 1; j < 5; j ++) /* 1st level of nesting */
{
temp = 1;
for(k = 0; k < j; k ++)
temp = temp * I;
printf ("%d\t", temp);
}
printf ("\n");
}
}
^
I I 2 I^3 I^4
-----------------------------------
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
5 25 125 625
6 36 216 1296
7 49 343 2401
8 64 512 4096
9 81 729 6561
We can make an endless loop by leaving the conditional expression empty as given
below:
for( ; ; )
printf(“This loop will run for ever”);
To terminate the infinite loop the break statement can be used anywhere inside the
body of the loop. A sample example is given below:
This loop will run until the user types an A at the keyboard.
A C-statement may be empty. This means that the body of the for loop may also be
empty. There need not be an expression present for any of the sections. The
expressions are optional.
Example 1:
for( x = 0; x != 123; )
scanf (“%d”, &x);
This means that each time the loop repeats, ‘x’ is tested to see if it equals 123, but no
further action takes place. If you type 123, at the keyboard, however the loop condition
becomes false and the loop terminates.
The initialization some times happens when the initial condition of the loop control
variable must be computed by some complex means.
Example 2:
#include<conio.h>
#include<string.h>
#include<stdio.h>
void main()
{
char s[20];
int x;
clrscr ();
printf ("\nEnter your name: ");
gets (s);
x = strlen (s);
for ( ; x > 0 ; )
{
--x;
printf ("%c\t", s[x]);
}
}
N A R I K
while (expression)
statement
The condition, can be any valid C languages expression including the value of a
variable, a unary or binary expression, an arithmetic expression, or the return value
from a function call.
while (condition)
{
statement1;
statement2;
}
With the if statement, it is important that no semicolon follow the closing parenthesis,
otherwise the compiler will assume the loop body consists of a single null statement.
This usually results in an infinite loop because the value of the condition will not change
with in the body of the loop.
Example:
main()
{
int j = 1;
double degC, degF;
clrscr ();
printf (“\n Table of Celsius and Fahrenheit degrees \n\n”);
printf (“Celsius Degree \t Fahrenheit Degree \n“)
degC = -20.0;
while (j <= 6)
{
degC = degC + 20.0;
degF = (degC * 9.0/5.0) + 32.0;
printf (“\n %7.2lf\t\ %7.2lf “, degC, degF);
j++;
}
}
while F
(Condition)
Statement in Next
the while loop Statement
Because the while loop can accept expressions, not just conditions, the following are all
legal:
while(x--);
while(x = x+1);
while(x += 5);
Using this type of expression, only when the result of x--, x=x+1, or x+=5, evaluates
to 0 will the while condition fail and the loop be exited.
We can go further still and perform complete operations within the while expression:
This uses C standard library functions: getchar () to reads a character from the
keyboard and putchar () to writes a given char to screen. The while loop will proceed to
read from the keyboard and echo characters to the screen until a 'q' character is read.
Nested while:
Example:
^
I I 2 I^3 I^4
-----------------------------------
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
5 25 125 625
6 36 216 1296
7 49 343 2401
8 64 512 4096
9 81 729 6561
do
statement;
while (expression);
If more than one statement is to be executed in the body of the loop, then these
statements may be formed into a compound statement as follows:
do
{
statement1;
statement2;
} while (condition);
do
Statement
in the
loop
while T
(Condition)
Next
Statement
Example 1:
# include <stdio.h>
main()
{
do
{
printf("x = %d\n", x--);
} while(x > 0);
}
X=3
X=2
X=1
Example 2:
#include <stdio.h>
void main()
{
char ch;
T: Train
C: Car
S: Ship
• return
• goto
• break and
• continue
A return statement is used to return from a function. A function can use this statement
as a mechanism to return a value to its calling function. If now value is specified,
assume that a garbage value is returned (some compilers will return 0).
return expression;
Example:
return x; or return(x);
return x + y or return(x + y);
return rand(x); or return(rand(x));
return 10 * rand(x); or return (10 * rand(x));
We can use as many return statements as we like within a function. However, the
function will stop executing as soon as it encounters the first return. The } that ends a
function also causes the function to return. It is same way as return without any
specified value.
A function declared as void may not contain a return statement that specifies a value.
label:
The label is a word (permissible length is machine dependent) followed by a colon. The
goto statement is formally defined as:
goto label;
‘
‘
‘
label:
target statement
Since, C has a rich set of control statements and allows additional control using break
and continue, there is a little need for goto. The chief concern about the goto is its
tendency to render programs unreachable. Rather, it a convenience, it used wisely, can
be a benefit in a narrow set of programming situation. So the usage of goto is highly
discouraged.
Example:
Void main()
{
int x = 6, y = 12;
if( x == y)
The compiler doesn’t require any formal declaration of the label identifiers.
Consider the following example where we read an integer values and process them
according to the following conditions. If the value we have read is negative, we wish to
print an error message and abandon the loop. If the value read is greater than 100, we
wish to ignore it and continue to the next value in the data. If the value is zero, we
wish to terminate the loop.
Example:
void main()
{
int value;
The continue statement forces the next iteration of the loop to take place, skipping any
code in between. But the break statement forces for termination.
Example 1:
#include<stdio.h>
void main()
{
int x;
An odd number causes continue to execute and the next iteration to occur, by passing
the printf () statement. A continue statement is used within a loop ( i.e for, while, do –
while) to end an iteration in while and do-while loops, a continue statement will cause
control to go directly to the conditional test and then continue the looping process. In
the case of for, first the increment part of the loop is performed, next the conditional
test is executed and finally the loop continues.
Example 2:
main()
{
char ch;
while (1)
{
ch = getchar();
if (ch == EOF)
break;
if (iscntrl (ch))
continue;
else
printf (“\n not a control character”);
}
Break Continue
Used to terminate the loops or to exist Used to transfer the control to the start
loop from a switch. of loop.
The break statement when executed The continue statement when executed
causes immediate termination of loop cause immediate termination of the
containing it. current iteration of the loop.
Just as we can break out of a loop, we can break out of a program by using the
standard library function exit(). This function causes immediate termination of the
entire program, forcing a return to the operation system.
The value of the return_code is returned to the calling process, which is usually the
operation system. Zero is generally used as a return code to indicate normal program
termination.
Void menu(void)
{
char ch;
printf(“B: Breakfast“);
printf(“L: Lunch“);
printf(“D: Dinner”);
printf(“E: Exit”);
printf(“Enter your choice: “);
do
{
ch = getchar();
switch (ch)
{
case ‘B’ :
printf (“time for breakfast”);
break;
case ‘L’ :
printf (“time for lunch”);
break;
case ‘D’ :
printf (“time for dinner”);
break;
case ‘E’ :
exit (0); /* return to operating system */
}
} while (ch != ‘B’ && ch != ‘L’ && ch != ‘D’);
}
2.7. ARRAYS:
An array is a collection of variables of the same type that are referenced by a common
name. In C, all arrays consists of contiguous memory locations. The lowest address
corresponds to the first element, and the highest address to the last element. Arrays
may have from one to several dimensions. A specific element in an array is accessed by
an index.
Type variable-name[size];
Here, type declares the base type of the array, size defines how many elements the
array will hold.
For example, the following declares as integer array named sample that is ten elements
long:
int sample[10];
In C, all arrays have zero as the index of their first element. This declares an integer
array that has ten elements, sample[0] through sample[9]
main()
{
int x [10], t;
for (t=; t<10; t++)
x [t] = t;
}
Example 2:
# include <stdio.h>
main()
{
int i, avg, sample[10];
Two-dimensional arrays:
int num[3][4];
Two dimensional arrays are stored in a row-column matrix where the first index
indicates the row and the second indicates the column. This means that the right most
index changes faster than the leftmost when accessing the elements in the array in the
order in which they are actually stored in memory.
Num[t][I] 0 1 2 3
0 1 2 3 4
1 5 6 7 8
2 9 10 11 12
main ()
{
int t, i, num [3][4];
byte = sizeof 1st Index * sizeof 2nd Index * sizeof (base type)
returns the size of memory (in terms of bytes) required to store an integer object.
4 * 3 * 2 = 24 bytes
This type of array has n size of rows, columns and spaces and so on. The syntax used
for declaration of this type of array is as follows:
Example 1:
Character arrays that hold strings allow a shorthand initialization that takes the form:
Example 2:
2.8. STRINGS:
In C, In order to allow variable length strings the \0 character is used to indicate the
end of a string. A null is specified using ‘\0’ and is zero. Because of the null terminator,
It is necessary to declare character array to be one character longer than the largest
string that they are to hold. For example, to declare an array str that can hold a 10
character string, we write:
char str[11];
this makes room for the null at the end of the string.
It is not necessary to manually add the null onto end of string constants – the compiler
does this automatically.
T U R B O C ‘\0’
The easiest way to input a string from the keyboard is with the gets() library function.
The general form gets() is:
gets(array_name);
To read a string, call gets() with the name of the array, with out any index, as its
arguments. Upon return form gets() the array will hold the string input. The gets()
function will continue to read characters until you enter a carriage return. The header
file used for gets() is stdio.h
Example:
# include <stdio.h>
main()
{
char str[80];
printf (“\nEnter a string:”);
gets (str);
printf (“%s”, str);
}
the carriage return does not become part of the string instead a null terminator is
placed at the end.
Writing strings:
The puts() functions writes its string argument to the screen followed by a newline. Its
prototype is:
puts(string);
It recognizes the same back slash code as printf(), such as “\t” for tab. As puts() can
output a string of characters – It cannot output numbers or do format conversions it
required faster overhead than printf(). Hence, puts() function is often used when it is
important to have highly optimized code.
puts(“hello”);
Array of strings:
To create an array of strings, a two dimensional character array is used with the size of
the left-Index determining the number of strings and the size of the right Index
specifying the maximum length of each string.
char str_array[30][80];
To access an individual string is quite easy: you simply specify only the left Index.
/* to accept lines of text and redisplay them when a blank line is entered */
main()
{
int t, i;
char text [100][80];
for (t=0; t<100; t++)
{
printf (“%d Enter Text: “, t);
gets (text [t]);
if (! text [t][0]) /* quit on blank line */
break;
}
for (i=0; i<t; i++)
printf (“%s\n”, text [i]);
}
As string data type is not present. A string constant is a list of characters enclosed in
double quotes.
Name Function
From to Copies s2 into s1 (the array forming to must be large
strcpy(s1, s2) enough to hold the string content in form)
strcat(s1, s2) Append s2 onto the end of s1
strlen(s1) Returns the length of s1
Returns 0 if s1 and s2 are the same to determine
strcmp(s1, s2) alphabetic order. Less than 0 if s1 < s2; greater than 0 if
s1 > s2
strchr(s1, ch) Return a pointer to the first occurrence of ch in s1
strstr(s1, s2) Return a pointer to the first occurrence of s2 in s1
strrev(s1) Reverses the string s1.
All the string handling functions are prototyped in: # include <string.h>
strcat () and strcopy () both return a copy of their first argument which is the
destination array. Note the order of the arguments is destination array followed by
source array which is sometimes easy to get the wrong around when programming.
The strcmp () function lexically compares the two input strings and returns:
The strcat (), strcmp () and strcpy () copy functions are string restricted version of
their more general counterparts. They perform a similar task but only up to the first n
characters. Note the NULL terminated requirement may get violated when using these
functions.
Example 1:
# include <stdio.h>
# include <string.h>
void main(void)
{
char s1 [80], s2 [80];
gets (s1);
gets (s2);
printf (“lengths: %d %d\n”, strlen (s1), strlen (s2));
if (! Strcmp (s1, s2)) /* strcmp () returns false if the strings are equal, */
*/ use ! to reverse the condition*/
printf(“two strings are equal \n”);
strcat (s1, s2);
printf (“%s\n”, s1);
strcpy (s1,”this is a test\n”);
printf (s1);
if (strchr (“hello”, ’e’)
printf(“e is in hello\n”);
if (strstr (“hi these”, ”hi”);
printf (“found hi”);
}
Output to the screen:
Example 2:
/* to reverse a string * /
# include <stdio.h>
# include <string.h>
main ()
{
char str[80];
int i;
printf (“enter a string: “);
gets (str);
for (i = strlen (str)-1; i > 0; i--)
printf (“%c”, str[i]);
}
We conclude this chapter with a related library #include <ctype.h> which contains
many useful functions to convert and test single characters. The common functions
are prototypes as follows:
Character testing:
The use of these functions is straightforward and we do not give examples here.
Conditional Expressions in C:
b = a * c;
if (b)
printf ("%d\n",b);
else
printf ("b evaluated to zero\n");
The if Statement:
if (expression)
statement;
else
statement;
where, statement may be a single statement, a block, or nothing, and the else
statement is optional. The conditional statement produces a scalar result, ie, an
integer, character or floating point type.
Nested ifs. The ANSI standard specifies that 15 levels of nesting must be supported.
In C, an else statement always refers to the nearest if statement in the same block and
not already associated with an if. For example:
if(i)
{
if(j)
statement 1;
if(k) // this if is associated with
statement 2;
else // this else
if(expression)
statement;
else if(expression)
statement;
else if(expression)
statement;
...
else
statement;
switch (expression)
{
case constant1:
statement sequence;
break;
case constant2:
statement sequence;
break;
...
default:
statement sequence;
}
• A switch can only test for equality, whereas if can evaluate an expression.
• No two case constants can have identical values.
• If character constants are used, they will automatically be converted to integers.
If the break statement is omitted, execution continues on into the next case statement
until either a break or the end of the switch is reached.
initialization is generally an assignment statement used to set the loop control variable.
condition is a relational expression that determines when the loop exits. operation
defines how the loop variable changes each time the loop is repeated.
In for loops, the conditional test is always performed at the top of the loop, which
means that the code inside the loop may not be executed at all if the condition is false,
to begin with as in:
x = 10;
for (y=10; y != x; ++y)
printf (“ %d”, y);
Variation 1 - The Comma Operator. A variant of the for loop is made possible by the
comma operator, as in:
Variation 2 - Missing Pieces of the Loop Definition. An interesting trait of the for
loop is that pieces of the loop definition need not be there. For example, in:
each time the loop repeats, x is tested to see if it equals 123. The loop condition only
becomes false, terminating the loop, when 123 is entered.
Variation 3 - The Infinite Loop. If all of the pieces in the loop definition are missing,
an infinite loop is created. However, the break statement may be used to break out of
the loop, as in:
for(;;)
{
ch = getchar();
if(ch == 'A')
break;
}
Variation 4 - for Loops with No Bodies. The body of the for loop may also be
empty. This improves the efficiency of some code. For example, the following removes
leading spaces from the stream pointed to by str:
Time delay loops are another application of a loop with an empty body, eg:
for (t=0; t<1000; t++);
while (condition)
statement;
The do-while loop tests the condition at the bottom of the loop rather than at the top.
This ensures that the loop will always execute at least once. In the following example,
the loop will read numbers from the keyboard until it finds a number equal to or less
than 100:
do
{
scanf("%d", &num);
} while (num>100);
Jump Statements:
The return statement is used to return from a function. If return has a value associated
with it, that value is returned by the function. If no return value is specified, either zero
or a garbage value will be returned, depending on the compiler. The general form of
the return statement is:
return expression;
The } which ends a function also causes the function to return. A function declared as
void may not contain a return statement that specifies a value
The goto statement requires a label (an identifier followed by a colon), which must be
in the same function as the goto.
The standard library function exit () causes immediate termination of the entire
program. The general form of the exit function is:
The value of return_code is returned to the operating system. Zero is generally used as
a return code to indicate normal program termination. Other arguments are used to
indicate some sort of error.
The continue statement forces the next iteration of the loop, skipping any code in
between. For the for loop, continue causes the conditional test and then the increment
portion of the loop to execute. For the while and do-while loops, program control
passes to the conditional test.
In C, arrays and pointers are closely related; a discussion of one usually refers to the
other.
type var_name[size];
In C, all arrays have zero as the index of their first element. Therefore a declaration of
char p[10]; declares a ten-element array (p[0] through p[9]).
A pointer to the first element in an array may be generated by simply specifying the
array name, without any index. For example, given:
int sample[10];
a pointer to the first element may be generated by simply using the name sample. For
example, the following code fragment assigns p the address of the first element of
sample:
int *p;
int sample[10];
p = sample;
The address of the first element may also be specified using the & operator. For
example, sample and &sample[0] produce the same result. The former is usually used.
function(int x) /* A pointer */
function(int x[10]) /* A sized array */
function(int x[]) /* An unsized array */
Strings:
Although C does not have a string data type, it allows string constants. For example,
"hello there" is a string constant.
Function Description
strcpy (s1, s2) Copies s2 into s1.
strcat (s1, s2) Concatenates s2 to s1.
strlen (s1) Returns the length of s1.
Returns 0 (false) if s1 and s2 are the same.
strcmp (s1, s2) Returns less than 0 if s1<s2
Returns greater than 0 if s1>s2
strchr (s1, ch) Returns pointer to first occurrence ch in s1.
strstr (s1, s2) Returns pointer to first occurrence s2 in s1.
strrev (s1) Reverses the string s1.
Since strcmp () returns false if the strings are equal, it is best to use the ! operator to
reverse the condition if the test is for equality.
Two-Dimensional Arrays:
int d[10][20];
Two-dimensional arrays are stored in a row-column matrix. The first index indicates the
row. The second index indicates the column.
Arrays of Strings:
Arrays of strings are created using a two-dimensional array. The left index determines
the number of strings. Each string is accessed using only the left index.
Multi-Dimensional Arrays:
C allows arrays of more than two dimensions, the exact limit depending on the
individual compiler.
Indexing Pointers:
In C, pointers and arrays are closely related. As previously stated, an array name
without an index is a pointer to the first element. For example, given the array char
Conversely, any pointer variable may be indexed as if it were declared as an array. For
example, in this program fragment:
p = i;
p[5] = 100; /* assignment using index */
(p+5) = 100 /* assignment using pointer arithmetic */
Pointers are sometimes used to access arrays because pointer arithmetic is faster than
array indexing.
For example, the following prints the contents of the specified row for the global array
num:
int num[10][10];
...
void print_row(int j)
{
int *p, t;
p = &num[j][0]; // get address of first element in row j
for(t=0;t<10;++t)
printf("%d ", *(p+t));
}
Array Initialization:
Arrays may be initialized at the time of declaration. The following example initializes a
ten-element integer array:
When the string constant method is used, the compiler automatically supplies the null
terminator.
If unsized arrays are declared, the C compiler automatically creates an array big
enough to hold all the initializes. This is called an unsized array.
Example:
int sgrs[][2] =
{
1, 1,
2, 4,
3, 9
4, 16,
};
# include <stdio.h>
main()
{
int year;
printf("Enter a year:\n");
scanf("%d", &year);
if ( (year % 4) == 0)
printf("%d is a leap year", year);
else
printf("%d is not a leap year\n", year);
}
Output:
RUN2:
# include <stdio.h>
main()
{
long number, tempnum;
printf("Enter an integer:\n");
scanf("%ld", &number);
tempnum = number;
number = number << 2; /*left shift by two bits*/
Output:
Enter an integer: 15
15 x 4 = 60
RUN2:
Enter an integer: 262
262 x 4 = 1048
#include <stdio.h>
#include <math.h>
void main()
{
long int x, n, xpown;
long int power(int x, int n);
Output:
RUN2:
Enter the values of X and N: 4 4
X to the power N ==256
RUN3:
Enter the values of X and N: 5 2
X to the power N = 25
RUN4:
Enter the values of X and N: 10 5
X to the power N = 100000
4. Program to swap the contents of two numbers using bitwise XOR operation.
Don't use either the temporary variable or arithmetic operators.
# include <stdio.h>
Output:
5. Program to find and output all the roots of a quadratic equation, for non-zero
coefficients. In case of errors your program should report suitable error message.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
main()
{
float A, B, C, root1, root2;
float realp, imagp, disc;
clrscr();
printf("Enter the values of A, B and C\n");
scanf("%f %f %f", &A,&B,&C);
Output:
RUN 1
Enter the values of A, B and C: 3 2 1
Imaginary Roots
Root1 = -0.333333 +i 0.471405
Root2 = -0.333333 -i 0.471405
RUN 2
Enter the values of A, B and C: 1 2 1
Roots are real and equal
Root1 = -1.000000
Root2 = -1.000000
RUN 3
Enter the values of A, B and C: 3 5 2
Roots are real and distinct
Root1 = -0.666667
Root2 = -1.000000
6. Write a C programme to accept a list of data items & find the II largest & II
smallest in it & take average of both & search for that value. Display appropriate
message on successful search.
main ()
{
int i,j,a,n,counter,ave,number[30];
printf ("Enter the value of N\n");
scanf ("%d", &n);
printf ("Enter the numbers \n");
for (i=0; i<n; ++i)
scanf ("%d",&number[i]);
for (i=0; i<n; ++i)
{
for (j=i+1; j<n; ++j)
{
if (number[i] < number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
main ()
{
int i,j,a,n,number[30];
printf ("Enter the value of N\n");
scanf ("%d", &n);
printf ("Enter the numbers \n");
for (i=0; i<n; ++i)
scanf ("%d",&number[i]);
for (i=0; i<n; ++i)
{
for (j=i+1; j<n; ++j)
{
if (number[i] > number[j])
{
a= number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("Number in Asscending order:\n");
for(i=0;i<n;i++)
printf("\t%d\n",number[i]);
}
# include <stdio.h>
main()
{
int num, bnum, dec = 0, base = 1, rem ;
printf("Enter the binary number(1s and 0s)\n");
scanf("%d", &num); /*maximum five digits */
#include <stdio.h>
main()
{
int fib1=0, fib2=1, fib3, limit, count=0;
#include <stdio.h>
main()
{
int num, rev = 0, found = 0, temp, digit;
temp = num;
if(temp == rev )
printf("Number is a palindrome\n");
else
printf("Number is not a palindrome\n");
}
#include <stdio.h>
main()
{
int numb;
printf(" Enter the number\n");
scanf("%d", &numb);
if((numb%2)!=0)
printf(" %d , is an odd number\n", numb);
#include <stdio.h>
main()
{
int a, b, c;
printf(" Enter the values for A,B,C\n");
scanf("%d %d %d", &a, &b, &c);
if( a > b )
{
if ( a > c)
printf(" A is the Largest\n");
else
printf("C is the largest\n");
}
else if ( b > c)
printf(" B is the Largest\n");
else
printf("C is the Largest\n");
}
#include <stdio.h>
main()
{
int fig_code;
float side, base, length, bredth, height, area, radius;
printf("-------------------------\n");
printf(" 1 --> Circle\n");
printf(" 2 --> Rectangle\n");
printf(" 3 --> Triangle\n");
printf(" 4 --> Square\n");
printf("-------------------------\n");
switch(fig_code)
{
case 1:
printf(" Enter the radius\n");
scanf("%f",&radius);
area=3.142*radius*radius;
printf("Area of a circle=%f\n", area);
break;
case 2:
printf(" Enter the bredth and length\n");
scanf("%f %f",&bredth, &length);
area=bredth *length;
printf("Area of a Reactangle=%f\n", area);
break;
case 3:
printf(" Enter the base and height\n");
scanf("%f %f", &base, &height);
area=0.5 *base*height;
printf("Area of a Triangle=%f\n", area);
break;
case 4:
printf(" Enter the side\n");
scanf("%f", &side);
area=side * side;
printf("Area of a Square=%f\n", area);
break;
default:
printf(" Error in figure code\n");
break;
}
#include <stdio.h>
main()
{
int i,fact=1,num;
printf("Enter the number\n");
scanf("%d",&num);
if( num <0)
printf(“Factorial is not there for –ve numbers”);
else if(num==0 || num==1)
fact=1;
else
{
for(i=1;i<=num; i++)
fact *= i;
}
printf(" Factorial of %d =%5d\n", num,fact);
}
15. Program to illustrate for loop without initial and increment/decrement expressions.
#include <stdio.h>
main()
{
int i=0,limit=5;
printf(" Values of I\n");
for( ; i<limit; )
{
i++;
printf("%d\n", i);
}
}
16. Program to accept a string and find the sum of all digits in the string.
#include <stdio.h>
main()
{
char string[80];
int count, nc=0, sum=0;
printf("Enter the string containing both digits and alphabet\n");
scanf("%s", string);
for(count=0; string[count]!='\0'; count++)
{
if((string[count]>='0') && (string[count]<='9'))
{
nc += 1;
sum += (string[count] - '0');
}
}
printf("NO. of Digits in the string= %d\n",nc);
printf("Sum of all digits= %d\n",sum);
#include <stdio.h>
#include <math.h>
#define pi 3.142
main()
{
int i,n,k,sign;
float sum=0,num,den,xdeg,xrad,xsqr,term;
printf("Enter the angle( in degree): \n");
scanf("%f",&xdeg);
printf("Enter the no. of terms: \n");
scanf("%d",&n);
xrad=xdeg * (pi/180.0); /* Degrees to radians*/
xsqr= xrad*xrad;
sign=1; k=2; num=xrad; den=1;
for(i=1;i<=n; i++)
{
term=(num/den)* sign;
sum += term;
sign *= -1;
num *= xsqr;
den *= k*(k+1);
k += 2;
}
printf("Sum of sine series of %d terms =%8.3f\n",n,sum);
}
#include<stdio.h>
#include<math.h>
main()
{
float x, sign, cosx, fact;
int n,x1,i,j;
printf("Enter the number of the terms in a series\n");
scanf("%d", &n);
printf("Enter the value of x(in degrees)\n");
scanf("%f", &x);
x1=x;
x=x*(3.142/180.0); /* Degrees to radians*/
cosx=1;
sign=-1;
for(i=2; i<=n; i=i+2)
{
fact=1;
for(j=1;j<=i;j++)
{
fact=fact*j;
}
cosx=cosx+(pow(x,i)/fact)*sign;
sign=sign*(-1);
}
#include <stdio.h>
main()
{
int num, rev = 0, found = 0, temp, digit;
temp = num;
while(num > 0)
{
digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
printf("Given number =%d\n", temp);
printf("Its reverse is =%d\n", rev);
}
20. Program to accept a decimal number and convert to binary and count the
number of 1's in the binary number.
#include <stdio.h>
main()
{
long num, dnum, bin = 0, base = 1;
int rem, no_of_1s = 0 ;
printf("Enter a decimal integer:\n");
scanf("%ld", &num); /*maximum five digits */
dnum = num;
while( num > 0)
{
rem = num % 2;
if (rem==1) /*To count number of 1s*/
{
no_of_1s++;
}
bin = bin + rem * base;
num = num / 2 ;
base = base * 10;
}
printf("Input number is = %ld\n", dnum);
printf("Its Binary equivalent is =%ld\n", bin);
printf("No. of 1's in the binary number is = %d\n", no_of_1s);
}
RUN2
Enter a decimal integer: 128
Input number is = 128
Its Binary equivalent is=10000000
No. of 1's in the binary number is = 1
#include<conio.h>
#include<string.h>
#include<stdio.h>
void main()
{
int count=0,chars,words=0,lines,i;
char text[1000];
clrscr();
puts("Enter text:");
gets(text);
while (text[count]!='\0')
count++;
chars=count;
for (i=0;i<=count;i++)
{
if ((text[i]==' '&&text[i+1]!=' ')||text[i]=='\0')
words++;
}
lines=chars/80+1;
printf("no. of characters: %d\n", chars);
printf("no. of words: %d\n", words);
printf("no. of lines: %d\n", lines);
getch();
}
22. Program to find the GCD and LCM of two integers output the results along with
the given integers. Use Euclids' algorithm.
#include <stdio.h>
main()
{
int num1, num2, gcd, lcm, remainder, numerator, denominator;
clrscr();
printf("Enter two numbers: \n");
scanf("%d %d", &num1,&num2);
if (num1 > num2)
{
numerator = num1;
denominator = num2;
}
Output:
23. Program to find the sum of odd numbers and sum of even numbers from 1 to
N. Output the computed sums on two different lines with suitable headings.
#include <stdio.h>
main()
{
int i, N, oddsum = 0, evensum = 0;
printf("Enter the value of N: \n");
scanf ("%d", &N);
for (i=1; i <=N; i++)
{
if (i % 2 == 0)
evensum = evensum + i;
else
oddsum = oddsum + i;
}
printf ("Sum of all odd numbers = %d\n", oddsum);
printf ("Sum of all even numbers = %d\n", evensum);
}
Output:
RUN1
Enter the value of N: 10
Sum of all odd numbers = 25
Sum of all even numbers = 30
RUN2
Enter the value of N: 50
Sum of all odd numbers = 625
Sum of all even numbers = 650
#include <stdio.h>
#include <stdlib.h>
main()
{
int num, j, flag;
clrscr();
Output:
RUN 1
Enter a number: 34
34 is not a prime number
RUN 2
Enter a number: 29
29 is a prime number
25. Program to generate and print prime numbers in a given range. Also print the
number of prime numbers.
#include <stdio.h>
#include <math.h>
main()
{
int M, N, i, j, flag, temp, count = 0;
clrscr();
printf("Enter the value of M and N: \n");
scanf("%d %d", &M,&N);
if(N < 2)
{
printf("There are no primes upto %d\n", N);
Output:
26. Write to accept a 1-dimensional array of N elements & split into 2 halves & sort
1st half in ascending order & 2nd into descending order.
#include<stdio.h>
main ()
{
int i,j,a,n,b,number[30];
printf ("Enter the value of N\n");
scanf ("%d", &n);
b = n/2;
printf ("Enter the numbers \n");
for (i=0; i<n; ++i)
scanf ("%d",&number[i]);
for (i=0; i<b; ++i)
# include <stdio.h>
main()
{
int vectx[10];
int i, n, found = 0, pos, element;
printf("Enter how many elements\n");
scanf("%d", &n);
printf("Enter the elements\n");
for(i=0; i<n; i++)
{
scanf("%d", &vectx[i]);
}
printf("Input array elements are\n");
for(i=0; i<n; i++)
{
printf("%d\n", vectx[i]);
}
printf("Enter the element to be deleted\n");
scanf("%d",&element);
for(i=0; i<n; i++)
{
28. Write a "C" program to Interchange the main diagonal elements with the
scondary diagonal elements.
#include<stdio.h>
main ()
{
int i,j,m,n,a;
static int ma[10][10];
printf ("Enetr the order of the matix \n");
scanf ("%dx%d",&m,&n);
if (m==n)
{
printf ("Enter the co-efficients of the matrix\n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
scanf ("%d",&ma[i][j]);
}
}
printf ("The given matrix is \n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
printf (" %d",ma[i][j]);
}
printf ("\n");
}
for (i=0;i<m;++i)
{
a = ma[i][i];
ma[i][i] = ma[i][m-i-1];
#include <stdio.h>
#include <conio.h>
main()
{
int x[10];
int i, j, n, m, temp, key, pos;
clrscr();
printf("Enter how many elements\n");
scanf("%d", &n);
printf("Enter the elements\n");
for(i=0; i<n; i++)
{
scanf("%d", &x[i]);
}
printf("Input array elements are\n");
for(i=0; i<n; i++)
{
printf("%d\n", x[i]);
}
for(i=0; i< n; i++)
{
for(j=i+1; j<n; j++)
{
if (x[i] > x[j])
{
temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
printf("Sorted list is:\n");
for(i=0; i<n; i++)
{
printf("%d\n", x[i]);
}
printf("Enter the element to be inserted\n");
main()
{
float x[10];
int i, n;
float avrg, var, SD, sum=0, sum1=0;
#include<stdio.h>
main ()
{
int i,j,m,n,even=0,odd=0;
static int ma[10][10];
printf ("Enter the order ofthe matrix \n");
scanf ("%d %d",&m,&n);
printf ("Enter the coefficients if matrix \n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
scanf ("%d", &ma[i][j]);
if ((ma[i][j]%2) == 0)
{
++even;
}
else
++odd;
}
}
printf ("The given matrix is\n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
printf (" %d",ma[i][j]);
printf ("\n");
}
printf ("The frequency of odd number occurrence = %d\n",odd);
printf ("The frequency of even number occurrence = %d\n",even);
}
32. Program to sort all rows of matrix in ascending order & all columns in
descending order.
#include <stdio.h>
main ()
{
int i,j,k,a,m,n;
static int ma[10][10],mb[10][10];
printf ("Enter the order of the matrix \n");
scanf ("%d %d", &m,&n);
printf ("Enter co-efficients of the matrix \n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
scanf ("%d",&ma[i][j]);
mb[i][j] = ma[i][j];
}
}
printf ("The given matrix is \n");
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
main()
{
char sentence[100];
int count, ch, i;
clrscr();
printf("Enter a sentence\n");
for(i=0; (sentence[i] = getchar())!='\n'; i++);
count = i;
sentence[count]='\0';
printf("Input sentence is : %s",sentence);
printf("\nResultant sentence is\n");
for(i=0; i < count; i++)
{
ch = islower(sentence[i]) ? toupper(sentence[i]) : tolower(sentence[i]);
putchar(ch);
}
}
34. Program to find the sum of the rows & columns of a matrix.
main ()
{
int i,j,m,n,sum=0;
static int m1[10][10];
printf ("Enter the order of the matrix\n");
scanf ("%d%d", &m,&n);
printf ("Enter the co-efficients of the matrix\n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
scanf ("%d",&m1[i][j]);
}
}
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
sum = sum + m1[i][j] ;
}
printf (" Sum of the %d row is = %d\n",i,sum);
sum = 0;
}
sum=0;
for (j=0;j<n;++j)
{
for (i=0;i<m;++i)
{
sum = sum+m1[i][j];
}
printf ("Sum of the %d column is = %d\n", j,sum);
#include<stdio.h>
main ()
{
int i,j,m,n;
static int ma[10][10];
printf ("Enter the order of the matrix \n");
scanf ("%d %d",&m,&n);
printf ("Enter the coefiicients of the matrix\n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
scanf ("%d",&ma[i][j]);
}
}
printf ("The given matrix is \n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
printf (" %d",ma[i][j]);
}
printf ("\n");
}
printf ("Transpose of matrix is \n");
for (j=0;j<n;++j)
{
for (i=0;i<m;++i)
{
printf (" %d",ma[i][j]);
}
printf ("\n");
}
}
36. Program to accepts two strings and compare them. Finally print whether, both
are equal, or first string is greater than the second or the first string is less than the
second string without using string library.
#include<stdio.h>
#include<conio.h>
void main()
{
int count1=0,count2=0,flag=0,i;
char str1[10],str2[10];
clrscr();
puts("Enter a string:");
gets(str1);
puts("Enter another string:");
/*The string comparison starts with the first character in each string and continues with
subsequent characters until the corresponding characters differ or until the end of the
strings is reached.*/
Output:
RUN2:
Enter a string: Hello
Enter another string: Hello
Both strings are equal
RUN3:
Enter a string: gold
Enter another string: silver
String1 is less than string2
#include <stdio.h>
main()
{
long int ARR[10], OAR[10], EAR[10];
int i,j=0,k=0,n;
printf("Enter the size of array AR:\n");
scanf("%d",&n);
printf("Enter the elements of the array:\n");
for(i=0;i<n;i++)
{
scanf("%ld",&ARR[i]);
fflush(stdin);
}
/*Copy odd and even elemets into their respective arrays*/
for(i=0;i<n;i++)
{
if (ARR[i]%2 == 0)
{
EAR[j] = ARR[i];
j++;
}
else
{
OAR[k] = ARR[i];
k++;
}
}
printf("The elements of OAR are:\n");
for(i=0;i<j;i++)
{
printf("%ld\n",OAR[i]);
}
Output:
#include<stdio.h>
#include<conio.h>
void main()
{
int count1=0,count2=0,i,j,flag;
char str[80],search[10];
clrscr();
puts("Enter a string:");
gets(str);
puts("Enter search substring:");
gets (search);
while (str[count1]!='\0')
count1++;
while (search[count2]!='\0')
count2++;
for(i=0;i<=count1-count2;i++)
{
for(j=i;j<i+count2;j++)
{
flag=1;
if (str[j]!=search[j-i])
{
flag=0;
break;
}
}
if (flag==1)
break;
}
if (flag==1)
puts("SEARCH SUCCESSFUL!");
else
puts("SEARCH UNSUCCESSFUL!");
getch();
}
39. Program to accept a string and find the number of times the word 'the' appears
in it.
#include<stdio.h>
#include<conio.h>
void main()
{
int count=0,i,times=0,t,h,e,space;
Output:
40. Program to find the length of a string without using the built-in function, also
check whether it is a palindrome or not.
#include <stdio.h>
#include <string.h>
main()
{
char string[25], revString[25]={'\0'};
int i,length = 0, flag = 0;
clrscr();
fflush(stdin);
printf("Enter a string\n");
gets(string);
for (i=0; string[i] != '\0'; i++) /*keep going through each */
{ /*character of the string */
length++; /*till its end */
}
printf("The length of the string: \'%s\' = %d\n", string, length);
Output:
RUN2:
Enter a string: good
The length of the string 'good' = 4
good is not a palindrome
41. Program to accept two strings and concatenate them i.e. The second string is
appended to the end of the first string.
#include <stdio.h>
#include <string.h>
main()
{
char string1[20], string2[20];
int i,j,pos;
strset(string1, '\0'); /*set all occurrences in two strings to NULL*/
strset(string2,'\0');
printf("Enter the first string:");
gets(string1);
fflush(stdin);
printf("Enter the second string:");
gets(string2);
printf("First string = %s\n", string1);
printf("Second string = %s\n", string2);
/*To concate the second stribg to the end of the string
travserse the first to its end and attach the second string*/
for (i=0; string1[i] != '\0'; i++)
{
; /*null statement: simply trvsering the string1*/
}
pos = i;
for (i=pos,j=0; string2[j]!='\0'; i++)
{
string1[i] = string2[j++];
}
string1[i]='\0'; /*set the last character of string1 to NULL*/
printf("Concatenated string = %s\n", string1);
}
#include <stdio.h>
#include <conio.h>
main()
{
int A[10][10], B[10][10];
int i, j, R1, C1, R2, C2, flag =1;
printf("Enter the order of the matrix A\n");
scanf("%d %d", &R1, &C1);
printf("Enter the order of the matrix B\n");
scanf("%d %d", &R2,&C2);
printf("Enter the elements of matrix A\n");
for(i=0; i<R1; i++)
{
for(j=0; j<C1; j++)
{
scanf("%d",&A[i][j]);
}
}
printf("Enter the elements of matrix B\n");
for(i=0; i<R2; i++)
{
for(j=0; j<C2; j++)
{
scanf("%d",&B[i][j]);
}
}
printf("MATRIX A is\n");
for(i=0; i<R1; i++)
{
for(j=0; j<C1; j++)
{
printf("%3d",A[i][j]);
}
printf("\n");
}
printf("MATRIX B is\n");
for(i=0; i<R2; i++)
{
for(j=0; j<C2; j++)
{
printf("%3d",B[i][j]);
}
printf("\n");
43. Program to illustrate how user authentication is made before allowing the user
to access the secured resources. It asks for the user name and then the password. The
password that you enter will not be displayed, instead that character is replaced by '*'.
#include <stdio.h>
void main()
{
char pasword[10],usrname[10], ch;
int i;
clrscr();
printf("Enter User name: ");
gets(usrname);
printf("Enter the password <any 8 characters>: ");
for(i=0;i<8;i++)
{
ch = getch();
pasword[i] = ch;
ch = '*' ;
printf("%c",ch);
}
pasword[i] = '\0';
printf("\n\n\nYour password is :");
for(i=0;i<8;i++)
{
printf("%c",pasword[i]);
}
}
# include <stdio.h>
main()
{
char string[50];
int i, length = 0;
printf("Enter a string\n");
gets(string);
for (i=0; string[i] != '\0'; i++) /*keep going through each */
{ /*character of the string */
length++; /*till its end */
}
printf("The length of a string is the number of characters in it\n");
printf("So, the length of %s =%d\n", string, length);
}
Output:
Enter a string
hello
The length of a string is the number of characters in it
So, the length of hello = 5
RUN2
Enter a string
E-Commerce is hot now
The length of a string is the number of characters in it
So, the length of E-Commerce is hot now =21
45. Program to read N integers (zero, +ve and -ve) into an array A and to
a) Find the sum of negative numbers
b) Find the sum of positive numbers and
c) Find the average of all input numbers
#include <stdio.h>
#define MAXSIZE 10
main()
{
int array[MAXSIZE];
int i, N, negsum=0, posum=0, count1=0, count2=0;
float total=0.0, averg;
clrscr();
printf ("Enter the value of N\n");
scanf("%d", &N);
printf("Enter %d numbers (-ve, +ve and zero)\n", N);
for(i=0; i< N ; i++)
{
scanf("%d",&array[i]);
fflush(stdin);
}
printf("Input array elements\n");
Output:
46. Program to sort N numbers in ascending order using Bubble sort and print both
the given and the sorted array with suitable headings.
#include <stdio.h>
#define MAXSIZE 10
main()
{
int array[MAXSIZE];
Output:
Input array is
390
234
111
876
345
#include <stdio.h>
main()
{
int array[10];
int i, j, N, temp, keynum, ascending = 0;
int low,mid,high;
clrscr();
printf("Enter the value of N: \n");
scanf("%d",&N);
printf("Enter the elements one by one\n");
for(i=0; i<N ; i++)
{
scanf("%d",&array[i]);
}
printf("Input array elements\n");
for(i=0; i<N ; i++)
{
printf("%d\n",array[i]);
}
/* Bubble sorting begins */
for(i=0; i< N ; i++)
{
for(j=0; j< (N-i-1) ; j++)
{
if(array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
printf("Sorted array is...\n");
for(i=0; i<N ; i++)
{
printf("%d\n",array[i]);
}
printf("Enter the element to be searched\n");
scanf("%d", &keynum);
/* Binary searching begins */
low=1;
high=N;
do
{
mid= (low + high) / 2;
if ( keynum < array[mid] )
high = mid - 1;
else if ( keynum > array[mid])
low = mid + 1;
} while( keynum!=array[mid] && low <= high); /* End of do- while */
if( keynum == array[mid] )
{
printf("SUCCESSFUL SEARCH\n");
Output:
SUCCESSFUL SEARCH
48. Program read a sentence and count the number of number of vowels and
consonants in the given sentence. Output the results on two lines with suitable
headings.
#include <stdio.h>
main()
{
char sentence[80];
int i, vowels=0, consonants=0, special = 0;
clrscr();
printf("Enter a sentence\n");
gets(sentence);
for(i=0; sentence[i] != '\0'; i++)
{
if((sentence[i] == 'a'||sentence[i] == 'e'||sentence[i] == 'i'||
sentence[i] == 'o'||sentence[i] == 'u') ||(sentence[i] == 'A'||
sentence[i] == 'E'||sentence[i] == 'I'|| sentence[i] == 'O'||
sentence[i] == 'U'))
{
vowels = vowels + 1;
}
else
{
Output:
Enter a sentence
Good Morning
No. of vowels in Good Morning = 4
No. of consonants in Good Morning = 7
#include<stdio.h>
#include<string.h>
#include<conio.h>
struct tag
{
char name[10];
int rno;
};
node s[5];
sort(int no)
{
int i,j;
node temp;
for(i=0;i<no-1;i++)
for(j=i+1;j<no;j++)
if(strcmp(s[i].name,s[j].name)>0)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
main()
{
int no,i;
clrscr();
fflush(stdin);
printf("Enter The Number Of Students:");
scanf("%d",&no);
#include <stdio.h>
#include <conio.h>
main()
{
union number
{
int n1;
float n2;
};
union number x;
clrscr() ;
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("Value of n1 =%d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%d", &x.n2);
printf("Value of n2 = %d\n",x.n2);
}
#include<stdio.h>
#include<conio.h>
void main()
{ struct date
{
int day;
int month;
int year;
};
struct details
{
char name[20];
#include <stdio.h>
main()
{
void readmatA();
void printmatA();
void readmatB();
void printmatB();
void sum();
void sum()
{
for(i=0; i<R1; i++)
{
for(j=0; j<C2; j++)
{
sumat[i][j] = A[i][j] + B[i][j];
}
}
printf("Sum matrix is\n");
for(i=0; i<R1; i++)
{
for(j=0; j<C2; j++)
{
printf("%3d",sumat[i][j]) ;
}
printf("\n");
}
return;
}
void diff()
{
for(i=0; i<R1; i++)
{
for(j=0; j<C2; j++)
{
diffmat[i][j] = A[i][j] - B[i][j];
}
}
printf("Difference matrix is\n");
for(i=0; i<R1; i++)
{
for(j=0; j<C2; j++)
{
printf("%3d",diffmat[i][j]);
}
printf("\n");
}
return;
}
#include <stdio.h>
main()
{
int arr[10][10];
int i, j, row, col, rowsum, colsum,sumall=0;
clrscr();
Output:
Input matrix is
1 2 3
4 5 6
7 8 9
Sum of row 1 = 6
Sum of row 2 = 15
Sum of row 3 = 24
Sum of column 1 = 12
Sum of column 2 = 15
Sum of column 3 = 18
Sum of all elements of matrix = 45
54. Program to find the sum of all elements of an array using pointers.
#include <stdio.h>
main()
{
static int array[5]={ 200,400,600,800,1000 };
int addnum(int *ptr); /* function prototype */
int sum;
sum = addnum(array);
printf(" Sum of all array elements=%d\n", sum);
#include <stdio.h>
main()
{
float x[10];
int i,n;
float swap34(float *ptr1, float *ptr2 ); /* Function Declaration */
printf(" How many Elements...\n");
scanf("%d", &n);
printf(" Enter Elements one by one\n");
for(i=0;i<n;i++)
scanf("%f",x+i);
swap34(x+2, x+3); /* Interchanging 3rd element by 4th
*/
printf(" Resultant Array...\n");
for(i=0;i<n;i++)
printf("X[%d]=%f\n",i,x[i]);
}
56. Program to find the sum of two 1-D arrays using Dynamic Memory Allocation.
#include <stdio.h>
#include <malloc.h>
main()
{
int i,n,sum;
int *a,*b,*c;
printf(" How many Elements in each array...\n");
scanf("%d", &n);
a=(int *) malloc(sizeof(n*(int));
b=(int *) malloc(sizeof(n*(int));
c=(int *) malloc(sizeof(n*(int));
printf(" Enter Elements of First List\n");
for(i=0;i<n;i++)
for(i=0;i<n;i++)
c+i=(a+i) +( b+i);
printf(" Resultant List is\n");
for(i=0;i<n;i++)
printf("C[%d]=%f\n",i,c[i]);
}
Storage classes are used to define the scope (visibility) and life-time of variables
and/or functions. Every variable and function in C has two attributes: type and storage
class. There are four storage classes:
• auto
• static
• extern or global and
• register
Declarations of variables within blocks are implicitly of storage class automatic. The
key-word auto can be used to explicitly specify the storage class. An example is:
auto int a, b, c;
auto float f;
Because the storage class is auto by default, the key-word auto is seldom used.
When a block is entered, the system allocates memory for the automatic variables.
With in that block, these variables are defined and are considered “local” to the block.
When the block is exited, the system releases the memory that was set aside for the
automatic variables. Thus, the values of these variables are lost. If the block is
reentered, the system once again allocates memory, but previous values are unknown.
The body of a function definition constitutes a block if it contains declarations. If it
does, then each invocation of the function set up a new environment.
It allows a local variable to retain its previous value when the block is reentered. This is
in contrast to automatic variables, which lose their value upon block exit and must be
reinitialized. The static variables hold their values throughout the execution of the
program. As an example of the value-retention use of static, the outline of a function
that behaves differently depending on how many times it has been called is:
The first time the function is invoked, the variable cnt is initialized to zero. On function
exit, the value of cnt is preserved in memory. Whenever the function is invoked again,
cnt is not reinitialized. Instead, it retains its previous value from the last time the
function was called. The declaration of cnt as a static int inside of fun () keeps it private
of fun (). If it was declared outside of the function, then other functions could access it,
too.
External static variables are declared outside of all functions including the main()
function. They are global variables but are declared with the keyword static. The
external static variables cannot be used across multi-file program.
A static variable is stored at a fixed memory location in the computer, and is created
and initialised once when the program is first started. Such a variable maintains its
value between calls to the block (a function, or compound statement) in which it is
defined. When a static variable is not initialized, it takes a value of zero.
One method of transmitting information across blocks and functions is to use external
variables. When a variable is declared outside a function, storage is permanently
assigned to it, and its storage class is extern. Such a variable is considered to be global
to all functions declared after it, and upon exit from the block or function, the external
variable remains in existence. The following program illustrates this:
# include <stdio.h>
extern int a = 1, b = 2, c = 3;
The extern variables cannot be initialised in other functions whereas we can use for
assignment.
This use of extern will cause some traditional C compilers to complain. In ANSI C, this
use is allowed but not required. Variables defined outside a function have external
storage class, even if the keyword extern is not used. Such variables cannot have auto
or register storage class.
The keyword extern is used to tell the compiler to “look for it else where, either in this
file or in some other file”. Let us rewrite the last program to illustrate a typical use of
the keyword extern:
In file file1.c
#include <stdio.h>
# include “file2.c”
In file file2.c
Output:
The two files can be compiled separately. The use of extern in the second file tells the
compiler that the variable a will be defined elsewhere, either in this file or in some
other. The ability to compile files separately is important when writing large programs.
External variables never disappear. Because they exist throughout the execution life of
the program, they can be used to transmit values across functions. They may,
however, be hidden if the identifier is redefined.
This is like `auto' except that it asks the compiler to store the variable in one of the
CPU's fast internal registers. In practice, it is usually best not to use the `register' type
since compilers are now so smart that they can do a better job of deciding which
variables to place in fast storage than you can.
The use of storage class register is an attempt to improve execution speed. When
speed is a concern, the programmer may choose a few variables that are most
frequently accessed and declare them to be of storage class register. Common
candidates for such treatment include loop variables and function parameters. The
keyword register is used to declare these variables.
Examples:
1) register int x;
2) register int counter;
The type qualifiers const and volatile restrict or qualify the way an identifier of a given
type can be used.
Variables can be qualified as ‘const’ to indicate that they are really constants, that can
be initialised, but not altered. The declaration is:
const int k = 5;
As the type of k has been qualified by const, we can initialise k, but thereafter k cannot
be assigned to, incremented, decremented or otherwise modified.
Variables can also be termed ‘volatile’ to indicate that their value may change
unexpectedly during the execution of the program. The declaration is:
The extern means look for it elsewhere, either in this file or in some other file. The
qualifier volatile indicates that the object may be acted on by the hardware. Because
const is also a qualifier, the object may not be assigned to, incremented, or
decremented within the program. The hardware can change the clock, but the code
cannot.
3.3. FUNCTIONS:
Functions are a group of statements that have been given a name. This allows you to
break your program down into manageable pieces and reuse your code.
1. Function makes the lengthy and complex program easy and in short forms.
It means large program can be sub-divided into self-contained and
convenient small modules having unique name.
3. By using function, memory space can be properly utilized. Also less memory
is required to run program if function is used.
4. They also allow more than one person to work on one program.
5. Function increases the execution speed of the program and makes the
programming simple.
8. Debugging (removing error) becomes very easier and fast using the function
sub-programming.
11. User can build a customized library of different functions used in daily
routine having specific goal and link with the main program similar to the
library functions.
The functions are classified into standard functions and user-defined functions.
The standard functions are also called library functions or built in functions. All
standard functions, such as sqrt(), abs(), log(), sin(), pow() etc. are provided in the
library of functions. These are selective.
You can write as many functions as you like in a program as long as there is only one
main (). As long as these functions are saved in the same file, you do not need to
include a header file. They will be found automatically by the compiler.
• Calling them,
• Defining them and
• Declaring them (prototypes).
When you wish to use a function, you can "call" it by name. Control is sent to the block
of code with that name. Any values that the function needs to perform its job are listed
in the parentheses that immediately follow the name are called arguments. The
computer will retrieve the values held by the variables and hand them off to the
function for its use. The number of arguments (or values) must match the variables in
the definition by type and number. A semicolon must be present, when the function is
called within the main() function.
Defining a function means writing an actual code for the function which does a specific
and identifiable task. Suppose you are defining a function which computes the square
of a given number. Then you have to write a set of instructions to do this.
type_specifier specifies the type of value that the function's return statement returns.
If nothing is returned to the calling function, then data type is void.
return is a keyword used to send the output of the function, back to the calling
function. It is a means of communication from the called function to the calling
All the statements placed between the left brace and the corresponding right brace
constitute the body of a function.
int m ai n()
{
int x = 5, y = 1 0;
float a = 0, b = 2;
stat e m e nts
Re t ur n e d a = d oc alc ( x, y, b); f u nc t i o n c a l l ( i nv oc at i o n)
va lu e
a s s ig ne d t o 5 10 2
a v ar i a b l e s r e p l ac e d w it h c urr e nt v a l u e s
stat e m e nts
r et u r n 0;
}
v a l u e s s e nt t o n e w
v ar i a b l e s a s i n it i a l v a l u e s
{
stat e m e nts
r et u r n ( n u m); v a l u e i s r et ur n e d t o t h e f u nc t i o n c a l l
Any values that the function receives are called parameters. It is easy to confuse
arguments and parameters. The values are called arguments in the statement that calls
the function but become parameters in the header of the function definition. A
semicolon does not follow the function header.
Example:
This program accepts two integers and computes their sum via function addnums().
# include <stdio.h>
int addnums (int val1, int val2) /* Function definition to add two numbers */
{
int sum;
sum=val1 + val2;
return (sum);
}
Output:
In the above example, n1 and n2 are two input values. These are passed to the
function addnums(). In function definition, the copies of n1 and n2 are obtained,
namely val1 and val2. After, the required computations are made in the function, the
control returns to the calling function along with the value computed. In the above
example, the main program receives the value of 46. This is then assigned to the
variable result. Finally, the value of the result is displayed.
A function may return int, float, char or double type data to the main (). However,
there is a restriction is returning arrays. Whenever an array is to be returned, the
return statement is not required. If the return value is not an int then explicitly the
data type of the return value should be specified.
There is another reason for the function declaration. Functions may be written before or
after the main(). If the functions are written before the main() then function
declaration is not required. But, the functions which are written after the main() require
function declaration. Function declaration informs the compiler, about the functions
which are declared after the main().
A prototype may be created by copying the function header and pasting it above the
main() definition and below the preprocessor directives (# include). A semicolon must
follow a function prototype. The variable names do not need to be included in the
prototype. If you include them, the compiler will ignore them.
Arguments and parameters are the variables used in a program and a function.
Variables used in the calling function are called arguments. These are written within the
parentheses followed by the name of the function. They are also called actual
parameters, as they are accepted in the main program (or calling function).
Variables used in the function definition (called function) are called parameters. They
are also referred to as formal parameters, because they are not the accepted values.
They receive values from the calling function. Parameters must be written within the
parentheses followed by the name of the function, in the function definition.
A method of information interchange between the calling function and called function is
known as parameter passing. There are two methods of parameter passing:
1. Call by value
2. Call by reference
The call-by-value method copies the value of an argument into the formal parameter of
the function. Therefore, changes made by the function to the parameters have no
effect on the variables used to call it.
Example:
# include <stdio.h>
main ()
{
int x, y;
x = 10;
y = 20;
swap (x, y); /* values passed */
}
temp = a;
a = b;
b = temp;
printf (“%d %d\n”, a, b);
}
The call by reference method copies the address of an argument into the formal
parameter. Inside the function, this address is used to access the argument used in the
call. In this way, changes made to the parameter affect the variable used in the call to
the function.
Example:
# include <stdio.h>
main ()
{
int x, y;
x = 10;
y = 20;
swap (&x, &y); /* addresses passed */
printf (“%d %d\n”, x, y);
}
temp = *a;
*a = *b;
*b = temp;
}
We have some other type of functions where the arguments and return value may be
present or absent. Such functions can be categorized into:
Here, the called functions does not receive any data from the calling function and, it
does not return any data back to the calling function. Hence, there is no data transfer
between the calling function and the called function.
Example:
This program illustrates the function with no arguments and no return value.
# include <stdio.h>
void read_name ();
main ()
{
read_name ();
}
void read_value () /*no return value */
{
char name [10];
printf (“Enter your name: ”);
scanf (“%s”, name);
printf (“\nYour name is %s: ”, name);
}
Output:
Here, the called function receives the data from the calling function. The arguments
and parameters should match in number, data type and order. But, the called function
does not return and value back to the calling function. Instead, it prints the data in its
scope only. It is one-way data communication between the calling function and the
called function.
Example:
This program illustrates the function with arguments but has no return value.
#include <stdio.h>
main()
{
int x, y;
printf (“Enter the values of x and y: ”);
scanf (“%d %d”, &x, &y);
maximum (x, y);
}
Output:
Here, the called function does not receive any data from the calling function. It
manages with its local data to carry out the specified task. However, after the specified
processing the called function returns the computed data to the calling function. It is
also a one-way data communication between the calling function and the called
function.
Example:
This program illustrates the function with no arguments but has a return value.
#include <stdio.h>
main ()
{
float sum;
sum = total ();
printf (“Sum = %f\n”, sum);
}
float total ()
{
float x, y;
x = 20.0;
y = 10.0;
return (x + y);
}
Output:
Sum = 30.000000
When a function has arguments it receives data from the calling function and does
some process and then returns the result to the called function. In this way the main()
function will have control over the function.
#include <stdio.h>
int sum (int x); /* function prototype*/
void main ()
{
int n;
printf (“Enter the limit: ”);
scanf (“%d”, &n);
printf (“sum of first %d natural numbers is: %d”, n, sum(n));
}
int sum(int x)
{
int i, result = 0
for (i=1; i <= x; i++)
result += i;
return (result);
}
Output:
The main() is the calling function which calls the function sum(). The function sum()
receives a single argument. Note that the called function (i.e., sum ()) receives its data
from the calling function (i.e., main()). The return statement is employed in this
function to return the sum of the n natural numbers entered from the standard input
device and the result is displayed from the main() function to the standard output
device. Note that int is used before the function name sum() instead of void since it
returns the value of type int to the called function.
• The function name in the function call and the function definition must be
same.
• The type, number, and sequence of actual and formal arguments must be
same.
We have seen programs using functions called only from the main() function. But there
are situations, where functions other than main() can call any other function(s) used in
the program. This process is referred as nested functions.
Example:
#include <stdio.h>
void func1();
void func2();
void main()
{
printf (“\n Inside main function”);
func1();
printf (“\n Again inside main function”);
}
void func1()
{
printf (“\n Inside function 1”);
func2();
printf (“\n Again inside function 1”);
}
void func2()
{
printf (“\n Inside function 2”);
}
Output:
Uses two functions func1() and func2() other than the main() function. The main()
function calls the function func1() and the function func1() calls the function func2().
Both the calling function and called function are using their own variables. The
existence of these variables is restricted to the calling function or to the called
functions. This is known as scope of the variables. Based on this scope the variables
can be classified into:
1. Local variables
2. Global variables
Variables whose existence is known only to the main program or functions are called
local variables. On the other hand, variables whose existence is known to both main()
as well as other functions are called global variables. Local variables are declared within
the main program or a function. But, the global variables are declared outside the
main() and other functions.
The following program illustrates the concept of local and global variables:
Example:
#include <stdio.h>
main()
{
int j; /* local variable declaration */
printf (“i = %d\n”, i);
j = value (i);
printf (“j = %d\n”, j);
}
int value (int i) /* function to compute value */
{
int k; /* local variable declaration */
k = i +10
return (k);
}
Output:
i = 10
j = 20
An array name represents the address of the first element in that array. So, arrays are
passed to functions as pointers (a pointer is a variable, which holds the address of
other variables).
When an array is passed to a function, only the address is passed, not the entire array.
When a function is called with just the array name, a pointer to the array is passed. In
C, an array name without an index is a pointer to the first element. This means that the
parameter declaration must be of a compatible pointer type. There are three ways to
declare a parameter which, is to receive an array pointer:
Example:
As an unsized array:
As a pointer:
which, is allowed because any pointer may be indexed with [] as if it were an array.
An array element used as an argument is treated like any other simple variable, as
shown in the example below:
Example:
main ()
{
...
display (t [a]);
...
}
The return causes an immediate exit from a function to the point from where the
function is called. It may also be used to return one value per call. All functions, except
those of type void, return a value. If no return statement is present, most compilers
will cause a 0 to be returned. The return statement can be any one of the types as
shown below:
1. return;
2. return ();
3. return (constant);
4. return (variable);
5. return (expression);
6. return (conditional expression);
7. return (function);
The first and second return statements, does not return any value and are just equal to
the closing brace the function. If the function reaches the end without using a return
statement, the control is simply transferred back to the calling portion of the program
without returning any value. The presence of empty return statement is recommended
in such situations.
if (x <= 10)
return (1);
The fourth return statement returns a variable to the calling function. For example:
if (x <= 10)
return (x);
The fifth return statement returns a value depending upon the expression specified
inside the parenthesis. For example:
return (a + b * c);
The sixth return statement returns a value depending upon the result of the conditional
expression specified inside the parenthesis. For example:
The parenthesis used around the expression or value used in a return statement is
optional.
C allows the programmer to create custom data types in five different ways. These are:
• Types created with typedef, which defines a new name for an existing type.
• The union, which enables the same piece of memory to be defined as two or more
types of variables.
• The bit-field, a variation of the structure, which allows easy access to the bits of a
word.
3.11.1. Structures:
A structure is a user defined data type. Using a structure we have the ability to define a
new type of data considerably more complex than the types we have been using.
In the following, the C keyword struct tells the compiler that a structure template is
being defined:
struct addr
{
char name[30];
char street[40];
int postalcode;
};
In this example, addr is known as the structure tag. A structure definition is actually a
statement hence it is terminated by a semicolon.
Variables may also be declared as the structure is defined. This can be done as follows:
struct addr
{
char name[30];
char street[40];
int postalcode;
} addr_info, binfo, cinfo;
If only one variable is needed, the structure tag is not needed, for example:
struct
{
char name[30];
char street[40];
int postalcode;
Structure Assignments:
binfo = addr_info;
Assuming the previously defined structure addr, the following declares addr_pointer as
a pointer to data of that type:
Individual elements of a structure are referenced using the dot operator. The pointer to
a structure member operator -> is used to access a member of a structure using a
pointer variable.
Individual elements of a structure are referenced using the dot operator, for example:
Example:
# include <stdio.h>
# include <string.h>
struct
{
char name[15]; /* childs name */
int age; /* childs age */
int grade; /* childs grade in school */
} boy, girl;
int main()
{
strcpy (boy.name, “Herbert”);
boy.age = 15;
boy.grade = 75;
girl.age = boy.age - 1; /* she is one year younger */
girl.grade = 82;
strcpy (girl.name, “Fousett”);
printf ("%s is %d years old and got a grade of %d\n",
girl.name, girl.age, girl.grade);
printf ("%s is %d years old and got a grade of %d\n",
boy.name, boy.age, boy.grade);
return 0;
}
To access the elements of a structure using a pointer, the -> operator is used:
where, ptr has been declared as a pointer to the type of structure and assigned the
address of a variable of that type, and postalcode is a structure element within that
variable.
(*ptr). postalcode
The parenthesis is necessary because the structure member operator “. “ takes higher
precedence than does the indirection operator.
Example:
#include <stdio.h>
struct
{
char initial;
int age;
int grade;
} kids[12], *point, extra;
int main()
{
int index;
return 0;
}
Output:
Arrays of Structures:
Example:
#include <stdio.h>
struct
{
char initial;
int age;
int grade;
} kids[12];
int main()
{
int index;
for (index = 0 ; index < 12 ; index++)
{
Output:
Example:
struct fred
{
char x;
int y;
char s[10];
} mike;
If the address of the element is required to be passed, the & operator is placed before
the structure name. In the above example, this would apply except in funct (mike.s);.
#include <string.h>
struct person
{
char name[25];
int age;
char status; /* M = married, S = single */
};
struct alldat
{
int grade;
struct person descrip;
char lunch[25];
};
int main()
{
struct alldat student[53];
struct alldat teacher, sub;
teacher.grade = 94;
teacher.descrip.age = 34;
teacher.descrip.status = 'M';
strcpy(teacher.descrip.name, "Mary Smith");
strcpy(teacher.lunch, "Baloney sandwich");
sub.descrip.age = 87;
sub.descrip.status = 'M';
strcpy(sub.descrip.name, "Old Lady Brown");
sub.grade = 73;
strcpy(sub.lunch, "Yogurt and toast");
student[1].descrip.age = 15;
student[1].descrip.status = 'S';
strcpy(student[1].descrip.name, "Billy Boston");
strcpy(student[1].lunch, "Peanut Butter");
student[1].grade = 77;
student[7].descrip.age = 14;
student[12].grade = 87;
return 0;
}
Arrays Structures
A array is an single entity representing A structure is a single entity
a collection of data items of same data representing a collection of data items
types. of different data types.
Individual entries in an array are called Individual entries in a structure are
elements. called members.
An array declaration reserves enough The structure definition reserves
memory space for its elements. enough memory space for its members.
There is no keyword to represent arrays The keyword struct tells us that we can
but the square braces [] preceding the dealing with structures.
variable name tells us that we are
dealing with arrays.
Initialization of elements can be done Initialization of members can be done
during array declaration. only during structure definition.
The members of a structure are not
The elements of an array are stored in
stored in sequence of memory
sequence of memory locations.
locations.
The array elements are accessed by its The members of a structure are
followed by the square braces [] within accessed by the dot operator.
which the index is placed.
Its general format is data type variable Its general format is:
name [size]; struct <struct name>
{
data_type structure member 1;
data_type structure member 2;
.
.
.
data_type structure member N;
} structure variable;
Example: Example:
int sum [100]; struct student
{
char studname [25];
int rollno;
} stud1;
3.11.2. typedef:
typedef allows a new data type to be explicitly defined. Note that it does not actually
create a new data class, but simply defines a new name for an existing type. This
process helps in making machine-dependent code more portable, since only the
typedef statements need be changed. It can also aid in self-documenting a program by
allowing the use of more descriptive names for the standard data types.
Where age symbolizes int, average symbolizes float and string symbolizes char.
They can be later used to declare variables as:
Where child and adult are declared as integer variables, mark1 and mark2 are declared
as floating point variables and name is declared as character array variable.
The typedef can also be used to define structures. The main advantage of type
definition is that, you can create meaningful data type names for increasing the
readability of the program. They also suggest the purpose of the data type names used
in the program.
3.11.3. Unions:
union tag
{
type variable_name;
type variable_name;
type variable_name;
.
.
} union_variables;
union u_type
{
int i;
char ch;
};
Declaration options are as for structures, i.e, variable names may be placed at the end
of the definition or a separate declaration statement may be used.
A union shares the memory space instead of wasting storage on variables that are not
being used. The compiler allocates a piece of storage that is large enough to hold the
largest type in the union.
union elements are accessed using the same methods used for accessing structure
elements.
The union aids in the production of machine-independent code because the compiler
keeps track of the actual sizes of the variables, which make up the union.
unions are frequently used when type conversions are needed because the data held in
a union can be referred to in different ways.
Example 1:
union exam
{
int roll_no;
char name[15];
int mark1,mark2,mark3;
} u1;
struct exam1
{
int roll_no;
char name[15];
int mark1, mark2, mark3;
} s1;
void main()
{
printf(“The size of union is %d\n”, sizeof(u1));
printf(“The size of structure is %d”, sizeof(s1));
}
Output:
In the above example, union exam has 5 members. The first member is a character
array name having 15 characters (i.e., 15 bytes). The second member is of type int
that requires 2 bytes for their storage. All the other members mark1, mark2, mark3
are of type int which requires 2 bytes for their storage. In the union, all these 5
members are allocated in a common place of memory (i.e., all the members share the
same memory location). As union shares the memory space instead of wasting storage
on variables that are not being used, the compiler allocates a piece of storage that is
large enough to hold the largest type in the union. In the above declaration, the
member name requires, 15 characters, which is the maximum of all members, hence a
total memory space of 15 bytes is allocated. In case of structures, the total memory
space allocated will be 23 (i.e. 15+2+2+2+2) bytes.
Example 2:
#include<stdio.h>
void main()
{
union dec
Output:
Size of union = 4
The value of x = 300
44 1 65461 74
The binary value of 300 is 0000 0001 0010 1100. As per the internal storage
representation first 0010 1100 = 44 is stored then 0000 0010 = 01 is stored.
Example 3:
#include<stdio.h>
#include<string.h>
#include <conio.h>
struct hos
{
char name[10];
char hostelname[20];
};
struct daysch
{
int phonenumber;
char name[10];
char address[40];
int rollno;
};
union student
{
struct hos hostler;
struct daysch dayscholar ;
} stu_data;
void main()
{
int n;
clrscr();
printf("\n MENU ");
printf("\n 1. Hostler \n 2. Day Scholar\n");
printf("\n enter the choice: ");
scanf("%d",&n);
if(n==1)
{
Output:
RUN 1:
MENU
1. Hostler
2. Day Scholar
RUN 2:
MENU
1. Hostler
2. Day Scholar
Structures Unions
Each member in a structure occupies All the members of a union use the
and uses its own memory space same memory space
The keyword struct tells us that we are The keyword union tells us that we are
dealing with structures dealing with unions
All the members of a structure can be Only the first member of an union can
initialized be initialized
More memory space is required since Less memory space is required since all
each member is stored in a separate members are stored int eh same
memory locations memory locations
Its general format is: Its general formula is:
struct <struct Name> union <union Name>
{ {
data_type structure Member1; data_type structure Member1;
data_type structure Member2; data_type structure Member2;
. .
. .
data_type structure Member N; data_type structure Member N;
} structure variable; } union variable;
Example: Example:
struct student union student
{ {
char studname[25]; char studname[25];
int rollno; int rollno;
} stud1; } stud1;
3.11.4. Enumerations:
This creates the user defined type enum day. The keyword enum is followed by the tag
name day. The enumerators are the identifiers sun, mon, . . ., sat. They are constants
of type int. By default the first one 0 and each succeeding one has the next integer
value.
Initialization:
The enumerators can be initialized. Also we can declare variables along with the
template. The following example do so:
clubs has been initialized to 1, diamonds, hearts and spades have the values 2, 3, and
4 respectively. a, b, and c are variables of this type.
Because the enumerator apple has been initialized to 7, pear has value 8. Similarly,
because orange has a value 3, lemon has a value 4. Multiple values are allowed, but
the identifiers themselves must be unique.
Example:
# include <stdio.h>
# include <conio.h>
main()
{
int n;
clrscr ();
printf (“Enter a day number (0 for sunday and so on upto 6):”);
scanf (“%d”,&n);
switch (n)
{
case sun:
printf(“\nSunday“);
break;
case mon:
printf(“\nMonday“);
break;
case tue:
printf(“\nTuesday“);
break;
case wed:
printf(“\nWednesday“);
break;
case thu:
printf(“\nThursday“);
break;
case fri:
printf(“\nFriday“);
break;
case sat:
printf(“\nSaturday“);
break;
}
getch();
}
C has a built-in method for accessing a single bit within a byte. This is useful because:
Tasks involving the manipulation of bits may, of course, be performed using C's bitwise
operators. However, the bit-field provides a means of adding more structure and
efficiency to the coding.
To access bits using bit-fields, C uses a method based on the structure. In fact, a bit-
field is simply a special type of structure element, which defines how long in bits the
field is to be.
struct tag
{
type name1: length;
type name2: length;
type name3: length;
} variable_list;
An Example Application:
Bit-fields are frequently used when analyzing input from a hardware device. For
example, the status port of a serial communications device might return a status byte
like this:
Bit Meaning When Set
0 Change in clear-to-send line.
1 Change in data-set-ready.
2 Trailing edge detected.
3 Change in receive line.
4 Clear-to-send.
5 Data-set-ready.
6 Telephone ringing.
7 Received signal.
The foregoing can be represented in a status byte using the following bit-field
definition/declaration:
Using this bit-field, the following routine would enable a program to determine whether
it can send or receive data:
status = get_port_status;
if(status.cts)
printf("Clear to send");
if(status.dsr)
printf("Data set ready);
Values are assigned to a bit-field using the usual method for assigning values to
structure elements, e.g.:
status.ring = 0;
Variations in Definition:
All bit-fields need not necessarily be named, which allows unused ones to be bypassed.
For example, if, in the above example, access had only been required to cts and dsr,
status_type could have been declared like this:
struct status_type
{
unsigned: 4;
unsigned cts: 1;
unsigned dsr: 1;
} status;
Example:
#include <stdio.h>
union
{
int index;
struct
{
unsigned int x : 1;
unsigned int y : 2;
int main ()
{
for (number.index = 0 ; number.index < 20 ; number.index++)
{
printf ("index = %3d, bits = %3d%3d%3d\n", number.index,
number.bits.z, number.bits.y, number.bits.x);
}
return 0;
}
Output:
index = 0, bits = 0 0 0
index = 1, bits = 0 0 1
index = 2, bits = 0 1 0
index = 3, bits = 0 1 1
index = 4, bits = 0 2 0
index = 5, bits = 0 2 1
index = 6, bits = 0 3 0
index = 7, bits = 0 3 1
index = 8, bits = 1 0 0
index = 9, bits = 1 0 1
index = 10, bits = 1 1 0
index = 11, bits = 1 1 1
index = 12, bits = 1 2 0
index = 13, bits = 1 2 1
index = 14, bits = 1 3 0
index = 15, bits = 1 3 1
index = 16, bits = 2 0 0
index = 17, bits = 2 0 1
index = 18, bits = 2 1 0
index = 19, bits = 2 1 1
struct emp
{
struct addr address;
float pay;
unsigned lay-off: 1; /* lay-off or active */
unsigned hourly: 1; /* hourly pay or wage */
unsigned deducts: 3; /* tax deductions */
}
which demonstrates the use of only one byte to store information which would
otherwise require three bytes.
automatic: declared when entering the block, lost upon leaving the block; the
declarations must be the first thing after the opening brace of the block
static: the variable is kept through the execution of the program, but it can only be
accessed by that block
extern: available to all functions in the file AFTER the declaration; use extern to make
the variable accessible in other files
register: automatic variable which is kept in fast memory; actual rules are machine-
dependent, and compilers can often be more efficient in choosing which variables to
use as registers.
Predefined Functions are functions that are written and stored for use in future
programs. Sometimes groups of these functions are organized by the type of purpose
they perform and stored in header files as function libraries. For this reason, predefined
functions are often referred to as library functions.
The scope of an identifier defines the area in program code where it has meaning.
Identifiers that are defined within a function are local to that function, meaning that
they will not be recognized outside of it. Identifiers that are defined outside of all
functions are global, meaning that they will be recognized within all functions.
Call: The action of one function activating or making use of another functions is
referred to as calling. A function must be declared in the source code ahead of the
statement that calls it.
declaration: specifies the type of the identifier, so that it can subsequently be used.
The function prototype is a declaration and is needed if the function is defined after its
use in the program. The syntax is:
If the return-type is omitted, int is assumed. If there are no argument declarations, use
void, not empty parentheses.
Parameters are values that are passed between functions. The C statement that calls
a function must include the function label followed by a parenthesized list of
parameters that are being passed into the function. These parameters are referred to
as actual parameters because they are the actual values being provided by the
calling function. Actual parameters are often also referred to as arguments.
In the C code where the function is declared, a function header is written to declare the
function identifier and to declare the identifiers, known as formal parameters, that
will be used inside of the function to represent any data being passed into it. Formal
parameters do not have to be identical to the actual parameters used in the calling
statement, but must match in quantity and be compatible in data type.
The scope of an identifier defines the area in program code where it has meaning.
Identifiers that are defined within a function are local to that function, meaning that
they will not be recognized outside of it. Identifiers that are defined outside of all
functions are global, meaning that they will be recognized within all functions.
References (labels) and referencing (use of those labels) involve the manner in
which we use labels to refer to stored data.
Direct referencing is the use of a storage label to refer directly to the contents of a
storage location. Direct referencing is often used in formulas when we want to use a
stored value in the formula. The statement Y = X + 1; refers directly to the contents of
the storage location X. The value stored in X will be added to 1.
Indirect referencing is the use of a storage label in such a way that the contents of
one storage location (see "pointer" below) is used to refer indirectly to the contents of
a different storage location. (See the web page about Pointers and Indirection.) Indirect
referencing is often used to pass data back from a function to its parent when more
than one parameter is involved. The statement *YP = 0; refers indirectly to the
contents of a storage location that is pointed to by an address stored in YP. The
identifier YP must be declared as a "pointer" (see below). The use of the star as an
indirection operator in front of the identifier makes it an indirect reference. This
operator also is often called the dereferencing operator because it prevents direct
reference to the variable.
Address referencing is the use of a storage label to refer to its memory address
rather than its contents. The statement scanf ("%d", &N); passes the address of
storage location N to the scanf function. Had we used the identifier N without the
preceding &, that would have passed the contents of the N storage location to the
function instead of its address. A function can return a value of any type, using the
return statement, The syntax is:
The return statement can occur anywhere in the function, and will immediately end
that function and return control to the function which called it. If there is no return
statement, the function will continue execution until the closing of the function
definition, and return with an undefined value.
A structure is a data type which puts a variety of pieces together into one object. The
syntax is given below:
struct structure-tag-optional
{
member-declarations
structure-names-optional ;
}
typedef: typedef defines a new type, which can simplify the code. Here is the syntax:
typedef struct
{
member-declarations
} TYPE-NAME;
union: With union, different types of values can be stored in the same location at
different times. Space is allocated to accomodate the largest member data type. They
are syntactically identical to structures, The syntax is:
union union-tag-optional
{
member-declarations
} union-names-optional;
union-name. member
enum: The type enum lets one specify a limited set of integer values a variable can
have. For example, flags are very common, and they can be either true or false. The
syntax is:
enum-name variable-name
The values of the enum variable are integers, but the program can be easier to read
when using enum instead of integers. Other common enumerated types are weekdays
and months.
Pointer is a fundamental part of C. If you cannot use pointers properly then you have
basically lost all the power and flexibility that C allows. The secret to C is in its use of
pointers. C uses pointers a lot because:
The unary operator & gives the “address of a variable''. The indirection or
dereference operator * gives the “contents of an object pointed to by a pointer''.
int *pointer;
We must associate a pointer to a particular type. We can't assign the address of a short
int to a long int.
#include <stdio.h>
main()
{
int x = 1, y = 2;
int *ip;
ip = &x;
y = *ip;
*ip = 3;
}
x 1 y 2 ip 100
100 200 1000
y = *ip;
x 1 y 1 ip 100
100 200 1000
*ip = 3;
x 3 y 1 ip 100
100 200 1000
F i g. 4. 1 P o i nt er, V ar i a b l e s a n d M e mo ry
Now the assignments x = 1 and y = 2 obviously load these values into the variables. ip
is declared to be a pointer to an integer and is assigned to the address of x (&x). So
ip gets loaded with the value 100.
Next y gets assigned to the contents of ip. In this example ip currently points to
memory location 100 -- the location of x. So y gets assigned to the values of x -- which
is 1. Finally, we can assign a value 3 to the contents of a pointer (*ip).
IMPORTANT: When a pointer is declared it does not point anywhere. You must set it
to point somewhere before you use it. So,
int *ip;
*ip = 100;
int *ip;
int x;
ip = &x;
*ip = 100;
++ip;
char m = ‘j’;
char *ch_ptr = &m;
float x = 20.55;
float *flp, *flq;
flp = &x;
*flp = *flp + 10;
++*flp;
(*flp)++;
flq = flp;
The reason we associate a pointer to a data type is that it knows how many bytes the
data is stored in. When we increment a pointer we increase the pointer by one “block “
of memory.
So, for a character pointer ++ch_ptr adds 1 byte to the address. For an integer or float
++ip or ++flp adds 2 bytes and 4 bytes respectively to the address.
#include <stdio.h>
Output:
m = 1, n = 1, k = 1
msg = “Hello World”
Note the very important point that the name of an array (`msg' in the above example),
if used without an index, is considered to be a pointer to the first element of the array.
Example:
#include <stdio.h>
Output:
Hello World
Hello World
Hello World
Hello World
There is a close association between pointers and arrays. Let us consider the following
statements:
The array initialization statement is familiar to us. The second statement, array name x
is the starting address of the array. Let we take a sample memory map as shown in
figure 4.2.:
From the figure 4.2 we can see that the starting address of the array is 1000. When x
is an array, it also represents an address and so there is no need to use the (&) symbol
before x. We can write int *p = x in place of writing int *p = &x[0].
The content of p is 1000 (see the memory map given below). To access the value in
x[0] by using pointers, the indirection operator * with its pointer variable p by the
notation *p can be used.
M e mo ry
1000 11 x[ 0]
1002 22 x[ 1]
1004 33 x[ 2]
1006 44 x[ 3]
1008 55 x[ 4]
1010
F i g ur e 4. 2. M e mo ry ma p - Arr ay s
The increment operator ++ helps you to increment the value of the pointer variable by
the size of the data type it points to. Therefore, the expression p++ will increment p by
2 bytes (as p points to an integer) and new value in p will be 1000 + 2 = 1002, now *p
will get you 22 which is x[1].
*p++;
*(p++);
(*p)++;
How would they be evaluated when the integers 10 & 20 are stored at addresses 1000
and 1002 respectively with p set to 1000.
p++ : The increment ++ operator has a higher priority than the indirection operator
* . Therefore p is increment first. The new value in p is then 1002 and the
content at this address is 20.
Example:
#include <stdio.h>
main()
{
int x[5] = {11, 22, 33, 44, 55};
int *p = x, i; /* p=&x[0] = address of the first element
*/
for (i = 0; i < 5; i++)
{
printf (“\n x[%d] = %d”, i, *p); /* increment the address*/
p++;
}
}
Output:
x [0] = 11
x [1] = 22
x [2] = 33
x [3] = 44
x [4] = 55
The meanings of the expressions p, p+1, p+2, p+3, p+4 and the expressions *p,
*(p+1), *(p+2), *(p+3), *(p+4) are as follows:
For the first statement, the compiler allocates 20 bytes of memory and stores in the
first six bytes the char values as shown below:
V a lu e ‘O’ ‘ N’ ‘ I’ ‘ D’ ‘ A’ ‘\ 0’
The statement:
Assigns the address 1000 to p. Now, we will write a program to find the length of the
string tv and print the string in reverse order using pointer notation.
Example:
#include <stdio.h>
main()
{
int n, i;
char tv[20] = “ONIDA”; /* p = 1000 */
char *p = tv, *q; /* p = &tv[0], q is a pointer */
q = p;
while (*p != ‘\0’) /* content at address of p is not null character */
p++;
n = p - q; /* length of the string */
--p; /* make p point to the last character A in the string */
printf (“\nLength of the string is %d”, n);
printf (“\nString in reverse order: \n”);
for (i=0; i<n; i++)
{
putchar (*p);
p--;
}
}
Output:
You have learnt so far that pointers can be set to point to an int, float, char, arrays and
strings. Now, we will learn how to set pointers to structures. Consider the structure
definition.
struct student
{
int rollno;
char name [20];
};
struct student s;
struct student *ps = &s;
The symbol is called arrow operator and is made up of a minus sign and a greater
than sign. The parentheses around ps are necessary because the member operator (.)
has a higher precedence than the indirection operator (*).
# include <stdio.h>
# include <conio.h>
struct invent
{
char name[20];
int number;
float price;
};
main()
{
float temp;
struct invent product[3], *ps;
int size ;
ps = &product[0];
printf("input product details:");
size = sizeof(product[0]);
printf("\n sizeof(product[0]) = %d",size );
printf("\n product = %u ",product);
printf("\n &product[0] = %u ",&product[0]);
printf("\n &product[1] = %u ",&product[1]);
printf("\n &product[2] = %u ",&product[2]);
printf("\nproduct + 3 = %u\n",(product+3) );
printf("\n Name \t Number \t Price\n");
for (ps=product; ps < product+3; ps++)
{
scanf ("%s %d %f", ps->name, &ps->number, &temp);
ps->price = temp;
}
printf("\n Item Details...\n Name\tNumber\t Price\n");
for (ps=product; ps < product+3; ps++)
printf ("\n%s %d %f", ps->name, ps->number, ps->price);
getch();
}
Output:
sizeof(product[0]) = 26
product = 9478
&product[0] = 9478
&product[1] = 9504
&product[2] = 9530
Item Details…….
n a me n u mb e r pr ic e n a me n u mb e r pr ic e n a me n u mb e r pr ic e
Pointer has deep relationship with function. We can pass pointer to the function and
also addresses can be passed to the function as pointer argument. This can be
represented by two ways as defined below:
This is achieved by call by reference. The call by reference method copies the address
of an argument into the formal parameter. Inside the function, this address is used to
access the argument used in the call. In this way, changes made to the parameter
affect the variable used in the call to the function.
Example:
# include <stdio.h>
main ()
{
int x, y;
x = 10;
y = 20;
swap (&x, &y); /* addresses passed */
printf (“%d %d\n”, x, y);
}
temp = *a;
*a = *b;
*b = temp;
}
A function works like a variable. It is also similar to data type declaration like the other
variable. Pointer to a function variable occurs when you define a function as a pointer.
As function has address location in memory the syntax used to declare pointer to
function is as:
Where, return_type is the data type which may be integer, float or character and
*(fptr) (argument list) is pointer to function. The procedure to illustrate this concept is
as follows:
By using the above example, we say that add() is a simple function. But f1 is pointer
variable which work as pointer to function and third statement the address of the add()
function is assigned to f1 variable which is a memory variable. So, (*f1)(int, int) is a
function pointer linked to the function add.
Example:
/* Program to add and substract two numbers by using the pointer to function. */
#include <stdio.h>
main()
{
f1 = & add;
(*f1) (10, 15);
f1 = & sub;
(*f1) (11, 7);
}
Output:
Sum = 25
Sub = 4
We can have array of pointers since pointers are variables. Array of Pointers will
handle variable length text lines efficiently and conveniently. How can we do this is:
Example:
#include <stdio.h>
void main(void)
{
char *p[5];
int x;
p[0] = "DATA";
p[1] = "LOGIC";
p[2] = "MICROPROCESSOR";
p[3] = "COMPUTER";
p[4] = "DISKETTE";
for (x = 0; x < 5; ++x)
printf("%s\n", p[x]);
}
Output:
DATA
LOGIC
MICROPROCESSOR
COMPUTER
DISKETTE
a[n][m] notation.
When we pass a 2D array to a function we must specify the number of columns -- the
number of rows are irrelevant. The reason for this is pointers again. C needs to know
how many columns in order that it can jump from row to row in memory.
We can do:
or even:
Now lets look at the difference between pointers and arrays. Strings are a common
application of this. Consider:
char *name[10];
char aname[10][20];
The advantage of the latter is that each pointer can point to arrays of different length.
Let us consider (shown in figure 4.3):
a n a me 2 0 e l e me n t s
n a me
n o mo n t h\ 0 0 n o mo n t h\ 0
j a n\ 0
1 j a n\ 0
f e b\ 0
10
2 f e b\ 0
F i g. 4. 3. 2 D Arr ay s a n d Arr ay s of P o i nt er s
The concept of a pointer having the exclusive storage address of another pointer is
called as pointer to pointer. Normally we do not use pointers to pointers very often but
they can exist. The following program demonstrates this:
Example:
#include <stdio.h>
void main(void)
{
int x, *p, **ptp;
x = 454;
p = &x;
ptp = &p;
printf("%d %d\n", *p, **ptp);
}
Output:
454 454
**ptp is declared as a pointer to pointer of type int. This means that ptp handles the
address of another pointer p. Variable x is assigned a value of 454, then its address is
assigned to pointer p. Next, the address of pointer p is assigned to pointer to a pointer
ptp. **ptp accesses the value of x.
Suppose we have a function malloc() which tries to allocate memory dynamically (at
run time) and returns a pointer to block of memory requested if successful or a NULL
pointer
otherwise.
There is a mistake above. That is, * before p in the statement 1. The correct code
should be:
p = (char *) malloc(100);
*p = `y';
The four important memory management functions for dynamic memory allocation and
reallocation are:
1. malloc
2. calloc
3. free
4. realloc
The function malloc is used to allocate a block of memory of specified size. It is defined
by:
void *malloc (number_of_bytes)
The malloc function returns a pointer to the first byte of the allocated memory block.
Since a void * is returned the C standard states that this pointer can be converted to
any type. For example,
char *cp;
cp = (char *) malloc (100);
attempts to get 100 bytes and assigns the starting address to cp.
We can also use the sizeof() function to specify the number of bytes. For example
int *ip;
ip = (int *) malloc (100*sizeof(int));
Some C compilers may require to cast the type of conversion. The (int *) means force
to an integer pointer. Forcing to the correct pointer type is very important to ensure
pointer arithmetic is performed correctly.
It is good practice to use sizeof() even if you know the actual size you want - it makes
for device independent (portable) code.
The sizeof can be used to find the size of any data type, variable or structure. Simply
supply one of these as an argument to the function. So:
int i;
struct complex
{
int real;
int imaginary;
};
sizeof(int), sizeof(i),
sizeof(struct complex) and
sizeof(comp) are all ACCEPTABLE.
It frees (releases) the memory space allocated for a block. The syntax is:
free (ptr);
This releases the block of memory allocated which is currently pointed to by the pointer
variable ptr. The advantage is simply memory management when we no longer need a
block.
There are two additional memory allocation functions, calloc() and realloc(). Their
prototypes are given below:
malloc does not initialise memory (to zero) in any way. If you wish to initialise memory
then use calloc. The calloc is slightly more computationally expensive but, occasionally,
more convenient than malloc. The syntax difference between calloc and malloc is that
calloc takes the number of desired elements, num_elements, and element_size, as two
individual arguments.
Thus to assign 100 integer elements that are all initially zero you would do:
int *ip;
ip = (int *) calloc (100, sizeof(int));
The realloc is a function, which attempts to change the size of a previous allocated
block of memory by malloc function. The new size can be larger or smaller. If the block
is made larger than the older, it will extend only if it can find additional space in the
same region. Otherwise, it may create entirely a new region (again, if space is
available) and move the contents of the old block into the new block without any loss.
The realloc function to increase the size of block to 200 integers instead of 100, simply
do:
ip = (int *) calloc (ip, 200);
If the size is to be made smaller then the remaining contents are unchanged. The
realloc function to reduce the size of block to 50 integers instead of 200, simply do:
Example:
# include <stdio.h>
# include <alloc.h>
# include <string.h>
Output:
The differences between the address stored in a pointer and a value at the
address:
The address stored in the pointer is the address of another variable. The value stored
at that address is a stored in a different variable. The indirection operator (*) returns
the value stored at the address, which itself is stored in a pointer.
The differences between the indirection operator and the address of operator:
The indirection operator (*) returns the value of the address stored in a pointer. The
address of operator (&) returns the memory address of the variable.
4.2. Files:
File is a bunch of bytes stored in a particular area on some storage devices like floppy
disk, hard disk, magnetic tape and cd-rom etc., which helps for the permanent storage.
The close operation disassociates a file from a specific stream. If the file was opened
for output, the close operation will write the contents (if any) of the stream to the
device. This process is usually called flushing the stream.
All files are closed automatically when the program terminates, but not when it
crashes.
Each stream associated with a file has a file control structure of type FILE.
Even though different devices are involved (terminals, disk drives, etc), the buffered
file system transforms each into a logical device called a stream. Because streams are
device-independent, the same function can write to a disk file or to another device,
such as a console. There are two types of streams:
The ANSI file system comprises several interrelated functions. These are:
Function Description
fopen() Opens a file.
fclose() Closes a file.
putc() Writes a character.
fputc() Writes a character.
getc() Reads a character.
fgetc() Reads a character.
fseek() Seeks a specified byte in a file.
fprintf() Is to a file what printf() is to the console.
fscanf() Is to a file what scanf() is to a console.
feof() Returns TRUE if end-of-file is reached.
ferror() Returns TRUE if an error is detected.
rewind() Resets file position to beginning of file.
remove() Erases a file.
fflush() Flushes a file.
Most of these functions begin with the letter "f". The header file stdio.h provides the
prototypes for the I/O function and defines these three types:
The latter three are used with fseek() function which performs random access on a file.
C treats a file just like a stream of characters and allows input and output as a stream
of characters. To store data in file we have to create a buffer area. This buffer area
allows information to be read or written on to a data file. The buffer area is
automatically created as soon as the file pointer is declared. The general form of
declaring a file is:
FILE *fp;
FILE is a defined data type, all files should be declared as type FILE before they are
used. FILE should be compulsorily written in upper case. The pointer fp is referred to as
the stream pointer. This pointer contains all the information about the file, which is
subsequently used as a communication link between the system and the program.
fopen() opens a stream for use, links a file with that stream and returns a pointer
associated with that file. The prototype of fopen() function is as follows:
Where, filename is a pointer to a string of characters that make a valid filename (and
may include a path specification) and mode determines how the file will be opened. The
legal values for mode are as follows:
Value Description
r Open a text file for reading.
w Create a text file for writing.
a Append to a text file.
rb Open a binary file for reading.
wb Create a binary file for writing.
ab Append to a binary file.
r+ Open a text file for read/write.
w+ Create a text file for read/write.
a+ Append or create a text file for read/write.
r+b Open a binary file for read/write.
w+b Create a binary file for read/write.
a+b Append a binary file for read/write.
FILE *fp;
fp = fopen ("test", "w");
However, because fopen() returns a null pointer if an error occurs when a file is
opened, this is better written as:
FILE *fp;
if ((fp = fopen ("test", "w")) == NULL)
{
printf("cannot open file\n");
exit(1);
}
fclose() closes the stream, writes any data remaining in the disk buffer to the file, does
a formal operating system level close on the file, and frees the associated file control
block. fclose() has this prototype:
A return value of zero signifies a successful operation. Generally, fclose() will fail only
when a disk has been prematurely removed or a disk is full.
Characters are written using putc() or its equivalent fputc(). The prototype for putc()
is:
Characters are read using getc() or its equivalent fgetc(). The prototype for getc() is:
For historical reasons, getc() returns an integer, but the high order byte is zero. getc()
returns an EOF when the end of file has been reached. The following code reads a text
file to the end:
As previously stated, the buffered file system can also operate on binary data. When a
file is opened for binary input, an integer value equal to the EOF mark may be read,
causing the EOF condition. To solve this problem, C includes the function feof(), which
determines when the end of the file is reached when reading binary data.
The following code reads a binary file until end of file is encountered:
Of course, this method can be applied to text files as well as binary files.
In addition to getc() and putc(), C supports the related functions fputs() and fgets(),
which read and write character strings. They have the following prototypes:
The function fputs() works like puts() but writes the string to the specified stream. The
fgets() function reads a string until either a newline character is read or length-1
characters have been read. If a newline is read, it will be part of the string (unlike
gets()). The resultant string will be null-terminated.
rewind() resets the file position indicator to the beginning of the file. The syntax of
rewind() is:
rewind(fptr);
ferror() determines whether a file operation has produced an error. It returns TRUE if
an error has occurred, otherwise it returns FALSE. ferror() should be called immediately
after each file operation, otherwise an error may be lost.
fflush () flushes the contents of an output stream. fflush() writes the contents of any
unbuffered data to the file associated with fp. It returns zero if successful.
To read and write data types which are longer than one byte, the ANSI standard
provides fread() and fwrite(). These functions allow the reading and writing of blocks of
any type of data. The prototypes are:
size_t fread (void *buffer, size_t num_bytes, size_t count, FILE *fp);
size_t fwrite (const void *buffer, size_t num_bytes, size_t count, FILE *fp);
For fread(), buffer is a pointer to a region of memory which will receive the data from
the file. For fwrite(), buffer is a pointer to the information which will be written. The
buffer may be simply the memory used to hold the variable, for example, &l for a long
integer.
fread() returns the number of items read. This value may be less than count if the end
of file is reached or an error occurs. fwrite() returns the number of items written.
One of the most useful applications of fread() and fwrite() involves reading and writing
user-defined data types, especially structures. For example, given this structure:
struct struct_type
{
float balance;
char name[80];
} cust;
Random read and write operations may be performed with the help of fseek(), which
sets the file position locator. The prototype is:
in which numbytes is the number of bytes from the origin, which will become the new
current position, and origin is one of the following macros defined in stdio.h:
fprint() and fscanf() behave exactly like print() and scanf() except that they operate
with files. The prototypes are:
Although these functions are often the easiest way to read and write assorted data,
they are not always the most efficient. Because formatted ASCII data is being written
as it would appear on the screen (instead of in binary), extra overhead is incurred with
each call. If speed or file size is of concern, use fread() and fwrite().
Normally, these streams refer to the console, but they may be redirected by the
operating system to some other device or environment. Because the standard streams
are file pointers, they may be used to provide buffered I/O operations on the console,
for example:
putchar(char c)
{
putc(c, stdout);
}
Some times it is very useful to pass information into a program when we run it from
the command prompt. The general method to pass information into main() function is
through the use of command line arguments.
A command line argument is the information that follows the program’s name on the
command prompt of the operating system.
• The third argument env (environment data) is used to access the DOS
environmental parameters active at the time the program begins execution.
When an array is used as an argument to function, only the address of the array is
passed, not a copy of the entire array. When you call a function with an array name, a
pointer to the first element in the array is passed into a function. (In C, an array name
without as index is a pointer to the first element in the array).
Each of the command line arguments must be separated by a space or a tab. If you
need to pass a command line argument that contains space, you must place it between
quotes as:
char *argv[];
The env parameter is declared the same as the argv parameter, it is a pointer to an
array of strings that contain environmental setting.
Example 4.3.1:
# include <stdio.h>
# include <process.h>
if the name of this program is name.exe, at the command prompt you have to type as:
name tom
Output:
hello tom
We must declare both argc and argv parameters even if they are not used because the
parameter declarations are position dependent.
The following programs demonstrate the use of C's file I/O functions.
Example 4.4.1:
Program on fopen(), fclose(), getc(), putc(). Specify filename on command line. Input
chars on keyboard until $ is entered. File is then closed. File is then re-opened and
read.
#include <stdio.h>
#include <stdlib.h>
if(argc!=2)
{
printf("You forgot to enter the file name\n");
exit(1);
}
while(ch != EOF)
{
putchar(ch); /* print on screen */
ch = getc(fp); /* read another char */
}
Example 4.4.2:
Program on feof() to check for EOF condition in Binary Files. Specify filenames for input
and output at command prompt. The program copies the source file to the destination
file. feof() checks for end of file condition. The feof() can also be used for text files.
#include <stdio.h>
#include <stdlib.h>
if(argc != 3)
{
printf("You forgot to enter the filenames\n");
exit(1);
}
Program on fputs(), fgets and rewind(). Strings are entered from keyboard until blank
line is entered. Strings are then written to a file called ‘testfile'. Since gets() does not
store the newline character, ‘\n’ is added before the string is written so that the file can
be read more easily. The file is then rewind, input and displayed.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main(void)
{
FILE *fp; /* file pointer */
char str[80];
rewind(fp); /* rewind */
Example 4.4.4:
Program on fread() and fwrite() (for Data Types Longer than Byte) which writes, then
reads back, a double, an int and a long. Notice how sizeof () is used to determine the
length of each data type. These functions are useful for reading and writing user-
defined data types, especially structures.
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
FILE *fp;
double d=12.23;
int i=101;
long l=123023;
rewind(fp);
printf("%2.3f %d %ld\n",d,i,l);
fclose(fp);
}
Example 4.4.5:
Program on fprintf() and fscanf(). Reads a string and an integer from the keyboard,
writes them to a file, then reads the file and displays the data. These functions are easy
to write mixed data to files but are very slow compared with fread() and fwrite().
#include <stdio.h>
#include <stdlib.h>
#include <exec/io.h>
FILE *fp;
char s[ 80];
int t;
if ((fp=fopen("testfile", "w"))==NULL) /* open for text write */
{
printf ("Cannot open file\n");
exit (1);
}
fscanf (fp,"%s%d",s,&t);
fprintf (stdout, "%s %d\n", s, t);
fclose (fp)
}
As defined by the ANSI standard, the C preprocessor contains the following directives:
#define:
Defines an identifier (the macro name) and a string (the macro substitution), which will
be substituted for the identifier each time the identifier is encountered in the source
file.
Once a macro name has been defined, it may be used as part of the definition of other
macro names.
If the string is longer than one line, it may be continued by placing a backslash on the
end of the first line.
#define TRUE 1
#define FALSE 0
The macro name may have arguments, in which case every time the macro name is
encountered, the arguments associated with it are replaced by the actual arguments
found in the program, as in:
Such macro substitutions in place of real functions increase the speed of the code at
the price of increased program size.
#error
#error forces the compiler to stop compilation. It is used primarily for debugging. The
general form is:
#error error_message
When the directive is encountered, the error message is displayed, possibly along with
other information (depending on the compiler).
#include instructs the compiler to read another source file, which must be included
between double quotes or angle brackets. Examples are:
#include "stdio.h"
#include <stdio.h>
Both instruct the compiler to read and compile the named header file.
If a file name is enclosed in angle brackets, the file is searched for the included file in a
special known \include directory or directories. If the name is enclosed in double
quotes, the file is searched in the current directory. If the file is not found, the search is
repeated as if the name had been enclosed in angle brackets.
Several directives control the selective compilation of portions of the program code.
They are:
#if constant_expression
statement sequence
#endif
#else works much like the C keyword else. #elif means "else if" and establishes an if-
else-if compilation chain.
Amongst other things, #if provides an alternative method of "commenting out" code.
For example, in
#if 0
printf("#d", total);
#endif
#ifdef means "if defined", and is terminated by an #endif. #indef means "if not
defined".
#undef
#line
#line changes the contents of __LINE__ (which contains the line number of the
currently compiled code) and __FILE__ (which is a string which contains the name of
the source file being compiled), both of which are predefined identifiers in the compiler.
Example 4.5.1.1:
# include <stdio.h>
# include <conio.h>
# define a 10
main()
{
#ifdef a
printf("\n Hello a is defined..");
#endif
#ifndef a
printf("\n Not defined ");
#else
printf("\n defined ");
#endif
getch();
}
Output:
Hello a is defined..
defined
The # and ## preprocessor operators are used when using a macro #define.
The # operator turns the argument it precedes into a quoted string. For example,
given:
#define mkstr(s) # s
#define concat(a, b) a ## b
int xy=10;
printf("%d", concat (x, y));
double ldexp(double x, int exp); Reconstructs x out of mantissa and exponent of two.
ldiv_t ldiv(long number, long denom); Divide one long integer by another.
double modf(double x, double *intptr); Breaks x into fractional and integer parts.
Math Constants:
The math.h library defines many (often neglected) constants. It is always advisable to
use these definitions:
M_PI π.
M_PI_2 π/2.
M_PI_4 π/4.
M_1_PI 1/ π.
M_2_PI 2/ π.
M_2_SQRTPI 2/ π .
M_SQRT2 The positive square root of 2.
There are also a number a machine dependent values defined in #include <value.h>.
The library #include <ctype.h> which contains many useful functions to convert and
test single characters. The common functions are prototypes are as follows:
Character testing:
Character Conversion:
The library #include <memory.h> contains the basic memory operations. Although not
strictly string functions the functions are prototyped in #include <string.h>:
void *memchr (void *s, int c, size_t n); Search for a character in a buffer.
int memcmp (void *s1, void *s2, size_t n); Compare two buffers.
void *memcpy (void *dest, void *src, size_t n); Copy one buffer into another.
void *memmove (void *dest, void *src, size_t n); Move a number of bytes from one buffer to
another.
void *memset (void *s, int c, size_t n); Set all bytes of a buffer to a given
character.
Note that in all case to bytes of memory are copied. The sizeof() function comes in
handy again here, for example:
char *strchr (const char *string, int c); Find first occurrence of character c in string.
char *strrchr (const char *string, int c); Find last occurrence of character c in string.
char *strstr (const char *s1, const char *s2); locates the first occurrence of the string s2 in
string s1.
char *strpbrk (const char *s1, const char *s2); returns a pointer to the first occurrence in
string s1 of any character from string s2, or a
null pointer if no character from s2 exists in
s1
size_t strspn (const char *s1, const char *s2); returns the number of characters at the
begining of s1 that match s2.
size_t strcspn (const char *s1, const char *s2); returns the number of characters at the
begining of s1 that do not match s2
char *strtok (char *s1, const char *s2); break the string pointed to by s1 into a
sequence of tokens, each of which is
delimited by one or more characters from the
string pointed to by s2.
char *strtok_r (char *s1, const char *s2, char has the same functionality as strtok () except
**lasts); that a pointer to a string placeholder lasts
must be supplied by the caller.
strchr () and strrchr () are the simplest to use.
#include <string.h>
#include <stdio.h>
main()
{
char *str1 = "Hello";
char *ans;
ans = strchr (str1,'l');
printf("%s\n", ans);
}
Output: llo
strpbrk () is a more general function that searches for the first occurrence of any of a
group of characters, for example:
#include <string.h>
#include <stdio.h>
main()
{
char *str1 = "Hello";
char *ans;
ans = strpbrk (str1,"aeiou");
printf("%s\n",ans);
}
Output: ello
Here, ans points to the location str1 + 1, the location of the first e.
strstr () returns a pointer to the specified search string or a null pointer if the string is
not found. If s2 points to a string with zero length (that is, the string ""), the function
returns s1.
Example 4.6.2:
#include <string.h>
#include <stdio.h>
main()
{
char *str1 = "Hello";
char *ans;
ans = strstr (str1, "lo");
printf("%s\n", ans);
}
strtok () is a little more complicated in operation. If the first argument is not NULL then
the function finds the position of any of the second argument characters. However, the
position is remembered and any subsequent calls to strtok() will start from this position
#include <string.h>
#include <stdio.h>
main()
{
char *str1 = "Hello Big Boy";
char *t1;
for(t1 = strtok (str1," "); t1 != NULL; t1 = strtok (NULL," "))
printf("%s\n", t1);
}
Output:
Hello
Big
Boy
The initialisation calls strtok () loads the function with the string str1.We terminate
when t1 is NULL. We keep assigning tokens of str1 to t1 until termination by calling
strtok () with a NULL first argument.
Example 1:
#include <stdio.h>
void main(void)
{
int i, *p;
i = 43;
p = & i;
printf ("%d %d\n", i, *p);
}
Output:
43 43
Example 2:
#include <stdio.h>
void main(void)
{
int i, *p;
i = 43;
p = &i;
*p = 16;
printf("%d\n", i);
}
Output:
16
Example 3:
#include <stdio.h>
void main(void)
{
int x;
x = 146;
change(&x);
printf("%d\n", x);
}
Output:
351
#include <stdio.h>
void swap(int *i, int *ii);
void main(void)
{
int x, y;
x = 10;
y = 127;
swap(&x, &y);
printf("%d %d\n", x, y);
}
Output:
127 10
Example 5:
#include <stdio.h>
void main(void)
{
void *v;
char *c;
c = "Testing void pointer";
v = c;
printf("%s\n", v);
}
Output:
Example 6:
#include <stdio.h>
#include <string.h>
void main(void)
{
char a[40], *p;
strcpy(a, "DATA");
p = a;
printf("%s\n", p);
}
Output:
DATA
#include <stdio.h>
void main(void)
{
char *a;
int x;
a = "DATA";
for (x = 0; x <= 4; ++x)
printf("%c\n", *(a + x));
}
Output:
D
A
T
A
Example 8:
#include <stdio.h>
void main(void)
{
char *a;
a = "DATA";
while (*a != '\0')
printf("%c\n", *a++);
}
Output:
D
A
T
A
Example 9:
#include <stdio.h>
void main(void)
{
char *a;
a = "DATA";
while (*a)
printf("%c\n", *a++);
}
Output:
D
A
T
A
#include <stdio.h>
void main(void)
{
char *a;
a = "DATA";
printf("%u\n", a);
while (*a)
printf("%c\n", *a++);
printf("%u\n", a);
}
Output:
118
D
A
T
A
122
Example 11:
#include <stdio.h>
void main(void)
{
char *p[5];
int x;
p[0] = "DATA";
p[1] = "LOGIC";
p[2] = "MICROPROCESSOR";
p[3] = "COMPUTER";
p[4] = "DISKETTE";
for (x = 0; x < 5; ++x)
printf("%s\n", p[x]);
}
Output:
DATA
LOGIC
MICROPROCESSOR
COMPUTER
DISKETTE
Example 12:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
void main(void)
{
char *a, b[256];
printf("enter a string:");
Output:
Example 13:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
void main(void)
{
char *a, b[256];
printf("enter a string:");
gets(b);
if ((a = (char*) malloc(strlen(b))) == NULL)
{
printf("Out of memory\n");
exit(0);
}
else
strcpy(a, b);
puts(a);
getch();
}
Output:
Example 14:
#include <stdio.h>
void main(void)
{
int x[40];
*(x + 0) = 65;
printf("%c\n", *(x + 0));
}
Output:
#include <stdio.h>
void main(void)
{
int x, y;
x = 8;
y = 11;
x = square(x, &y);
printf("%d %d\n", x, y);
}
Output:
64 121
Example 16:
#include <stdio.h>
void square(int *i, int *j);
void main(void)
{
int x, y;
x = 8;
y = 11;
square(&x, &y);
printf("%d %d\n", x, y);
}
Output:
64 121
Example 17:
#include <stdio.h>
#include <string.h>
Output:
housefly
Example 18:
struct test
{
int a;
char b;
char name[20];
};
#include <stdio.h>
#include <string.h>
void main(void)
{
struct test r;
load(&r);
printf("%d %c %s\n", r.a, r.b, r.name);
}
Output:
14 A Group
struct e_record
{
char name[15];
int id;
int years;
double sal;
};
#include <stdio.h>
#include <string.h>
void main(void)
{
struct e_record e, *emp;
emp = &e;
strcpy(emp->name, "Herbert Schildt");
emp->id = 14;
emp->years = 22;
emp->sal = 5305.00;
printf("Employee Name: %s\n", emp->name);
printf("Employee Number: %d\n", emp->id);
printf("Years Employed: %d\n", emp->years);
printf("Employee Salary: Rs.%-.2lf\n", emp->sal);
}
Output:
Example 20:
struct e_record
{
char name[15];
int id;
int years;
double sal;
};
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main(void)
{
struct e_record *emp;
if ((emp = (e_record*) malloc(sizeof(struct e_record))) == NULL)
exit(0);
strcpy(emp->name, "Herbert Schildt");
emp->id = 14;
emp->years = 22;
emp->sal = 535.00;
Output:
Example 21:
#include <stdlib.h>
void main(void)
{
int *x;
float *y;
double *z;
if ((z = malloc(sizeof(double))) == NULL)
exit(0);
y = (float *) z;
x = (int *) z;
/* x, y, and z all contain the same address */
/* memory allocation is for a double type */
*x = 19;
*y = 131.334;
*z = 9.9879;
}
Example 22:
#include <stdlib.h>
union test
{
int x;
float y;
double z;
};
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
union test *ptr;
if ((ptr = malloc(sizeof(union test))) == NULL)
exit(0);
printf("%d\n", sizeof(union test));
ptr->x = 19;
ptr->y = 131.334;
ptr->z = 9.9879;
}
Output: 8
struct e_record
{
char name[15];
int id;
int years;
double sal;
};
struct a_record
{
char name[15];
char address[40];
};
union com
{
struct e_record a;
struct a_record b;
};
#include <stdio.h>
#include <string.h>
void main(void)
{
union com v;
strcpy(v.a.name, "Bill Collins");
v.a.id = 44;
v.a.years = 12;
v.a.sal = 351.22;
printf("Name: %s\n", v.a.name);
printf("Identification: %d\n", v.a.id);
printf("Tenure: %d years\n", v.a.years);
printf("Salary: $%-.2lf\n\n", v.a.sal);
strcpy(v.b.name, "Bill Collins");
strcpy(v.b.address, "523 Short St.; Front Royal, VA 22630");
printf("Name: %s\n", v.b.name);
printf("Address: %s\n", v.b.address);
}
Example 24:
#include <stdio.h>
void main(void)
{
int x, *p, **ptp;
x = 454;
p = &x;
ptp = &p;
printf("%d %d\n", *p, **ptp);
}
Output:
454 454
#include <stdio.h>
#include <string.h>
void main(void)
{
char a[20], *b, **c;
strcpy(a, "Capacitor");
b = a;
c = &b;
printf(“%s %s\n", b, *c);
}
Output:
Capacitor Capacitor
Example 26:
#include <stdio.h>
void main(void)
{
int x, *p, **ptp, ***ptptp, ****ptptptp;
x = 274;
p = &x;
ptp = &p;
ptptp = &ptp;
ptptptp = &ptptp;
printf("%d\n", ****ptptptp);
}
Output:
274
getchar() gets()
Used to receive a single character. Used to receive a single string with
white spaces.
Does not require any argument. It requires a single argument.
scanf() gets()
Strings with any number of spaces can
Strings with spaces cannot be accessed.
be accessed.
Only character array data can be
All data types can be accessed.
accessed.
Spaces and tabs are not acceptable as a Spaces and tabs are perfectly acceptable
part of the input string. of the input string as a part.
Any number of characters, integers, float Only one string can be read at a time.
etc. can be read.
puts() printf()
It can display only one string at a time. It can display any number of characters,
integers or strings at a time.
No such conversion specifications. Every Each data type is considered separately
thing is treated as string. depending upon the conversion
specifications.
4. What is the difference between a pre increment and a post increment operation?
Break Continue
Used to terminate the loops or to exit Used to transfer the control to the start
from loop or switch. of loop.
The continue statement when executed
The break statement when executed
cause immediate termination of the
causes immediate termination of loop.
current iteration of the loop.
8. State the differences between the function prototype the function definition
Iteration Recursion
Iteration explicitly user a repetition Recursion achieves repetition through
structure. repeated function calls.
Iteration terminates when the loop Recursion terminates when a base case
continuation condition fails. is recognized.
Iteration keeps modifying the counter Recursion keeps producing simple
until the loop continuation condition versions of the original problem until
fails. the base case is reached.
Iteration normally occurs within a loop Recursion causes another copy of the
so, the extra memory assigned is function and hence a considerable
omitted. memory space is occupied.
It reduces the processor’s operating It increases the processor’s operating
time. time.
11. What is the difference between the address stored in a pointer and a value at the
address?
The address stored in the pointer is the address of another variable. The value
stored at that address is a stored in a different variable. The indirection operator
(*) returns the value stored at the address.
12. What is the difference between the indirection operator and the address of
operator?
The indirection operator (*) returns the value of the address stored in a pointer.
The address of operator (&) returns the memory address of the variable.
13. State the difference between call by value and call by reference.
Arrays Structures
An array is an single entity representing A structure is a single entity
a collection of data items of same data representing a collection of data items
types. of different data types.
Individual entries in an array are called Individual entries in a structure are
elements. called members.
An array declaration reserves enough The structure definition reserves
memory space for its elements. enough memory space for its members.
There is no keyword to represent arrays The keyword struct tells us that we are
but the square braces [] preceding the dealing with structures.
variable name tells us that we are
dealing with arrays.
Structures Unions
Each member in a structure occupies All the members of a union use the
and uses its own memory space. same memory space.
The keyword struct tells us that we are The keyword union tells us that we are
dealing with structures. dealing with unions.
All the members of a structure can be Only one member of a union can be
initialized. initialized.
More memory space is required since Less memory space is required since all
each member is stored in a separate members are stored in the same
memory locations. memory locations.
Its general format is: Its general formula is:
struct structure name union union name
{ {
data_type structure Member1; data_type structure Member1;
data_type structure Member2; data_type structure Member2;
. .
. .
data_type structure Member N; data_type structure Member N;
} structure variable; } union variable;
Example: Example:
struct student union student
{ {
char studname[25]; char studname[25];
int rollno; int rollno;
} stud1; } stud1;
1. Function makes the lengthy and complex program easy and in short forms.
It means large program can be sub-divided into self-contained and
convenient small modules having unique name.
3. By using function, memory space can be properly utilized. Also less memory
is required to run program if function is used.
7. Debugging (removing error) becomes very easier and fast using the function
sub-programming.
10. User can build a customized library of different functions used in daily
routine having specific goal and link with the main program similar to the
library functions.
18. A complete summarized table to represent the lifetime and visibility (scope) of all
the
storage class specifier is as below:
19. Tokens:
Tokens are the smallest individual unit in a program. The different types of tokens
used in C are as follows:
• Keywords.
• Identifiers.
• Constants.
• Operators.
• Strings.
SAMPLE C – PROGRAMS
1. Write a C programme to accept a list of data items & find the II largest & II
smallest in it & take average of both & search for that value. Display appropriate
message on successful search.
main ()
{
int i,j,a,n,counter,ave,number[30];
printf ("Enter the value of N\n");
scanf ("%d", &n);
printf ("Enter the numbers \n");
for (i=0; i<n; ++i)
scanf ("%d",&number[i]);
for (i=0; i<n; ++i)
{
for (j=i+1; j<n; ++j)
{
if (number[i] < number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf ("The numbers arranged in ascending order are given below\n");
for (i=0; i<n; ++i)
printf ("%10d\n",number[i]);
printf ("The 2nd largest number is = %d\n", number[1]);
printf ("The 2nd smallest number is = %d\n", number[n-2]);
ave = (number[1] +number[n-2])/2;
counter = 0;
for (i=0; i<n; ++i)
{
if (ave==number[i])
++counter;
}
if (counter==0)
printf("The average of 2nd largest & 2nd smallest is not in the array\n");
else
printf("The average of 2nd largest & 2nd smallest in array is %d in
numbers\n", counter);
}
206
2. Write a C programme to arrange the given numbers in ascending order.
main ()
{
int i,j,a,n,number[30];
printf ("Enter the value of N\n");
scanf ("%d", &n);
printf ("Enter the numbers \n");
for (i=0; i<n; ++i)
scanf ("%d",&number[i]);
for (i=0; i<n; ++i)
{
for (j=i+1; j<n; ++j)
{
if (number[i] > number[j])
{
a= number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("Number in Asscending order:\n");
for(i=0;i<n;i++)
printf("\t%d\n",number[i]);
}
# include <stdio.h>
main()
{
int num, bnum, dec = 0, base = 1, rem ;
printf("Enter the binary number(1s and 0s)\n");
scanf("%d", &num); /*maximum five digits */
bnum = num;
while( num > 0)
{
rem = num % 10;
if(rem>1)
{
printf("\nError in input");
break;
}
dec = dec + rem * base;
num = num / 10 ;
base = base * 2;
}
if(num==0)
{
printf("The Binary number is = %d\n", bnum);
printf("Its decimal equivalent is =%d\n", dec);
}
}
207
4. Write to accept a 1-dimensional array of N elements & split into 2 halves & sort
1st half in ascending order & 2nd into descending order.
#include<stdio.h>
main ()
{
int i,j,a,n,b,number[30];
printf ("Enter the value of N\n");
scanf ("%d", &n);
b = n/2;
printf ("Enter the numbers \n");
for (i=0; i<n; ++i)
scanf ("%d",&number[i]);
for (i=0; i<b; ++i)
{
for (j=i+1; j<b; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
for (i=b; i<n; ++i)
{
for (j=i+1; j<n; ++j)
{
if (number[i] < number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf (" The 1st half numbers\n");
printf (" arranged in asc\n");
for (i=0; i<b; ++i)
printf ("%d ",number[i]);
printf("\nThe 2nd half Numbers\n");
printf("order arranged in desc.order\n");
for(i=b;i<n;i++)
printf("%d ",number[i]);
}
208
5. Program to delete the desired element from the list.
# include <stdio.h>
main()
{
int vectx[10];
int i, n, found = 0, pos, element;
209
6. Write a "C" program to Interchange the main diagonal elements with the
scondary diagonal elements.
#include<stdio.h>
main ()
{
int i,j,m,n,a;
static int ma[10][10];
printf ("Enetr the order of the matix \n");
scanf ("%dx%d",&m,&n);
if (m==n)
{
printf ("Enter the co-efficients of the matrix\n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
scanf ("%dx%d",&ma[i][j]);
}
}
printf ("The given matrix is \n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
printf (" %d",ma[i][j]);
}
printf ("\n");
}
for (i=0;i<m;++i)
{
a = ma[i][i];
ma[i][i] = ma[i][m-i-1];
ma[i][m-i-1] = a;
}
printf ("THe matrix after changing the \n");
printf ("main diagonal & secondary diagonal\n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
printf (" %d",ma[i][j]);
}
printf ("\n");
}
}
else
printf ("The given order is not square matrix\n");
}
210
7. Program to insert an element at an appropriate position in an array.
#include <stdio.h>
#include <conio.h>
main()
{
int x[10];
int i, j, n, m, temp, key, pos;
clrscr();
printf("Enter how many elements\n");
scanf("%d", &n);
211
x[n-i+2] = x[n-i+1] ;
}
x[pos] = key;
#include <stdio.h>
main()
{
int fib1=0, fib2=1, fib3, limit, count=0;
main()
{
float x[10];
int i, n;
float avrg, var, SD, sum=0, sum1=0;
212
}
avrg = sum /(float) n;
/* Compute varaience and standard deviation */
for(i=0; i<n; i++)
{
sum1 = sum1 + pow((x[i] - avrg),2);
}
var = sum1 / (float) n;
SD = sqrt(var);
#include<stdio.h>
#include<string.h>
#include<conio.h>
struct tag
{
char name[10];
int rno;
};
node s[5];
sort(int no)
{
int i,j;
node temp;
for(i=0;i<no-1;i++)
for(j=i+1;j<no;j++)
if(strcmp(s[i].name,s[j].name)>0)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
main()
{
int no,i;
clrscr();
fflush(stdin);
for(i=0;i<no;i++)
213
{
printf("Enter The Name:");
fflush(stdin);
gets(s[i].name);
printf("Enter the Roll:");
scanf("%d",&s[i].rno);
}
sort(no);
for(i=0;i<no;i++)
{
printf("%s\t",s[i].name);
printf("%d\n",s[i].rno);
}
getche();
}
#include <stdio.h>
main()
{
int num, rev = 0, found = 0, temp, digit;
temp = num;
while(num > 0)
{
digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
printf("Given number =%d\n", temp);
printf("Its reverse is =%d\n", rev);
if(temp == rev )
printf("Number is a palindrome\n");
else
printf("Number is not a palindrome\n");
}
12. Program to find the frequency of odd numbers & even numbers in the input of a
matrix.
#include<stdio.h>
main ()
{
int i,j,m,n,even=0,odd=0;
static int ma[10][10];
printf ("Enter the order ofthe matrix \n");
scanf ("%d %d",&m,&n);
printf ("Enter the coefficients if matrix \n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
214
{
scanf ("%d", &ma[i][j]);
if ((ma[i][j]%2) == 0)
{
++even;
}
else
++odd;
}
}
printf ("The given matrix is\n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
printf (" %d",ma[i][j]);
printf ("\n");
}
printf ("The frequency of odd number occurance = %d\n",odd);
printf ("The frequency of even number occurance = %d\n",even);
}
#include <stdio.h>
main()
{
int numb;
printf(" Enter the number\n");
scanf("%d", &numb);
if((numb%2)!=0)
printf(" %d , is an odd number\n", numb);
#include <stdio.h>
main()
{
int m,n;
printf(" Enter the values for M and N\n");
scanf("%d%d", &m,&n);
if(m == n )
printf("M and N are equal\n");
else
printf("M and N are not equal\n");
}
215
15. Program to find the largest among three numbers.
#include <stdio.h>
main()
{
int a,b,c;
printf(" Enter the values for A,B,C\n");
scanf("%d %d %d", &a,&b,&c);
if( a > b )
{
if ( a > c)
printf(" A is the Largest\n");
else
printf("C is the largest\n");
}
else if ( b > c)
printf(" B is the Largest\n");
else
printf("C is the Largest\n");
}
#include <stdio.h>
main()
{
int x,y;
printf("Enter the values for X and Y\n");
scanf("%d %d",&x,&y);
17. Program to find the areas of different geometrical figures using switch statement.
#include <stdio.h>
main()
{
int fig_code;
float side,base,length,bredth,height,area,radius;
printf("-------------------------\n");
printf(" 1 --> Circle\n");
printf(" 2 --> Rectangle\n");
printf(" 3 --> Triangle\n");
printf(" 4 --> Square\n");
216
printf("-------------------------\n");
switch(fig_code)
{
case 1:
printf(" Enter the radius\n");
scanf("%f",&radius);
area=3.142*radius*radius;
printf("Area of a circle=%f\n", area);
break;
case 2:
printf(" Enter the bredth and length\n");
scanf("%f %f",&bredth, &length);
area=bredth *length;
printf("Area of a Reactangle=%f\n", area);
break;
case 3:
printf(" Enter the base and height\n");
scanf("%f %f",&base,&height);
area=0.5 *base*height;
printf("Area of a Triangle=%f\n", area);
break;
case 4:
printf(" Enter the side\n");
scanf("%f",&side);
area=side * side;
printf("Area of a Square=%f\n", area);
break;
default:
printf(" Error in figure code\n");
break;
} /* End of switch */
} /* End of main() */
#include <stdio.h>
#include <string.h>
main()
{
char remark[15], grade;
switch(grade)
{
case 'S':
strcpy(remark," SUPER");
217
break;
case 'A':
strcpy(remark," VERY GOOD");
break;
case 'B':
strcpy(remark," FAIR");
break;
case 'Y':
strcpy(remark," ABSENT");
break;
case 'F':
strcpy(remark," FAILS");
break;
default :
strcpy(remark, "ERROR IN GRADE\n");
break;
} /* End of switch */
printf("RESULT: %s\n",remark);
}
#include <stdio.h>
main()
{
int num,sum=0;
for(num=1;num<=50; num++)
sum += num;
printf("Sum =%4d\n", sum);
}
#include <stdio.h>
main()
{
int index=0, value=0,number;
printf("Enter The Number\n");
scanf("%d", &number);
for(index=1;index<=number;index++)
{
value++;
printf("%d\n",value);
}
printf("Goodbye\n");
}
#include <stdio.h>
main()
{
int i,fact=1,num;
printf("Enter the number\n");
218
scanf("%d",&num);
if( num <0)
printf(“Factorial is not there for –ve numbers”);
else if(num==0 || num==1)
fact=1;
else
{
for(i=1;i<=num; i++)
fact *= i;
}
printf(" Factorial of %d =%5d\n", num,fact);
}
22. Program to illustrate for loop without initial and increment/decrement expressions.
#include <stdio.h>
main()
{
int i=0,limit=5;
printf(" Values of I\n");
for( ; i<limit; )
{
i++;
printf("%d\n",i);
}
}
23. Program to accept a string and find the sum of all digits in the string.
#include <stdio.h>
main()
{
char string[80];
int count,nc=0,sum=0;
printf("Enter the string containing both digits and alphabet\n");
scanf("%s",string);
for(count=0;string[count]!='\0'; count++)
{
if((string[count]>='0') && (string[count]<='9'))
{
nc += 1;
sum += (string[count] - '0');
}
}
printf("NO. of Digits in the string=%d\n",nc);
printf("Sum of all digits=%d\n",sum);
#include <stdio.h>
#include <math.h>
#define pi 3.142
219
main()
{
int i,n,k,sign;
float sum=0,num,den,xdeg,xrad,xsqr,term;
printf("Enter the angle( in degree)\n");
scanf("%f",&xdeg);
printf("Enter the no. of terms\n");
scanf("%d",&n);
xrad=xdeg * (pi/180.0); /* Degrees to radians*/
xsqr= xrad*xrad;
sign=1; k=2; num=xrad; den=1;
for(i=1;i<=n; i++)
{
term=(num/den)* sign;
sum += term;
sign *= -1;
num *= xsqr;
den *= k*(k+1);
k += 2;
}
printf("Sum of sine series of %d terms =%8.3f\n",n,sum);
}
#include<stdio.h>
#include<math.h>
main()
{
float x,sign,cosx,fact;
int n,x1,i,j;
printf("Enter the number of the terms in a series\n");
scanf("%d",&n);
printf("Enter the value of x(in degrees)\n");
scanf("%f",&x);
x1=x;
x=x*(3.142/180.0); /* Degrees to radians*/
cosx=1;
sign=-1;
for(i=2;i<=n;i=i+2)
{
fact=1;
for(j=1;j<=i;j++)
{
fact=fact*j;
}
cosx=cosx+(pow(x,i)/fact)*sign;
sign=sign*(-1);
}
printf("Sum of the cosine series=%f\n",cosx);
printf("The value of cos(%d) using library function=%f\n",x1,cos(x));
}
220
26. Program to find the sum of all elements of an array using pointers.
#include <stdio.h>
main()
{
static int array[5]={ 200,400,600,800,1000 };
int addnum(int *ptr); /* function prototype */
int sum;
sum = addnum(array);
printf(" Sum of all array elements=%d\n", sum);
#include <stdio.h>
main()
{
float x[10];
int i,n;
float swap34(float *ptr1, float *ptr2 ); /* Function Declaration */
printf(" How many Elements...\n");
scanf("%d", &n);
printf(" Enter Elements one by one\n");
for(i=0;i<n;i++)
scanf("%f",x+i);
221
28. Program to find the sum of two 1-D arrays using Dynamic Memory Allocation.
#include <stdio.h>
#include <malloc.h>
main()
{
int i,n,sum;
int *a,*b,*c;
printf(" How many Elements in each array...\n");
scanf("%d", &n);
a=(int *) malloc(sizeof(n*(int));
b=(int *) malloc(sizeof(n*(int));
c=(int *) malloc(sizeof(n*(int));
printf(" Enter Elements of First List\n");
for(i=0;i<n;i++)
scanf("%f",a+i);
for(i=0;i<n;i++)
c+i=(a+i) +( b+i);
printf(" Resultant List is\n");
for(i=0;i<n;i++)
printf("C[%d]=%f\n",i,c[i]);
}
#include <stdio.h>
main()
{
int num, rev = 0, found = 0, temp, digit;
temp = num;
while(num > 0)
{
digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
printf("Given number =%d\n", temp);
printf("Its reverse is =%d\n", rev);
}
222
30. Program to sort all rows of matrix in ascending order & all columns in descending
order.
main ()
{
int i,j,k,a,m,n;
static int ma[10][10],mb[10][10];
printf ("Enter the order of the matrix \n");
scanf ("%d %d", &m,&n);
printf ("Enter co-efficients of the matrix \n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
scanf ("%d",&ma[i][j]);
mb[i][j] = ma[i][j];
}
}
printf ("The given matrix is \n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
printf (" %d",ma[i][j]);
}
printf ("\n");
}
printf ("After arranging rows in ascending order\n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
for (k=(j+1);k<n;++k)
{
if (ma[i][j] > ma[i][k])
{
a = ma[i][j];
ma[i][j] = ma[i][k];
ma[i][k] = a;
}
}
}
}
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
printf (" %d",ma[i][j]);
}
printf ("\n");
}
printf ("After arranging the columns in descending order \n");
for (j=0;j<n;++j)
{
for (i=0;i<m;++i)
{
for (k=i+1;k<m;++k)
223
{
if (mb[i][j] < mb[k][j])
{
a = mb[i][j];
mb[i][j] = mb[k][j];
mb[k][j] = a;
}
}
}
}
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
printf (" %d",mb[i][j]);
}
printf ("\n");
}
}
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
main()
{
char sentence[100];
int count, ch, i;
clrscr();
printf("Enter a sentence\n");
for(i=0; (sentence[i] = getchar())!='\n'; i++);
count = i;
sentence[count]='\0';
printf("Input sentence is : %s",sentence);
printf("\nResultant sentence is\n");
for(i=0; i < count; i++)
{
ch = islower(sentence[i]) ? toupper(sentence[i]) :
tolower(sentence[i]);
putchar(ch);
}
}
32. Program to find the sum of the rows & columns of a matrix.
main ()
{
int i,j,m,n,sum=0;
static int m1[10][10];
printf ("Enter the order of the matrix\n");
scanf ("%d%d", &m,&n);
printf ("Enter the co-efficients of the matrix\n");
for (i=0;i<m;++i)
224
{
for (j=0;j<n;++j)
{
scanf ("%d",&m1[i][j]);
}
}
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
sum = sum + m1[i][j] ;
}
printf (" Sum of the %d row is = %d\n",i,sum);
sum = 0;
}
sum=0;
for (j=0;j<n;++j)
{
for (i=0;i<m;++i)
{
sum = sum+m1[i][j];
}
printf ("Sum of the %d column is = %d\n", j,sum);
sum = 0;
}
}
#include<stdio.h>
main ()
{
int i,j,m,n;
static int ma[10][10];
printf ("Enter the order of the matrix \n");
scanf ("%d %d",&m,&n);
printf ("Enter the coefiicients of the matrix\n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
scanf ("%d",&ma[i][j]);
}
}
printf ("The given matrix is \n");
for (i=0;i<m;++i)
{
for (j=0;j<n;++j)
{
printf (" %d",ma[i][j]);
}
printf ("\n");
}
printf ("Transpose of matrix is \n");
for (j=0;j<n;++j)
{
225
for (i=0;i<m;++i)
{
printf (" %d",ma[i][j]);
}
printf ("\n");
}
}
#include <stdio.h>
#include <conio.h>
main()
{
union number
{
int n1;
float n2;
};
union number x;
clrscr() ;
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("Value of n1 =%d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%d", &x.n2);
printf("Value of n2 = %d\n",x.n2);
}
35. Program to accepts two strings and compare them. Finally print whether, both
are equal, or first string is greater than the second or the first string is less than the
second string without using string library.
#include<stdio.h>
#include<conio.h>
void main()
{
int count1=0,count2=0,flag=0,i;
char str1[10],str2[10];
clrscr();
puts("Enter a string:");
gets(str1);
226
/*The string comparison starts with the first character in each string and continues with
subsequent characters until the corresponding characters differ or until the end of the
strings is reached.*/
if (flag==0)
printf("Both strings are equal\n");
if (flag==1)
printf("String1 is greater than string2\n", str1, str2);
if (flag == -1)
printf("String1 is less than string2\n", str1, str2);
getch();
}
Output:
RUN2:
Enter a string: Hello
Enter another string: Hello
Both strings are equal
RUN3:
Enter a string: gold
Enter another string: silver
String1 is less than string2
36. Program to accept a decimal number and convert it binary and count the number
of 1's in the binary number.
#include <stdio.h>
main()
{
227
long num, dnum, bin = 0, base = 1;
int rem, no_of_1s = 0 ;
Output:
RUN2
Enter a decimal integer: 128
Input number is = 128
Its Binary equivalent is=10000000
No. of 1's in the binary number is = 1
#include<stdio.h>
#include<conio.h>
void main()
{
struct employee
{
long int code;
char name[20];
char vertical[15];
float salary;
};
struct employee emp;
clrscr();
printf("employee code:");
scanf("%ld",&emp.code);
fflush(stdin);
228
printf("employee name:");
scanf("%[^\n]",emp.name);
fflush(stdin);
printf("vertical:");
scanf("%[^\n]",emp.vertical);
fflush(stdin);
printf("salary:");
scanf("%f",&emp.salary);
clrscr();
printf(" EMPLOYEE INFORMATION SYSTEM\n");
printf("------------------------------------------------\n");
printf("CODE | NAME | VERTICAL |SALARY\n");
printf("%ld | %-15s| %-15.10s| 7.2f\n", emp.code, emp.name, emp.vertical,
emp.salary);
printf("------------------------------------------------\n");
getch();
}
38. Program to accept N integer number and store them in an array AR. The odd
elements in the AR are copied into OAR and other elements are copied into EAR. Display
the contents of OAR and EAR.
#include <stdio.h>
main()
{
long int ARR[10], OAR[10], EAR[10];
int i,j=0,k=0,n;
229
}
Output:
39.
#include<stdio.h>
#include<conio.h>
void main()
{ struct date
{
int day;
int month;
int year;
};
struct details
{
char name[20];
int price;
int code;
int qty;
struct date mfg;
};
clrscr();
printf("Enter number of items:");
230
scanf("%d",&n);
fflush(stdin);
for(i=0;i<n;i++)
{
fflush(stdin);
printf("Item name:");
scanf("%[^\n]",item[i].name);
fflush(stdin);
printf("Item code:");
scanf("%d",&item[i].code);
fflush(stdin);
printf("Quantity:");
scanf("%d",&item[i].qty);
fflush(stdin);
printf("price:");
scanf("%d",&item[i].price);
fflush(stdin);
printf("Manufacturing date(dd-mm-yyyy):");
scanf("%d-%d-%d",&item[i].mfg.day,&item[i].mfg.month,&item[i].mfg.year);
}
printf(" ***** INVENTORY *****\n");
printf("------------------------------------------------------------------\n");
printf("S.N.| NAME | CODE | QUANTITY | PRICE |MFG.DATE\n");
printf("------------------------------------------------------------------\n");
for(i=0;i<n;i++)
printf("%d %-15s %-d %-5d %-5d
%d/%d/%d\n",i+1,item[i].name,item[i].code,item[i].qty,item[i].pr
ice,item[i].mfg.day,item[i].mfg.month,item[i].mfg.year);
printf("------------------------------------------------------------------\n");
getch();
}
# include <stdio.h>
main()
{
int year;
printf("Enter a year:\n");
scanf("%d",&year);
if ( (year % 4) == 0)
printf("%d is a leap year",year);
else
printf("%d is not a leap year\n",year);
}
Output:
231
2000 is a leap year
RUN2:
# include <stdio.h>
main()
{
long number, tempnum;
printf("Enter an integer:\n");
scanf("%ld",&number);
tempnum = number;
number = number << 2; /*left shift by two bits*/
Output:
Enter an integer: 15
15 x 4 = 60
RUN2:
Enter an integer: 262
262 x 4 = 1048
42.
#include<stdio.h>
#include<conio.h>
void main()
{
int count1=0,count2=0,i,j,flag;
char str[80],search[10];
clrscr();
puts("Enter a string:");
gets(str);
puts("Enter search substring:");
gets(search);
while (str[count1]!='\0')
count1++;
while (search[count2]!='\0')
count2++;
for(i=0;i<=count1-count2;i++)
{
for(j=i;j<i+count2;j++)
{
flag=1;
if (str[j]!=search[j-i])
{
232
flag=0;
break;
}
}
if (flag==1)
break;
}
if (flag==1)
puts("SEARCH SUCCESSFUL!");
else
puts("SEARCH UNSUCCESSFUL!");
getch();
}
#include <stdio.h>
#include <math.h>
void main()
{
long int x,n,xpown;
long int power(int x, int n);
Output:
RUN2:
Enter the values of X and N: 4 4
X to the power N ==256
RUN3:
Enter the values of X and N: 5 2
X to the power N = 25
233
RUN4:
Enter the values of X and N: 10 5
X to the power N = 100000
44. Program to accept a string and find the number of times the word 'the' appears in
it.
#include<stdio.h>
#include<conio.h>
void main()
{
int count=0,i,times=0,t,h,e,space;
char str[100];
clrscr();
puts("Enter a string:");
gets(str);
/*Traverse the string to count the number of characters*/
while (str[count]!='\0')
{
count++;
}
/*Finding the frequency of the word 'the'*/
for(i=0;i<=count-3;i++)
{
t=(str[i]=='t'||str[i]=='T');
h=(str[i+1]=='h'||str[i+1]=='H');
e=(str[i+2]=='e'||str[i+2]=='E');
space=(str[i+3]==' '||str[i+3]=='\0');
if ((t&&h&&e&&space)==1)
times++;
}
printf("Frequency of the word \'the\' is %d\n",times);
getch();
}
Output:
#include<conio.h>
#include<string.h>
#include<stdio.h>
void main()
{
int count=0,chars,words=0,lines,i;
char text[1000];
clrscr();
234
puts("Enter text:");
gets(text);
while (text[count]!='\0')
count++;
chars=count;
for (i=0;i<=count;i++)
{
if ((text[i]==' '&&text[i+1]!=' ')||text[i]=='\0')
words++;
}
lines=chars/80+1;
printf("no. of characters:%d\n",chars);
printf("no. of words:%d\n",words);
printf("no. of lines:%d\n",lines);
getch();
}
46. Program to swap the contents of two numbers using bitwise XOR operation. Don't
use either the temporary variable or arithmetic operators.
# include <stdio.h>
main()
{
long i,k;
printf("Enter two integers: \n");
scanf("%ld %ld",&i,&k);
printf("\nBefore swapping i= %ld and k = %ld",i,k);
i = i^k;
k = i^k;
i = i^k;
printf("\nAfter swapping i= %ld and k = %ld",i,k);
Output:
47. Program to find the length of a string without using the built-in function, also
check whether it is a palindrome or not.
#include <stdio.h>
#include <string.h>
#include <conio.h>
main()
{
char string[25], revString[25]={'\0'};
int i, length = 0, flag = 1;
235
clrscr();
fflush(stdin);
printf("Enter a string\n");
gets(string);
if (flag == 1)
printf ("%s is a palindrome\n", string);
else
printf("%s is not a palindrome\n", string);
}
Output:
RUN2:
Enter a string: good
The length of the string 'good' = 4
good is not a palindrome
48. Program to accept two strings and concatenate them i.e. the second string is
appended to the end of the first string.
#include <stdio.h>
#include <string.h>
main()
{
char string1[20], string2[20];
int i,j,pos;
236
printf("Enter the first string:");
gets(string1);
fflush(stdin);
printf("Enter the second string:");
gets(string2);
pos = i;
for (i=pos,j=0; string2[j]!='\0'; i++)
{
string1[i] = string2[j++];
}
string1[i]='\0'; /*set the last character of string1 to NULL*/
Output:
49.
#include <stdio.h>
int A[10][10], B[10][10], sumat[10][10], diffmat[10][10];
int i, j, R1, C1, R2, C2;
main()
{
void readmatA();
void printmatA();
void readmatB();
void printmatB();
void sum();
void diff();
237
if( R1 != R2 && C1 != C2)
{
printf("Addition and subtraction are possible\n");
exit(1);
}
else
{
printf("Enter the elements of matrix A\n");
readmatA();
printf("MATRIX A is\n");
printmatA();
sum();
diff();
}
return 0;
}
void readmatA()
{
for(i=0; i<R1; i++)
{
for(j=0; j<C1; j++)
{
scanf("%d",&A[i][j]);
}
}
return;
}
void readmatB()
{
for(i=0; i<R2; i++)
{
for(j=0; j<C2; j++)
{
scanf("%d",&B[i][j]);
}
}
}
void printmatA()
{
for(i=0; i<R1; i++)
{
for(j=0; j<C1; j++)
{
printf("%3d",A[i][j]);
}
printf("\n");
}
}
238
void printmatB()
{
for(i=0; i<R2; i++)
{
for(j=0; j<C2; j++)
{
printf("%3d",B[i][j]);
}
printf("\n");
}
}
void sum()
{
for(i=0; i<R1; i++)
{
for(j=0; j<C2; j++)
{
sumat[i][j] = A[i][j] + B[i][j];
}
}
printf("Sum matrix is\n");
for(i=0; i<R1; i++)
{
for(j=0; j<C2; j++)
{
printf("%3d",sumat[i][j]) ;
}
printf("\n");
}
return;
}
void diff()
{
for(i=0; i<R1; i++)
{
for(j=0; j<C2; j++)
{
diffmat[i][j] = A[i][j] - B[i][j];
}
}
printf("Difference matrix is\n");
for(i=0; i<R1; i++)
{
for(j=0; j<C2; j++)
{
printf("%3d",diffmat[i][j]);
}
printf("\n");
}
return;
}
239
50.
#include <stdio.h>
#include <conio.h>
main()
{
int A[10][10], B[10][10];
int i, j, R1, C1, R2, C2, flag =1;
240
{
if(A[i][j] != B[i][j])
{
flag = 0;
break;
}
}
}
}
else
{
printf(" Cannot be compared\n");
exit(1);
}
if(flag == 1 )
printf("Two matrices are equal\n");
else
printf("But,two matrices are not equal\n");
}
51. Program to illustrate how user authentication is made before allowing the user to
access the secured resources. It asks for the user name and then the password. The
password that you enter will not be displayed, instead that character is replaced by '*'.
#include <stdio.h>
void main()
{
char pasword[10],usrname[10], ch;
int i;
clrscr();
for(i=0;i<8;i++)
{
ch = getch();
pasword[i] = ch;
ch = '*' ;
printf("%c",ch);
}
pasword[i] = '\0';
printf("\n\n\nYour password is :");
for(i=0;i<8;i++)
{
printf("%c",pasword[i]);
}
}
241
52. Program to find the length of a string without using the built-in function.
# include <stdio.h>
main()
{
char string[50];
int i, length = 0;
printf("Enter a string\n");
gets(string);
Output:
Enter a string
hello
The length of a string is the number of characters in it
So, the length of hello = 5
RUN2
Enter a string
E-Commerce is hot now
The length of a string is the number of characters in it
So, the length of E-Commerce is hot now =21
53. Program to read a matrix A (MxN) and to find the following using functions:
a) Sum of the elements of each row
b) Sum of the elements of each column
c) Find the sum of all the elements of the matrix
#include <stdio.h>
main()
{
int arr[10][10];
int i, j, row, col, rowsum, colsum,sumall=0;
clrscr();
242
{
scanf("%d", &arr[i][j]);
}
}
printf("Input matrix is\n");
for(i=0; i<row; i++)
{
for(j=0;j<col;j++)
{
printf("%3d", arr[i][j]);
}
printf("\n");
}
/* computing row sum */
for(i=0; i<row; i++)
{
rowsum = Addrow(arr,i,col);
printf("Sum of row %d = %d\n", i+1, rowsum);
}
243
Output:
Input matrix is
1 2 3
4 5 6
7 8 9
Sum of row 1 = 6
Sum of row 2 = 15
Sum of row 3 = 24
Sum of column 1 = 12
Sum of column 2 = 15
Sum of column 3 = 18
Sum of all elements of matrix = 45
#include <stdio.h>
main()
{
int number;
clrscr();
printf("Enter a number\n");
scanf ("%d", &number);
if (number > 0)
printf ("%d, is a positive number\n", number);
else
printf ("%d, is a negative number\n", number);
Output:
Enter a number
-5
-5, is a negative number
RUN2
Enter a number
89
89, is a positive number
244
55. Program to find and output all the roots of a quadratic equation, for non-zero
coefficients. In case of errors your program should report suitable error message.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
main()
{
float A, B, C, root1, root2;
float realp, imagp, disc;
clrscr();
Output:
RUN 1
Enter the values of A, B and C: 3 2 1
Imaginary Roots
245
Root1 = -0.333333 +i 0.471405
Root2 = -0.333333 -i 0.471405
RUN 2
Enter the values of A, B and C: 1 2 1
Roots are real and equal
Root1 = -1.000000
Root2 = -1.000000
RUN 3
Enter the values of A, B and C: 3 5 2
Roots are real and distinct
Root1 = -0.666667
Root2 = -1.000000
#include <stdio.h>
main()
{
char operator;
float n1, n2;
float sum, diff, prod, quot, result;
clrscr();
fflush (stdin);
switch (operator)
{
case '+':
result = n1 + n2;
break;
case '-':
result = n1 - n2;
break;
case '*':
result = n1 * n2;
break;
case '/':
result = n1 / n2;
break;
default :
printf ("Error in operation\n");
246
break;
}
printf ("\n%5.2f %c %5.2f= %5.2f\n", n1,operator, n2, result);
Output:
RUN2
Simulation of Simple Calculator
RUN3
Simulation of Simple Calculator
RUN4
Simulation of Simple Calculator
57. Program to find the GCD and LCM of two integers output the results along with
the given integers. Use Euclids' algorithm.
#include <stdio.h>
main()
{
int num1, num2, gcd, lcm, remainder, numerator, denominator;
clrscr();
247
denominator = num2;
}
else
{
numerator = num2;
denominator = num1;
}
remainder = num1 % num2;
while(remainder !=0)
{
numerator = denominator;
denominator = remainder;
remainder = numerator % denominator;
}
gcd = denominator;
lcm = num1 * num2 / gcd;
printf("GCD of %d and %d = %d \n", num1,num2,gcd);
printf("LCM of %d and %d = %d \n", num1,num2,lcm);
}
Output:
RUN 1
Enter two numbers: 5 15
GCD of 5 and 15 = 5
LCM of 5 and 15 = 15
58. Program to find the sum of odd numbers and sum of even numbers from 1 to N.
Output the computed sums on two different lines with suitable headings.
#include <stdio.h>
main()
{
int i, N, oddSum = 0, evenSum = 0;
clrscr();
Output:
RUN1
Enter the value of N: 10
Sum of all odd numbers = 25
248
Sum of all even numbers = 30
RUN2
Enter the value of N: 50
Sum of all odd numbers = 625
Sum of all even numbers = 650
59. Program to check whether a given number is prime or not and output the given
number with suitable message.
#include <stdio.h>
#include <stdlib.h>
main()
{
int num, j, flag;
clrscr();
flag = 0;
for ( j=2; j<= num/2; j++)
{
if( ( num % j ) == 0)
{
flag = 1;
break;
}
}
if(flag == 0)
printf("%d is a prime number\n",num);
else
printf("%d is not a prime number\n", num);
}
Output:
RUN 1
Enter a number: 34
34 is not a prime number
RUN 2
Enter a number: 29
29 is a prime number
249
60. Program to generate and print prime numbers in a given range. Also print the
number of prime numbers.
#include <stdio.h>
#include <math.h>
main()
{
int M, N, i, j, flag, temp, count = 0;
clrscr();
if(N < 2)
{
printf("There are no primes upto %d\n", N);
exit(0);
}
printf("Prime numbers are\n");
temp = M;
if ( M % 2 == 0)
{
M++;
}
for (i=M; i<=N; i=i+2)
{
flag = 0;
Output:
250
29
31
37
41
43
Number of primes between 15 and 45 = 8
61. Program to read N integers (zero, +ve and -ve) into an array A and to
#include <stdio.h>
#define MAXSIZE 10
main()
{
int array[MAXSIZE];
int i, N, negsum=0, posum=0, count1=0, count2=0;
float total=0.0, averg;
clrscr();
printf ("Enter the value of N\n");
scanf("%d", &N);
/* Summing begins */
for(i=0; i< N ; i++)
{
if(array[i] < 0)
{
negsum = negsum + array[i];
}
else if(array[i] > 0)
{
posum = posum + array[i];
}
else if( array[i] == 0)
{
;
}
251
total = total + array[i] ;
}
averg = total / N;
printf("\nSum of all negative numbers = %d\n",negsum);
printf("Sum of all positive numbers = %d\n", posum);
printf("\nAverage of all input numbers = %.2f\n", averg);
Output:
62. Program to sort N numbers in ascending order using Bubble sort and print both
the given and the sorted array with suitable headings.
#include <stdio.h>
#define MAXSIZE 10
main()
{
int array[MAXSIZE];
int i, j, N, temp;
clrscr();
252
printf("%d\n",array[i]);
}
/* Bubble sorting begins */
for(i=0; i< N ; i++)
{
for(j=0; j< (N-i-1) ; j++)
{
if(array[j] > array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
printf("Sorted array is...\n");
for(i=0; i<N ; i++)
{
printf("%d\n",array[i]);
}
}
Output:
Input array is
390
234
111
876
345
63. Program to accept N numbers sorted in ascending order and to search for a given
number using binary search. Report success or failure in the form of suitable messages.
#include <stdio.h>
main()
{
int array[10];
int i, j, N, temp, keynum, ascending = 0;
int low,mid,high;
253
clrscr();
254
Output:
SUCCESSFUL SEARCH
64. Program read a sentence and count the number of number of vowels and
consonants in the given sentence. Output the results on two lines with suitable headings.
#include <stdio.h>
main()
{
char sentence[80];
int i, vowels=0, consonants=0, special = 0;
clrscr();
printf("Enter a sentence\n");
gets(sentence);
255
}
}
consonants = consonants - special;
printf("No. of vowels in %s = %d\n", sentence, vowels);
printf("No. of consonants in %s = %d\n", sentence, consonants);
}
Output:
Enter a sentence
Good Morning
256
IMPORTANT REVIEW QUESTIONS
getchar() gets()
Used to receive a single character. Used to receive a single string, white
spaces and blanks.
Does not require any argument. It requires a single argument.
scanf() gets()
Strings with spaces cannot be accessed Strings with any number of spaces can
until ENTER key is pressed. be accessed.
Only character data type can be
All data types can be accessed.
accessed.
Spaces and tabs are not acceptable as a Spaces and tabs are perfectly acceptable
part of the input string. of the input string as a part.
Only one string can be received at a
Any number of characters, integers. time. Strings, floats can be received at a
time.
puts() printf()
They can display only one string at a They can display any number of
time. characters, integers or strings a time.
All data types of considered as Each data type is considered separately
characters. depending upon the conversion
specifications.
4. What is the difference between a pre increment and a post increment operation?
Break Continue
Used to terminate the loops or to exist Used to transfer the control to the start
loop from a switch. of loop.
The break statement when executed The continue statement when executed
causes immediate termination of loop cause immediate termination of the
containing it. current iteration of the loop.
6. Distinguish between while and do-while loops.
8. State the differences between the function prototype the function definition
Iteration Recursion
Iteration explicitly user a repetition Recursion achieves repetition through
structure. repeated function calls.
Iteration terminates when the loop Recursion terminates when a base case
continuation. is recognized.
Recursion keeps producing simple
Iteration keeps modifying the counter
versions of the original problem until the
until the loop continuation condition fails.
base case is reached.
Recursion causes another copy of the
Iteration normally occurs within a loop so
function and hence a considerable
the extra memory assigned is omitted.
memory space’s occupied.
It reduces the processor’s operating It increases the processor’s operating
time. time.
10. State the uses of pointers.
11. What is the difference between the address stored in a pointer and a value at the
address?
The address stored in the pointer is the address of another variable. The value stored at
that address is a stored in a different variable. The indirection operator (*) returns the
value stored at the address, which itself is stored in a pointer.
12. What is the difference between the indirection operator and the address of operator?
The indirection operator (*) returns the value of the address stored in a pointer. The
address of operator (&) returns the memory address of the variable.
13. State the difference between call by value and call by reference.
int a; int a;
Formal parameter ‘a’ is a local variable. Formal parameter is ‘a’ local reference.
It cannot change the actual parameter. It can change the actual parameter.
Actual parameter may be a constant, a
Actual parameter must be a variable.
variable, or an expression.
Arrays Structures
A array is an single entity representing a A structure is a single entity representing
collection of data items of same data a collection of data items of different
types. data types.
Individual entries in an array are called Individual entries in a structure are
elements. called members.
An array declaration reserves enough The structure definition reserves enough
memory space for its elements. memory space for its members.
There is no keyword to represent arrays The keyword struct tells us that we can
but the square braces [] preceding the dealing with structures.
variable name tells us that we are
dealing with arrays.
Initialization of elements can be done Initialization of members can be done
during array declaration. only during structure definition.
The elements of an array are stored in The members of a structure are not
sequence of memory locations. stored in sequence of memory locations.
The array elements are accessed by its The members of a structure are accessed
followed by the square braces [] within by the dot operator.
which the index is placed.
Its general format is data type variable Its general format is:
name [size]; struct <struct name>
{
data_type structure member 1;
data_type structure member 2;
.
.
.
data_type structure member N;
} structure variable;
Example: Example:
int sum [100]; struct student
{
char studname [25];
int rollno;
} stud1;
Structures Unions
Each member in a structure occupies and All the members of a union use the same
uses its own memory space memory space
The keyword struct tells us that we are The keyword union tells us that we are
dealing with structures dealing with unions
All the members of a structure can be Only the first member of an union can be
initialized initialized
More memory space is required since Less memory space is required since all
each member is stored in a separate members are stored int eh same memory
memory locations locations
Its general format is: Its general formula is:
struct <struct Name> union <union Name>
{ {
data_type structure Member1; data_type structure Member1;
data_type structure Member2; data_type structure Member2;
. .
. .
data_type structure Member N; data_type structure Member N;
} structure variable; } union variable;
Example: Example:
struct student union student
{ {
char studname[25]; char studname[25];
int rollno; int rollno;
} stud1; } stud1;
17. Advantages of functions:
1. Function makes the lengthy and complex program easy and in short forms. It
means large program can be sub-divided into self-contained and convenient small
modules having unique name.
3. By using function, memory space can be properly utilized. Also less memory is
required to run program if function is used.
5. Function increases the execution speed of the program and makes the
programming simple.
8. Debugging (removing error) becomes very easier and fast using the function sub-
programming.
11. User can build a customized library of different functions used in daily routine
having specific goal and link with the main program similar to the library
functions.
18. A complete summarized table to represent the lifetime and visibility (scope) of all the
storage class specifier is as below: