Additional Lecture Notes CP - 0
Additional Lecture Notes CP - 0
ON
COMPUTER PROGRAMMING
(USING C)
Revision 1.0
1 December, 2014
PROF B. PADMAJA
Associate Professor
Department of Computer Science and Engineering
2014 - 2015
1. INTRODUCTION TO COMPUTERS
1.1 INTRODUCTION TO COMPUTERS
A Computer is an electronic device that can perform activities that involve Mathematical, Logical and
graphical manipulations. Generally, the term is used to describe a collection of devices that function
together as a system.
It performs the following three operations in sequence.
1. It receives data & instructions from the input device.
2. Processes the data as per instructions.
3. Provides the result (output) in a desired form.
1.1.1 Basic Elements of a Computer System:
Basic elements of a computer system are Mouse, Keyboard, monitor, memory, CPU, motherboard, Hard
Disk, Speakers, Modem, power supply and processor.
Mouse: Mouse is used for operating the system. Nowadays, optical mouse is more popular
as compared to simple mouse.
Keyboard: Keyboard is used to input data in to the system so that the system gives output to the
user. Therefore, the keyboard is an integral part of the input system. A computer is
essentially incomplete without a keyboard.
Monitor: Monitor, which again is a very essential part of the computer system, displays the
actions that the computer performs on our command.
Motherboard: Motherboard again a necessary element of the computer system contains different
elements as memory, processor, modem, slots for graphic card and LAN card.
Hard Disk: Hard disk is used to store data permanently on computer.
Modem: Modem is used to connecting to the Internet. Two types of modems are widely used.
One is known as software modems and the other is known as hardware modems.
Speakers: Speakers are also included in basic elements of a computer. It is not indispensible,
because a computer can perform its function without speakers. However, we use
them to for multiple purposes.
1.1.2 Basic Computer Functioning
A computer can be defined as an electronic device that accepts data from an input device, processes it,
stores it in a disk and finally displays it on an output device such as a monitor. To understand the basic
rudiments of the functioning of the computer refer to the basic block diagram of a computer as shown
.This flow of information holds true for all types of computers such as Personal Computers, Laptops,
Palmtops etc. In other words, the fundamental principle of working is the same.
4. Now, Click on File->New. Please find image below for your reference.
5. Write your C Program. Press F2 (or File->Save) to save your program. On pressing F2, pop window
will open (as shown below). You need to specify the name of the program. For C Program, use .C as
extension.
6. To compile a C Program you can either press Alt+F9 or Compile->Compile. After you compile your
C Program you will see the following screen.
7. To run a C Program you can either press Ctrl+F9 or Run->Run. After you run your C Program you
will see the output screen as shown below.
2. INTRODUCTION TO C LANGUAGE
BRIEF HISTORY OF DENNIS MACALISTAIR RITCHIE - FATHER OF C AND UNIX
Dennis MacAlistair Ritchie (1941 - 2011) was an American Computer
Scientist also popularly known as dmr is best known as the creator of
the C Programming Language and co-creator of UNIX along with his
colleague Ken Thompson at Bell Laboratories.
Education:
1. Harvard University, Bachelor's degrees in physics and applied
mathematics, 1963
2. Harvard University, PhD, 1968
Today, C remains the second most popular programming language in the
world.
2.1 BRIEF HISTORY OF C PROGRAMMING LANGUAGE
1. C was developed at Bell Laboratories in 1972 by Dennis Ritchie.
2. C is a general-purpose computer programming language and was the descendent of CPL
(Combined Programming Language and BCPL (Basic CPL).
3. Dennis Ritchie wrote the improved and portable version named C that could run on any
machine.
4. By virtue of C's portability, UNIX was rewritten in 1973 was also a portable operating
system that could work on different computers.
2.1.1 Significant Features of C Language
1. C is a powerful, flexible language that provides fast program execution.
2. C is a Procedural Language i.e. the programmer is required to provide step-by-step
instructions for the CPU (central processing unit).
3. The success of C is due to its simplicity, efficiency, flexibility and
small memory requirements.
4. Low Level features: C's power and fast program execution come from its ability to
access low level commands, similar to assembly language, but with high level syntax.
5. Portability: C programs are portable i.e. they can run on any compiler with little or no
modification. Compiler and Preprocessor makes it possible for C program to run it on
different PC.
6. Bit Manipulation: C Programs can be manipulated using bits and it provides wide
variety of bit manipulation operators.
7. Modular Programming: It is a software design technique that increases the extent to
which software is composed of separate parts, called modules. C program consist of
different modules that are integrated together to form a complete program.
8. Efficient Usage of Pointers: C supports efficient use of pointers and pointers has direct
access to memory.
9. Standard Library Concept:
10. Powerful and varied repertoire of Operators
11. Elegant Syntax:
12. Ready Access to Hardware when needed:
13. Structured Programming Language: C supports
2.1.2 Areas of Application
The C programming language is used in many different areas of application, but the most prolific
area is UNIX operating system applications.
Computer Games
System level Programming making Operating System Assemblers, Compilers,
Interpreter, Cross-Compilers, Text Editors, and Device Drivers.
Application Development e.g. making Reservation System, Library System, Inventory
Control System etc.
Writing Embedded Software/firmware for various electronics, industrial and
communication products.
Used in developing verification software, test code, and simulators for various
applications and hardware products.
2.2 BASIC STRUCTURE OF C LANGUAGE
Documentation Section (Optional) The documentations section consists of comment lines
giving the name of the program, the author and other
details which the programmer would like to use later.
Single Line Comment: // This is a sample program
Multiple Line Comment: \* This is a sample Program*\
Preprocessor Statements The preprocessor statements begin with # symbol and are
also called the preprocessor directive. These statements
instruct the compiler to include C preprocessors such as
header files and symbolic constants or macros before
compiling the C program.
e.g.
# include<stdio.h>
Header Files
# include<conio.h>
# define PI 3.142
Symbolic Constants
# define MAX 100
Global Declaration The variables are declared before the main () functions as
Section(Optional) well as user defined functions are called global variables.
main() Function Section (must) The C program execution starts with main() function.
The main() function should be written in small
(lowercase) letters and it should not be terminated by
semicolon.
Syntax:
main()
{
Local Declarations;
Processing Statements;
}
User Defined Functions (Optional) This section contains all the user defined functions that
are called in the main() function. User defined functions
are generally placed immediately before /after the main
function.
2.3 C TOKENS
C Tokens
A token is the basic building block of a C program which can be recognized by the compiler.
2.3.1 Identifier
An identifier is used to give a name to an object. An identifier refers to the names of variables,
constants, functions, arrays, types (typedefs, structs, unions, enums), type members and macros
etc. These are user-defined names and consist of sequence of letters and digits, with a letter or
underscore as a first character. Both uppercase and lowercase letters are permitted.
Rules for Identifiers:
1. First character must be an alphabet or underscore.
2. Identifier names must consist of only letters, digits or underscore.
3. It must not be a keyword.
4. It must not contain white space, operators and special characters.
5. There is no rule for the length of an identifier.
6. The first 31 characters of an identifier are discriminated by the compiler.
2.3.2 Constants
A constant is a quantity that doesnt change. There are mainly to types of constants.
1. Numeric Constants
a. Integer Constants e.g. 5, 9, 35
b. Floating Point Constants e.g. 5.25,0.22E-5, -2.0
2. Non numeric or Character Constants
a. Single Character Constants e.g. a,x,p
b. String Constants e.g. hello, sample,good
2.3.3 Keywords
These are reserved words used in programming. Each keyword has fixed meaning and that
cannot be changed by user.
e.g. int n;
Here int is keyword and it indicates n is of type integer.
Here is the list of all keywords predefined by ANSI C.
Standard Keywords in C Language:
Keywords used while declaring variables int
char
float
double
long
short
signed
unsigned
volatile
void
const
Control flow related Keywords if
else
switch
case
default
do
while
for
return
break
continue
goto
Storage classes related Keywords auto
static
register
extern
User defined data type related Keywords enum
typedef
struct
union
Special operator related Keyword sizeof
2.4 OPERATORS
An operator is used to describe an operation applied to one or several objects.
1. Arithmetic Operators
2. Increment and Decrement Operators
3. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Conditional operators
7. Bitwise Operators
8. Special Operators
Arithmetic Operators:
Operator Meaning of Operator
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Remainder after division (modulo division)
Increment and Decrement Operators:
Operator Meaning of Operator
++ Increment operator (unary)
a++; //post increment
++a; //pre increment
-- Decrement operator (unary)
a--; //post decrement
--a; //pre decrement
Assignment Operators:
There are two types of assignment operators.
1. Simple Assignment
2. Compound Assignment
Reading and writing Characters: 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:
# 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;
}
There are two important variations on getche().
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.
A second, more useful, variation on getche() is getch(), which operates precisely like
getche () except that the character you type is not echoed to the screen. It uses the
CONIO.H header.
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.
# 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.
int puts (char str);
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 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:
printf() function
#include <stdio.h>
main()
{
int dec = 5;
char str[] = "abc";
char ch = 's';
float pi = 3.14;
5 abc 3.140000 c
Here %d is being used to print an integer, %s is being usedto print a string, %f is being used to
print a float and %c is being used to print a character.
scanf() function
This is the function which can be used to to read an input from the command line.
#include <stdio.h>
main()
{
int x;
int args;
Here %d is being used to read an integer value and we are passing &x to store the vale read
input. Here &indicates the address of variable x.
This program will prompt you to enter a value. Whatever value you will enter at command
prompt that will be output at the screen using printf() function. If you enter a non-integer value
then it will display an error message.
Enter an integer: 20
Read in 20
Questions on Variables, Constant, Data Types, Arithmetic Expressions, Input & Output
Functions:
Q1) What is input function?
Ans: It is used to read values from input device.
Q2) What is output function?
Ans: It is used to display output of a program.
Q3) What is a Variable?
Ans: A variable is a data name that is used to store a value.
Q4) What is Constant?
Ans: Constant is a fixed values that do not change during the execution of a program.
Q5) What is data type?
Ans: This indicates type of data.
Q6) What are the rules to define a variable?
Ans:
It must begin with a letter, or with underscore.
It must not be a keyword.
It must not contain white space or special characters.
It can have digits at middle or end.
Q7) Give few examples for valid variable names?
Ans: T_raise, delhi, x1, ph_value, mark, sum1, distance
Q8) Is char a valid variable name?
Ans: No, char is a keyword
Q9) Is price$ a valid variable name?
Ans: NOT VALID, dollar sign is illegal.
Q10) Is 'group one' a valid variable name?
Ans: NOT VALID blank space not permitted.
Q11) Is int_type a valid variable name?
Ans: Valid, keyword may be a part of a name.
Q12) What are the data types that ANSI c supports?
Ans: ANSI c supports three classes of data types .they are
1. Primary (or fundamental/ primitive)data type
2. Derived data types
3. User defined data types.
Q13) What are primary data types?
Ans : char , int , long , float & double.
Q14) What are derived data types?
Ans : Array , pointer.
Q15) What are user defined data types.
Ans : Structure, union and enum.
Q16) What is the size and range of the basic data types?
Ans: The size and range of the basic data types are:
Data Type size (bytes) range
int 21 -32,768 to +32767
long int 4 -231 to 231-1
char 1 -128 to +127
float 4 3.4e-38 to 3.4e+38
double 8 1.7e-308to1.7e+308
Q17) What is the size and range of short int(or)signed short int, long int (or)signed long int?
Ans:
Data Type size (bytes) range
Short int or signed short int 2 -215 to +215-1
Long int or signed long int 4 -231 to +231-1
Q18) How many types of constants exist in C?
Ans: C has two types of constants. Those are
1. Numeric constants
2. Character constants
Q19) How many types of numeric constants exist in C?
Ans: There are two types of numeric constants. They are:
1. Integer constants
2. Real constants
Q20) How many types of character constants exist in?
Ans: There are two types of character constants. Those are
1. Single character constants
2. String constants
Q21) Is embedded spaces, commas and non digit characters are permitted between decimal
integer constants?
Ans: No, embedded spaces, commas and non digit characters are NOT permitted between
decimal integer constants.
Q22) Is '20,000' a valid decimal integer constant?
Ans: Not valid
Q23) Give few examples of octal integer constants?
Ans: 037, 0435, 0551
Q24) Give few examples of hexa decimal integer constants?
Ans: 0x2, 0x9f, 0xbcd, ox1234.
Q25) Give few examples of real type constants?
Ans: 0.0083,-.75,435.36,+247.008
Q26) Give few examples of single character type constant?
Ans: '5', 'x', ';'
Q27) Give few examples of string constant?
Ans: rana, 123, seetha123. Rama Rao
Q28) What are the basic escape sequence characters & meaning ?
Ans: \a - --- alarm
\b ----- BackSpace
\f ---- form feed
\n ---- newline
\r ---- carriage Return
\t ---- tab
\v ---- vertical Tab
Q29) What is an integer expression?
Ans: When both the operands in an expression are integers then the expression is known as an
integer expression.
Q30) Let a=14, b=4 what will be the output for the following
a) a-b b) a+b c) a*b d) a/b e) a%b
Ans: a) 10 b) 18 c) 56 d) 3 e) 2
Q31) When an expression is called mixed mode arithmetic?
Ans: When one of the operands is real and the other is integer, the expression is called mixed
mode arithmetic.
Q32) What will be the value of c,d,e & f in the below code.
float c=15/10.0 & int d=15/10;
float e = 15/10 and float f= 15.0/10.0;
Ans: c = 1.5 d=1 e = 1.0, f = 1.5.
Output Prediction:
1. What will be the output of the following program:
int main()
{
printf("%%",7);
return(0);
}
2. What will be the output of the following program :
int main()
{
printf("//",5);
return(0);
}
30. What will be the output of the following program [NOTE : 3 values entered by the user
are:100 200 300] :
int main()
{
int a=1,b=2,c=3;
scanf("%d %*d %d",&a,&b,&c);
printf("a=%d b=%d c=%d",a,b,c);
return(0);
}
31. What will be the output of the following program [NOTE : THE USER INPUT IS:Dear
Friends, What is the output?] :
int main()
{
char line[80]; // Max. length=80 Chars
scanf("%[^,]s",line);
printf("\n%s",line);
return(0);
}
32. What will be the output of the following program [NOTE : THE USER INPUT IS :A B
C] :
int main()
{
char a,b,c;
scanf("%c%c%c",&a,&b,&c);
printf("a=%c b=%c c=%c",a,b,c);
return(0);
}
33. What will be the output of the following program [NOTE : THE USER INPUT IS:5 5.75]
:
void main()
{
int i=1;
float f=2.25;
scanf("%d a %f",&i,&f);
printf("%d %.2f",i,f);
}
34. What will be the output of the following program [NOTE : THE USER INPUT IS :ABC
DEF GHI] :
int main()
{
char a,b,c;
scanf("%c %c %c",&a,&b,&c);
printf("a=%c b=%c c=%c",a,b,c);
return(0);
}
35. What will be the output of the following program [NOTE : THE USER INPUT
IS:CMeansSea Ocean Vast] :
int main()
{
char a[80],b[80],c[80];
scanf("%1s %5s %3s",a,b,c);
printf("%s %s %s",a,b,c);
return(0);
}
36. What will be the output of the following program [NOTE : THE USER INPUT IS
:123456 44 544] :
int main()
{
int a,b,c;
scanf("%1d %2d %3d",&a,&b,&c);
printf("Sum=%d",a+b+c);
return(0);
}
If the test expression is true then, statements for the body if, i.e, statements inside parenthesis are
executed. But, if the test expression is false, the execution of the statements for the body of if
statements are skipped.
e.g.
int main()
{
int a=40,b=40;
if (a == b)
{
printf("a and b are equal");
}
}
Output: a and b are equal
Flowchart of if Statement
if...else Statement
The if...else statement is used, if the programmer wants to execute some code, if the test
expression is true and execute some other code if the test expression is false.
Syntax:
if (test expression)
{
statements to be executed if test expression is true;
}
else
{
statements to be executed if test expression is false;
}
e.g.
int main()
{
int a=40,b=20;
if (a == b)
{
printf("a and b are equal");
}
else
{
printf("a and b are not equal");
}
}
Output: a and b are not equal
}
The following rules apply to a switch statement:
The expression used in a switch statement must have an integral or enumerated type, or
be of a class type in which the class has a single conversion function to an integral or
enumerated type.
You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases is
true. No break is needed in the default case.
e.g.
#include <stdio.h>
int main ()
{
char grade = 'B';
switch(grade)
{
case 'A' : printf("Excellent!\n" ); break;
case 'B' :
case 'C' : printf("Well done\n" ); break;
case 'D' : printf("You passed\n" ); break;
case 'F' : printf("Better try again\n" ); break;
default : printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
Output:
Well done
Your grade is B
Flowchart for switch case Statement:
3.2 LOOPING STATEMENTS / ITERATIVE STATEMENTS
'A loop' is a part of code of a program which is executed repeatedly.
A loop is used using condition. The repetition is done until condition becomes condition true.
A loop declaration and execution can be done in following ways.
1. Check condition to start a loop
2. Initialize loop with declaring a variable.
3. Executing statements inside loop.
4. Increment or decrement of value of a variable.
3.2.1 Types of looping statements
Basically, the types of looping statements depend on the condition checking mode. Condition
checking can be made in two ways as: Before loop and after loop. So, there are 2(two) types of
looping statements.
Entry controlled loop
Exit controlled loop
1. Entry controlled loop :
In such type of loop, the test condition is checked first before the loop is executed.
Some common examples of this looping statements are :
1. while loop
2. for loop
2. Exit controlled loop :
In such type of loop, the loop is executed first. Then condition is checked after block of
statements are executed. The loop executed at least one time.
Some common example of this looping statement is :
1. do-while loop
while loop Statement
Repeats a statement or group of statements while a given condition is true. It tests the condition
before executing the loop body.
Syntax:
while( test condition)
{
statement(s);
}
In the beginning of while loop, test expression is checked. If it is true, codes inside the body of
while loop, i. e., code/s inside parentheses are executed and again the test expression is checked
and process continues until the test expression becomes false.
e.g.
/*C program to demonstrate the working of while loop*/
#include <stdio.h>
int main()
{
int n,fact;
printf("Enter a number: \n");
scanf("%d",&n);
fact=1;
while (n > 0)
{ /* while loop continues until test condition n > 0 is true */
fact=fact*n;
--n;
}
printf("Factorial=%d", fact);
return 0;
}
Output:
Enter a number: 5
Factorial=120
do{
printf("Hello %d\n", i );
i = i -1;
}while ( i > 0 );
}
Output:
Hello 5
Hello 4
Hello 3
Hello 2
Hello 1
Flowchart for dowhile loop
for(i=1;i<6;i++)
{
printf("%d\n",i);
}
}
Output:
1
2
3
4
5
Flowchart for for loop
3.3 SPECIAL CONTROL STATEMENTS: BREAK , CONTINUE, RETURN AND GOTO
STATEMENTS
C provides two commands to control how we loop:
break -- exit form loop or switch.
continue -- skip 1 iteration of loop.
The execution of break statement causes immediate exit from the concern construct and the
control is transferred to the statement following the loop.
Execution of continue statement does not cause an exit from the loop but it suspend the
execution of the loop for that iteration and transfer control back to the loop for the next iteration.
e.g. for break statement:
#include <stdio.h>
int main ()
{
int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
break;
}
}
return 0;
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
return statement
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 no value is specified, 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 should not return a value. But it may contain a simple return statement(i.e.
return;
goto statement:
goto statement provides a method of unconditional transfer control to a labeled point in the program.
The goto statement requires a destination label declared as:
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:
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, its a convenience, it used wisely, can be a benefit in a narrow set of programming
situations. So the usage of goto is highly discouraged.
Example:
void main()
{
int x, y, z;
printf(\n Enter the value of x and y);
scanf(%d%d, &x, &y);
if( y == 0 )
goto ERROR;
else
printf( \n Div = %d,x/y)
ERROR :
Printf(\n Divide by zero error );
The compiler doesnt require any formal declaration of the label identifiers.
MULTIPLE CHOICE QUESTIONS
1) What will be the output of the following program :
void main()
{
int i=1;
for (; i<4; i++);
printf("%d\n",i);
}
a.No Output b. 1 c. 4 d. None of these
2
3
}
a. 4 3 3 4 b. 4 3 3 2 c. 4 32 3 d. 4 33 1
}
a. 4 32 3 b. 4 33 42 3 c. 4 3 3 4 2 3 d. None of these
switch(choice)
{
default:
printf("Default");
case 1:
printf("Choice1");
break;
case 2:
printf("Choice2");
break;
}
}
a. No Output b. Default c. DefaultChoice1 d. None of these
case 2:
printf("Choice2");
break;
default:
printf("Default");
}
}
a. Choice1 b. Choice2 c. Default d. None of these
OUTPUT PREDICTION
(9) #include<stdio.h>
int main()
{
int i;
for(i=0;i<=5;i++);
printf("%d",i)
return 0;
}
(10) What will be output of following c code?
#include<stdio.h>
int i=40;
extern int i;
int main()
{
do
{
printf("%d",i++);
}while(5,4,3,2,1,0);
return 0;
}
(11) What will be output of following c code?
#include<stdio.h>
int main()
{
int i;
for(i=10;i<=15;i++)
{
while(i)
{
do
{
printf("%d ",1);
if(i>>1)
continue;
}while(0);
break;
}
}
return 0;
}
Before calling and defining a function, we have to declare function prototype in order to inform
the compiler about the function name, function parameters and return value type.
e.g.
#include<stdio.h>
float square ( float x ); // function prototype, also called function declaration
int main( ) // main function, program starts from here
{
float m, n ;
printf ( "\n Enter a number for finding square: ");
scanf ( "%f", &m ) ;
n = square ( m ) ; // function call
printf ( "\nSquare of the given number %f is %f",m,n );
}
float square ( float x ) // function definition
{
float p ;
p=x*x;
return ( p ) ;
}
Output:
Enter a number for finding square: 2
Square of the given number 2.000000 is 4.000000
5.2 TYPES OF FUNCTION
There are 2(two) types of functions as:
1. Built in Functions
2. User Defined Functions
Built in/Library Functions:
There are many inbuilt functions available in C language. We can directly make use of these
inbuilt functions in our C program to get the predefined outputs instead of writing our own
function to get those outputs. In particular, all input and output operations (e.g., writing to the
terminal) and all math operations (e.g., evaluation of sines and cosines) are implemented by
library functions.
In order to use a library function, it is necessary to call the appropriate header file at the
beginning of the program. The header file informs the program of the name, type, and number
and type of arguments, of all of the functions contained in the library in question. A header file is
called via the preprocessor statement.
#include <filename>
where filename represents the name of the header file.
A library function is accessed by simply writing the function name, followed by a list of
arguments, which represent the information being passed to the function. The arguments must
be enclosed in parentheses, and separated by commas: they can be constants, variables, or more
complex expressions. Note that the parentheses must be present even when there are no
arguments.
1. stdio.h: I/O functions:
1. getchar() returns the next character typed on the keyboard.
2. putchar() outputs a single character to the screen.
3. printf() as previously described
4. scanf() as previously described
2. string.h: String functions
1. strcat() concatenates a copy of str2 to str1
2. strcmp() compares two strings
3. strcpy() copies contents of str2 to str1
3. ctype.h: Character functions
1. isdigit() returns non-0 if argument is digit 0 to 9
2. isalpha() returns non-0 if argument is a letter of the alphabet
3. isalnum() returns non-0 if argument is a letter or digit
4. islower() returns non-0 if argument is lowercase letter
5. isupper() returns non-0 if argument is uppercase letter
4. math.h: Mathematics functions
1. acos() returns arc cosine of argument
2. asin() returns arc sine of argument
3. atan() returns arc tangent of argument
4. cos() returns cosine of argument
5. exp() returns natural logarithmic
6. fabs() returns absolute value of num
7. sqrt() returns square root of num
5. time.h: Time and Date functions
1. time() returns current calendar time of system
2. difftime() returns difference in seconds between two times
3. clock() returns number of system clock cycles since program execution
6. stdlib.h: Miscellaneous functions
1. malloc() provides dynamic memory allocation, covered in future sections
2. rand() as already described previously
3. srand() used to set the starting point for rand()
5.3 USER DEFINED FUNCTIONS
C provides programmer to define their own function according to their requirement known as
user defined functions. Suppose, a programmer wants to find factorial of a number and check
whether it is prime or not in same program. Then, he/she can create two separate user-defined
functions in that program: one for finding factorial and other for checking whether it is prime or
not.
Syntax:
#include <stdio.h>
void function_name()
{
................ ................
}
int main()
{
........... ...........
function_name();
........... ...........
}
Every C program begins from main() and program starts executing the codes inside main()
function. When the control of program reaches to function_name() inside main() function. The
control of program jumps to void function_name() and executes the codes inside it. When, all the
codes inside that user-defined function are executed, control of the program jumps to the
statement just after function_name() from where it is called.
e.g.
#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
int main()
{
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
return 0;
}
int add(int a,int b) //function declaratory
{
int add;
add=a+b;
return add; //return statement of function
}
5.3.1 Advantages of User Defined Functions
1. User defined functions helps to decompose the large program into small segments which
makes programmar easy to understand, maintain and debug.
2. If repeated code occurs in a program. Function can be used to include those codes and
execute when needed by calling that function.
3. Programmar working on large project can divide the workload by making different
functions.
5.3.2 Function prototype (declaration)
Every function in C programming should be declared before they are used. This type of
declaration are also called function prototype. Function prototype gives compiler information
about function name, type of arguments to be passed and return type.
Syntax of function prototype
return_type function_name(type(1) argument(1),....,type(n) argument(n));
e.g.
int add(int a, int b); is a function prototype which provides following information to the
compiler:
1. name of the function is add()
2. return type of the function is int.
3. two arguments of type int are passed to function.
Function prototype are not needed if user-definition function is written before main() function.
5.4 CALLING A FUNCTION
There are two ways that a C function can be called from a program. They are,
1. call by value
2. call by reference
5.4.1 call by value
Arguments are passed by value while calling a function in C program.
e.g.
#include<stdio.h>
void swap(int a, int b); // function prototype, also called function declaration
int main()
{
int m = 22, n = 44;
printf(" values before swap m = %d and n = %d", m, n); // calling swap function by value
swap(m, n);
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}
Output:
values before swap m = 22 and n = 44
values after swap m = 44 and n = 22
5.4.2 call by reference
Arguments are passed by address while calling a function in C program.
e.g.
#include<stdio.h>
void swap(int *a, int *b); // function prototype, also called function declaration
int main()
{
int m = 22, n = 44;
printf("values before swap m = %d and n = %d",m,n); // calling swap function by reference
swap(&m, &n);
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d and b = %d", *a, *b);
}
Output:
values before swap m = 22 and n = 44
values after swap a = 44 and b = 22
How many values can be returned from a function at a time?
Only one value can be returned. If you want to return more than one values, pointers can be used.
5.4.3 Advantages of writing functions
1. Modular and Structural Programming can be done: we can divide a program into
smaller modules and we can call a module whenever required. Modular programming
makes a program more readable and it enhances re-useablitity.
2. It follows Top-Down execution approach, so main() can be kept small: Every C
program starts from main() function and every function is called directly or indirectly
through main().
5.5 TYPES OF USER-DEFINED FUNCTIONS
For better understanding of arguments and return in functions, user-defined functions can be
categorized as:
1. Function with no arguments and no return value
2. Function with no arguments and return value
3. Function with arguments but no return value
4. Function with arguments and return value.
Let's take an example to find whether a number is prime or not using above 4 categories of user
defined functions.
5.5.1 Function with no arguments and no return value
/*C program to check whether a number entered by user is prime or not using function with no
arguments and no return value*/
#include <stdio.h>
void prime();
int main()
{
prime(); //No argument is passed to prime().
return 0;
}
void prime()
{
int num,i,flag=0;
printf("Enter positive integer enter to check:\n");
scanf("%d",&num);
for(i=2;i<=num/2;++i)
{
if(num%i==0)
{
flag=1;
}
}
if (flag==1)
printf("%d is not prime",num);
else
printf("%d is prime",num);
}
Function prime() is used for asking user a input, check for whether it is prime of not and display
it accordingly. No argument is passed and returned from prime() function.
5.5.2 Function with no arguments and return value
/*C program to check whether a number entered by user is prime or not using function with no
arguments but having return value */
#include <stdio.h>
int input();
int main()
{
int num,i,flag;
num=input(); /* No argument is passed to input() */
for(i=2,flag=i;i<=num/2;++i,flag=i){
if(num%i==0)
{
printf("%d is not prime",num);
++flag;
break;
}
}
if(flag==i)
printf("%d is prime",num);
return 0;
}
int input()
{
int n;
printf("Enter positive enter to check:\n");
scanf("%d",&n);
return n;
}
There is no argument passed to input() function But, the value of n is returned from input() to
main() function.
5.5.3 Function with arguments but no return value
/*Program to check whether a number entered by user is prime or not using function with
arguments and no return value */
#include <stdio.h>
void check_display(int n);
int main()
{
int num;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
check_display(num); /* Argument num is passed to function. */
return 0;
}
void check_display(int n)
{
int i,flag;
for(i=2,flag=i;i<=n/2;++i,flag=i)
{
if(n%i==0)
{
printf("%d is not prime",n);
++flag;
break;
}
}
if(flag==i)
printf("%d is prime",n);
}
Here, check_display() function is used for check whether it is prime or not and display it
accordingly. Here, argument is passed to user-defined function but, value is not returned from it
to calling function.
5.5.4 Function with arguments and return value
/* Program to check whether a number entered by user is prime or not using function with
argument and return value */
#include <stdio.h>
int check(int n);
int main()
{
int num,num_check=0;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
num_check=check(num); /* Argument num is passed to check() function. */
if(num_check==1)
printf("%d in not prime",num);
else
printf("%d is prime",num);
return 0;
}
int check(int n)
{
int i;
for(i=2;i<=n/2;++i)
{
if(n%i==0)
return 1;
}
return 0;
}
Here, check() function is used for checking whether a number is prime or not. In this program,
input from user is passed to function check() and integer value is returned from it. If input the
number is prime, 0 is returned and if number is not prime, 1 is returned.
5.6 RECURSIVE FUNCTIONS
A function that calls itself is known as recursive function and the process of calling function
itself is known as recursion in C programming.
e.g. Write a C program to find sum of first n natural numbers using recursion. Note: Positive
integers are known as natural number i.e. 1, 2, 3....n
#include <stdio.h>
int sum(int n);
int main()
{
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}
int sum(int n)
{
if(n==0)
return n;
else
return n+sum(n-1); /*self call to function sum() */
}
Output:
Enter a positive integer:5
15
In, this program, sum() function is invoked from the same function. If n is not equal to 0 then,
the function calls itself passing argument 1 less than the previous argument it was called with.
Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function and the value of
argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is
returned which is the sum numbers from 5 to 1.
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Every recursive function must be provided with a way to end the recursion i.e. called the
stopping case or base case.. In this example when, n is equal to 0, there is no recursive call and
recursion ends.
5.6.1 Recursion Versus Iteration
In iteration repetition structure is explicitly used whereas in recursion the same function is
invoked by itself. Both recursion and iteration go through the termination test. Iteration
terminates when the loop continuation condition fails. The recursion also terminates when the
test for termination is satisfied. Both iteration and recursion can be executed infinitely. When
recursion and iteration are defined without termination condition, they turn to infinite loop.
Recursion has several overheads. Each time a function is executed, a new copy of function is
created. Memory is occupied by the functions. In iteration only once the variable is created.
Thus, iteration is very useful and efficient as compared to recursion. However, there are a few
problems that cannot be solved with iteration, and recursion perfectly works.
5.6.2 Rules for Recursive Function
1. In recursion, it is essential to call a function itself, otherwise recursion would not take
place.
2. Only the user-defined function can be involved in the recursion. Library function cannot
be involved in recursion because their source code cannot be viewed.
3. A recursive function can be invoked by itself or by other function. It saves return address
with the intention to return at proper location when return to a calling statement is made.
The last-in-first-out nature of recursion indicates that stack data structure can be used to
implement it.
4. Recursion is turning out to be increasingly important in non-numeric applications and
symbolic manipulations.
5. To stop the recursive function, it is necessary to base the recursion on test condition, and
proper terminating statement such as exit() or return must be written .
5.6.3 Direct Versus Indirect Recursion
In direct recursion, only one function is involved which calls itself until the given condition is
true.
In Indirect recursion, two or more functions are involved in the recursion. The indirect recursion
does not make any overhead as direct recursion. When control exits from one function and enter
into another function, the local variables of former function are destroyed. Hence, memory is not
engaged.
5.6.4 Advantages and Disadvantages of Recursion
Advantages:
1. Recursion is more elegant and requires few variables which make program clean.
2. Recursion can be used to replace complex nesting code by dividing the problem into
same problem of its sub-type.
3. Using recursion, the length of the program can be reduced.
Disadvantages:
1. It requires extra storage space. The recursive calls and automatic variables are stored on
the stack. For every recursive calls separate memory is allocated to automatic variables
with the same name.
2. The recursion function is not efficient in execution speed and time.
5.7 STORAGE CLASS
Every variable and function in C programming has two properties: type and storage class. Type
refers to the data type of variable whether it is character or integer or floating-point value etc.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register
5.7.1 Automatic storage class (Keyword: auto)
Variables declared inside the function body are automatic by default. These variable are also
known as local variables as they are local to the function and doesn't have meaning outside that
function
Since, variable inside a function is automatic by default, keyword auto are rarely used.
5.7.2 External storage class
External variable can be accessed by any function. They are also known as global variables.
Variables declared outside every function are external variables.
In case of large program, containing more than one file, if the global variable is declared in file 1
and that variable is used in file 2 then, compiler will show error. To solve this problem, keyword
extern is used in file 2 to indicate that, the variable specified is global variable and declared in
another file.
e.g.
#include<stdio.h>
void Check();
int a=5; /* a is global variable because it is outside every function */
int main()
{
a+=4;
Check();
return 0;
}
void Check()
{
++a; /* Variable a is not declared in this function but, works in any function as they are global
variable */
printf("a=%d\n",a);
}
Output:
a=10
5.7.3 Register Storage Class
Register variables are similar to automatic variable and exists inside that particular function only.
If the compiler encounters register variable, it tries to store variable in microprocessor's register
rather than memory. Values stored in register are much faster than that of memory.
In case of larger program, variables that are used in loops and function parameters are declared
register variables.
Since, there are limited number of register in processor and if it couldn't store the variable in
register, it will automatically store it in memory.
5.7.4 Static Storage Class (Keyword: static)
The value of static variable persists until the end of the program. A variable can be declared
static using keyword: static. For example:
static int i;
Here, i is a static variable.
#include <stdio.h>
void Check();
int main()
{
Check();
Check();
Check();
}
void Check(){
static int c=0;
printf("%d\t",c);
c+=5;
}
Output:
0 5 10
During first function call, it will display 0. Then, during second function call, variable c will not
be initialized to 0 again, as it is static variable. So, 5 is displayed in second function call and 10
in third call.
If variable c had been automatic variable, the output would have been:
0 0 0
Function Examples:
/*C program to find the factorial of a number*/
#include <stdio.h>
long factorial(int);
int main()
{
int number;
long fact = 1;
printf("Enter a number to calculate it's factorial\n");
scanf("%d", &number);
printf("%d! = %ld\n", number, factorial(number));
return 0;
}
long factorial(int n)
{
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result * c;
return result;
}
Output:
Enter a number to calculate it's factorial
7
7! = 5040
Program to Display Prime Numbers between Intervals
This program takes two positive integers from user and displays all prime numbers between
these two intervals. To perform this task, user-defined function is created which will check
whether a number is prime or not.
#include<stdio.h>
int check_prime(int num);
int main()
{
int n1,n2,i,flag;
printf("Enter two numbers(intervals): ");
scanf("%d %d",&n1, &n2);
printf("Prime numbers between %3d and %3d are: ", n1, n2);
for(i=n1+1;i<n2;++i)
{
flag=check_prime(i);
if(flag==0)
printf("%d ",i);
}
return 0;
}
int check_prime(int num) /* User-defined function to check prime number*/
{
int j,flag=0;
for(j=2;j<=num/2;++j)
{
if(num%j==0)
{
flag=1;
break;
}
}
return flag;
}
Output:
Enter two numbers(intervals): 10
50
Prime numbers between 10 and 50 are: 11 13 17 19 23 29 31 37 41 43 47
Program to Check Whether a Number can be expressed as Sum of Two Prime Numbers
This program takes a positive integer from user and checks whether that number can be
expressed as the sum of two prime numbers. If that number can be expressed as sum of two
prime numbers then, that number is expressed as sum of two prime numbers in output. To
perform this task, a user-defined function is created to check prime number.
#include <stdio.h>
int prime(int n);
int main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i<=n/2; ++i)
{
if (prime(i)!=0)
{
if ( prime(n-i)!=0)
{
printf("%d = %d + %d\n", n, i, n-i);
flag=1;
}
}
}
if (flag==0)
printf("%d can't be expressed as sum of two prime numbers.",n);
return 0;
}
int prime(int n) /* Function to check prime number */
{
int i, flag=1;
for(i=2; i<=n/2; ++i)
if(n%i==0)
flag=0;
return flag;
}
Enter a positive integer: 100
100 = 3 + 97
100 = 11 + 89
100 = 17 + 83
100 = 29 + 71
100 = 41 + 59
100 = 47 + 53
Program to Check Prime and Armstrong Number by Making Function
In this program, user is asked to enter a positive integer and a character either 'p' or 'a'. If user
enters p then, this program checks whether that number is prime or not and if user enters a then,
this program checks whether that number is an Armstrong number or not. To perform this task,
two user-defined functions are defined to check prime number and Armstrong number.
/* C program to check either prime number or Armstrong number depending upon the data
entered by user. */
#include <stdio.h>
#include<conio.h>
int prime(int n);
int armstrong(int n);
int main()
{
char c;
int n,temp=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Enter P to check prime and A to check Armstrong number: ");
c=getche();
if (c=='p' || c=='P')
{
temp=prime(n);
if(temp==1)
printf("\n%d is a prime number.", n);
else
printf("\n%d is not a prime number.", n);
}
if (c=='a' || c=='A')
{
temp=armstrong(n);
if(temp==1)
printf("\n%d is an Armstrong number.", n);
else
printf("\n%d is not an Armstrong number.",n);
}
return 0;
}
int prime(int n)
{
int i, flag=1;
for(i=2; i<=n/2; ++i)
{
if(n%i==0)
{
flag=0;
break;
}
}
return flag;
}
int armstrong(int n)
{
int num=0, temp, flag=0;
temp=n;
while(n!=0)
{
num+=(n%10)*(n%10)*(n%10);
n/=10;
}
if (num==temp)
flag=1;
return flag;
}
/*
Enter a positive integer: 153
Enter P to check prime and A to check Armstrong number: p
153 is not a prime number.
Enter a positive integer: 153
Enter P to check prime and A to check Armstrong number: a
153 is an Armstrong number.
*/
Program to Find Sum of Natural Numbers using Recursion
In this program, user is asked to enter a positive integer and sum of natural numbers up to that
integer is displayed by this program. Suppose, user enters 5 then,
Sum will be equal to 1+2+3+4+5 = 15
#include<stdio.h>
int add(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Sum = %d",add(n));
return 0;
}
int add(int n)
{
if(n!=0)
return n+add(n-1); /* recursive call */
}
Output:
Enter an positive integer: 10
Sum = 210
Program to Find factorial of a number using Recursion
/*C program to find the factorial of a number using recursion*/
#include<stdio.h>
long factorial(int);
int main()
{
int n;
long f;
printf("Enter an integer to find factorial\n");
scanf("%d", &n);
if (n < 0)
printf("Negative integers are not allowed.\n");
else
{
f = factorial(n);
printf("%d! = %ld\n", n, f);
}
return 0;
}
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
Output:
Enter an integer to find factorial
-5
Negative integers are not allowed.
#include<stdio.h>
int factorial(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, factorial(n));
return 0;
}
int factorial(int n)
{
if(n!=1)
return n*factorial(n-1);
}
Output:
Enter an positive integer: 6
Factorial of 6 = 720
Program to Find H.C.F or GCD Using Recursion
This program takes two positive integers from user and calculates HCF or GCD using recursion.
/* Example to calculate GCD or HCF using recursive function. */
#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d%d", &n1, &n2);
printf("H.C.F of %d and %d = %d", n1, n2, hcf(n1,n2));
return 0;
}
int hcf(int n1, int n2)
{
if (n2!=0)
return hcf(n2, n1%n2);
else
return n1;
}
Output:
Enter two positive integers: 366
60
H.C.F of 366 and 60 = 6
Program to Reverse a Sentence Using Recursion
This program takes a sentence from user and reverses that sentence using recursion. This
program does not use string to reverse the sentence or store the sentence.
/* Example to reverse a sentence entered by user without using strings. */
#include <stdio.h>
void Reverse();
int main()
{
printf("Enter a sentence: ");
Reverse();
return 0;
}
void Reverse()
{
char c;
scanf("%c",&c);
if( c != '\n')
{
Reverse();
printf("%c",c);
}
}
Output:
Enter a sentence: margorp emosewa
awesome program
Program to Calculate the Power of a Number Using Recursion
This program takes two integers from user ( base number and a exponent) and calculates the
power. Instead of using loops to calculate power, this program uses recursion to calculate the
power of a number.
/* Source Code to calculate power using recursive function */
#include <stdio.h>
int power(int n1,int n2);
int main()
{
int base, exp;
printf("Enter base number: ");
scanf("%d",&base);
printf("Enter power number(positive integer): ");
scanf("%d",&exp);
printf("%d^%d = %d", base, exp, power(base, exp));
return 0;
}
int power(int base,int exp)
{
if ( exp!=1 )
return (base*power(base,exp-1));
}
Output:
Enter base number: 3
Enter power number(positive integer): 3
3^3 = 27
Program to Convert Binary Number to Decimal and Decimal to Binary
This program converts either binary number entered by user to decimal number or decimal
number entered by user to binary number in accordance with the character entered by user.
/* C programming source code to convert either binary to decimal or decimal to binary according
to data entered by user. */
#include <stdio.h>
#include <math.h>
int binary_decimal(int n);
int decimal_binary(int n);
int main()
{
int n;
char c;
printf("Instructions:\n");
printf("1. Enter alphabet 'd' to convert binary to decimal.\n");
printf("2. Enter alphabet 'b' to convert decimal to binary.\n");
scanf("%c",&c);
if (c =='d' || c == 'D')
{
printf("Enter a binary number: ");
scanf("%d", &n);
printf("%d in binary = %d in decimal", n, binary_decimal(n));
}
if (c =='b' || c == 'B')
{
printf("Enter a decimal number: ");
scanf("%d", &n);
printf("%d in decimal = %d in binary", n, decimal_binary(n));
}
return 0;
}
/*At this point, the decimal variable contains corresponding decimal value of binary number. */
i=1;
while (decimal!=0)
{
octal+=(decimal%8)*i;
decimal/=8;
i*=10;
}
return octal;
}
int octal_binary(int n) /* Function to convert octal to binary.*/
{
int decimal=0, binary=0, i=0;
while (n!=0)
{
decimal+=(n%10)*pow(8,i);
++i;
n/=10;
}
/* At this point, the decimal variable contains corresponding decimal value of that octal number.
*/
i=1;
while(decimal!=0)
{
binary+=(decimal%2)*i;
decimal/=2;
i*=10;
}
return binary;
}
Output:
Instructions:
Enter alphabet 'o' to convert binary to octal.
2. Enter alphabet 'b' to convert octal to binary.
o
Enter a binary number: 1000
1000 in binary = 10 in octal
Instructions:
Enter alphabet 'o' to convert binary to octal.
2. Enter alphabet 'b' to convert octal to binary.
b
Enter a octal number: 10
10 in octal = 1000 in binary
Program Swap Numbers in Cyclic Order Using Call by Reference
This program takes three enters from user which is stored in variable a, b and c respectively.
Then, these variables are passed to function using call by reference.
#include<stdio.h>
void Cycle(int *a, int *b, int *c);
int main()
{
int a,b,c;
printf("Enter value of a, b and c respectively: ");
scanf("%d%d%d",&a,&b,&c);
printf("Value before swapping:\n");
printf("a=%d\nb=%d\nc=%d\n",a,b,c);
Cycle(&a,&b,&c);
printf("Value after swapping numbers in cycle:\n");
printf("a=%d\nb=%d\nc=%d\n",a,b,c);
return 0;
}
void Cycle(int *a,int *b,int *c)
{
int temp;
temp=*b;
*b=*a;
*a=*c;
*c=temp;
}
Output:
Enter value of a, b and c respectively: 5
3
4
Value before swapping:
a=5
b=3
c=4
Value after swapping numbers in cycle:
a=4
b=5
c=3
ONE WORD ANSWERS
Ans: a. The length of the source program can be reduced by using function.
b.It is easy to locate and isolate a faulty functions for further investigations.
Ans: The six elements that are involved in a function definition are:
b.Function name
c.Parameter list
d.Local variables
f.Return statement
Ans: The function type,function name and the parameter list together is called
a function header.
Ans: The local variables the function statements and the return statement on a whole is known
as function body.
Ans: The parameter list declares the variables that will receive the data sent by the calling
programme. They serve as the input data to function to carry out the specified task since
they represent actual input values, they are called as the "formal parameters".
Ans: The parameters which are used in the function call are called as actual parameters. These
may be simple constants, variables or expressions.
Ans: This is one type of parameter which collects the value from the calling function.
Ans: The variables which are declared inside the function is known as local variable
Ans: The variables which are declared outside the function is known as global variable
Ans: The calling function should declare any function that is to be used later in the program
this is known as function declaration or function prototype.
Q14) what are the main elements required in the function prototype?
b.function name
c.parameters list
d.terminating semicolon
Q15) What are the types of functions depending upon categories of arguments and return
statements?
Ans: Depending upon categories of arguments and return statements there are four types of
functions
Ans: Multiple values to the calling function can be returned using "POINTERS".
b.the function definition, the formal parameter must be an array type; the size of an array
does not need to be specified.
Ans: To pass an array to a function ,the name of the array must appear itself, without brackets
or subscripts, as an actual argument with in the function call.
Ans: These are the variables declared inside a function in which they are utilised. They are
cerated when the function is 'called' and destroyed automatically when the function is
exited.
Ans: These are the variables which persist until the end of the program. They are of two types
Ans: Recusion can be used for doing progrms like mathematical induction, fibbonaci series
etc.....
7. Which of the following types of variables remain alive for the entire life
time of the program?
a. extern
b. auto
c. register
d. static
8. Which of the following refers to the region of a programme where a variable is available
for use?
a. scope
b. visibility
c. life time
d. None of the above
9. The formal parameters in the function header must be prefixed by which of the following
indirection operator?
a. *
b. +
c. -
d. /
10. What will be the output of the following program :
static int funct(int val)
{
static int sum;
sum+=val;
return sum;
}
void main()
{
int i,n=9;
for (i=1; i<n--; i++)
funct(i*2);
printf("%d",funct(0));
}
a.209 b.20 c.30 d.90
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
This is called a single-dimensional array. The arraySize must be an integer constant greater than
zero and type can be any valid C data type. For example, to declare a 10-element array called
balance of type double, use this statement:
double balance[10];
The number of values between braces { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ]. Following is an example to assign a single
element of the array:
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write:
The above statement will take 10th element from the array and assign the value to salary
variable.
e.g.
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
4.2 MULTIDIMENSIONAL ARRAYS
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration:
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:
int threedim[5][10][4];
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two
dimensional array can be think as a table which will have x number of rows and y number of
columns. A 2-dimentional array a which contains three rows and four columns can be shown as
below:
Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is
the name of the array, and i and j are the subscripts that uniquely identify each element in a.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
The above statement will take 4th element from the 3rd row of the array. You can verify it in the
above diagram. Let us check below program where we have used nested loop to handle a two
dimensional array:
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
When the above code is compiled and executed, it produces following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
ONE WORD ANSWERS
Q1) What is an array?
Ans: Array is collection of homogeneous data.It stores data in contigeous memory location.
Q2) How many types of arrays exist and what are they?
Ans: There are 3 types of arrays they are
a) one dimensional array
b) two dimensional array
c) multi dimensional array
Q8) What value is automatically assigned to those array elements that are not explicitly
initialized?
Ans: All of array elements automatically set to zero except those that have been explicitly
initialized with in array definitions.
Q9) State the rule that determines the order in which initial values
are assigned to multi dimensional array elements?
Ans: the rule is that the last (right most) subscript increases most
rapidly and the first (left most) increases least rapidly.
SAMPLE C PROGRAMS
# 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>
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:
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;
}
}
}
printf ("The numbers arranged in descending 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);
}
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);
}
}
#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;
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");
}
#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");
}
13. 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");
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);
}
17. Program to find the sum of the sine series.
#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);
}
printf("Sum of the cosine series=%f\n", cosx);
printf("The value of cos(%d) using library function=%f\n",x1,cos(x));
}
#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);
}
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<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;
}
else
{
numerator = num2;
denominator = num1;
}
remainder = numerator % denominator;
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:
#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
24. 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();
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);
exit(0);
}
printf("Prime numbers are\n");
temp = M;
if ( M % 2 == 0)
{
M++;
}
for (i=M; i<=N; i=i+2)
{
flag = 0;
for (j=2; j<=i/2; j++)
{
if( (i%j) == 0)
{
flag = 1;
break;
}
}
if(flag == 0)
{
printf("%d\n",i);
count++;
}
}
printf("Number of primes between %d and %d = %d\n",temp,N,count);
}
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)
{
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]);
}
# 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++)
{
if ( vectx[i] == element)
{
found = 1;
pos = i;
break;
}
}
if (found == 1)
{
for(i=pos; i< n-1; i++)
{
vectx[i] = vectx[i+1];
}
printf("The resultant vector is \n");
for(i=0; i<n-1; i++)
{
printf("%d\n",vectx[i]);
}
}
else
printf("Element %d is not found in the vector\n", element);
}
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];
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");
}
29 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);
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");
scanf("%d",&key);
for(i=0; i<n; i++)
{
if ( key < x[i] )
{
pos = i;
break;
}
}
m = n - pos + 1 ;
for(i=0; i<= m ; i++)
{
x[n-i+2] = x[n-i+1] ;
}
x[pos] = key;
main()
{
float x[10];
int i, n;
float avrg, var, SD, sum=0, sum1=0;
A pointer is a variable which contains the address in memory of another variable. We can have a
pointer to any variable type.
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;
}
It is worth considering what is going on at the machine level in memory to fully understand how
pointer works. Assume for the sake of this discussion that variable x resides at memory location
100, y at 200 and ip at 1000 shown in figure 4.1.
int x = 1, y = 2;
int *ip;
ip = & x ;
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
Note, however, that `cp' is a variable, and can be changed, whereas`msg' is a constant, and is not
an lvalue.
7.2 POINTERS AND ARRAYS
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.
(*p)++: *p which is content at address 1000 (i.e. 10) is incremented. Therefore (*p)++ is 11.
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 ria ble t v[ 0] t v[ 1] t v[ 2] t v[ 3] t v[ 4] t v[ 5]
V alu e O N I D A \ 0
The statement:
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;
in the last statement, we have declared a pointer variable ps and initialized it with the address of
the structure s. We say that ps points to s. To access the structure members with the help of the
pointer variable ps, we use the following syntax:
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
product + 3 = 9556
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
Call by reference is achieved by passing a pointer as the argument. Of course, in this case, the
parameters must be declared as pointer types. The following program demonstrates this:
Example:
# include <stdio.h>
main ()
{
int x, y;
x = 10;
y = 20;
swap (&x, &y); /* addresses passed */
printf (%d %d\n, x, y);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
7.5.2 Pointer to Function
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
7.6 ARRAY OF POINTERS
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
7.6.1 Multidimensional arrays and pointers
A 2D array is really a 1D array, each of whose elements is itself an array. Hence:
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.
Consider int a[5][35] to be passed in a function:
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
#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.
7.8 DYNAMIC MEMORY ALLOCATION AND DYNAMIC STRUCTURES
Dynamic allocation is a unique feature to C among high level languages. It enables us to create
data types and structures of any size and length to suit our program need. The process of
allocating memory at run time is known as dynamic memory allocation.
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;
};
typedef struct complex comp;
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>
main()
{
char *ptr, *qtr;
ptr = (char *) malloc ( 12);
strcpy(ptr, "hello world" );
printf("\n Block now contains: %s", ptr);
qtr =(char *) realloc(ptr,25);
strcpy(qtr, "Hello beautiful world");
printf("\n The Block contents after reallocation: %s", qtr);
ptr =(char *) realloc(qtr, 5);
printf("\n After reducing the size: %s", ptr);
}
Output:
Chain of pointers:
The process of linking the pointer varible to another pointer varible is known as chain of
pointers.this can be shown as **ptr.
Q9) What the compiler does when the array name has been assigned to pointer variable?
Ans: The compiler allocate the address of the first member of an array to the pointer.
Q11) Which operator is used to access the structure member when we use pointer in structures?
Ans: Arrow operator(->) or member selection operator.
2. An integer pointer:
a. Points to the address of another integer value
b. Points to any data type
c. Points to itself
d. None of the above
4. Which of the following expressions in c is used for accessing the address Of a variable
var?
a. &(*var)
b. *var
c. &var
d. *(&var)
6. Which of the following expressions will give the value stored in variable X?
a. X
b. *x
C. *&X
d. &X
7. If(int a1,*a2) a1=2 and a2=&a1 then what does a2++ depict(consider the address value of
a1 to be 3802,a1&a2 are integer pointers)
a. 3
b. 3803
c. 3804
d. 3802
8. If a1=2 and a2=&a1 then what does a2++ depict(consider the address value of a1 to be
3802,a1&a2 are char pointers)
a. 3
b. 3803
c. 3804
d. 3802
9. If a1=2 and a2=&a1 then what does a2++ depict(consider the address value of a1 to be
3802,a1&a2 are float pointers)
a. 3
b. 3803
c. 3804
d. 3806
10. If a1=&x and a2=&a1,what will be the output generated by the expression **a2?
a. address of a2
b. address of a1
c. value of x
d. address of x
8) What will be output if you will compile and execute the following c code?
#include<stdio.h>
int main()
{
int a=5,b=10,c=15;
int *arr[]={&a,&b,&c};
printf("%d",*arr[1]);
return 0;
16) What will be output if you will compile and execute the following c code?
#include<stdio.h>
int main()
{
static char *s[3]={"math","phy","che"};
typedef char *( *ppp)[3];
static ppp p1=&s,p2=&s,p3=&s;
char * (*(*array[3]))[3]={&p1,&p2,&p3};
char * (*(*(*ptr)[3]))[3]=&array;
p2+=1;
p3+=2;
printf("%s",(***ptr[0])[2]);
return 0;
}
6. STRINGS
6.1 INTRODUCTION TO STRINGS
A string in the C language is simply an array of characters. Strings must have a NULL or \0
character after the last character to show where the string ends. A string can be declared as a
character array or with a string pointer. The string can be declared as follow :
Syntax:
char string_nm[size];
Example:
char name[50];
When compiler assigns string to character array then it automatically supplies null character ('\0')
at the end of string. Thus, size of string = original length of string + 1.
char name[7];
name = "TECHNO"
For example, to declare an array of 30 strings each having a max length of 80 characters.
char str_array[30][80];
}
Output: HELLO is in upper case.
9)char* strstr (main string,substring): This function accepts two strings i.e main string and
substring.
It searches for the first occurrence substring in main string and returns the character pointer to the
first char.
Example
#include <stdio.h>
#include <string.h>
void main()
{
char str1[]="programmingsea",str2[]="ming",*ptr;
ptr=strstr(str1, str2);
printf("substring is: %s",ptr);
getch();
}
Output : substring is mingsea
Q4) Other than the scanf function,what is the other function that can be used to read the string?
Ans: gets() is the other function that can be used to read the string.
Q5) What is the funtcion we use to write the string on the screen?
Ans: printf() function by using format code %s.
6. What value will strlen functions return for the string {'r','a','m','\0'}
a. 3
b. 4
c. 5
d. None of the above
7. Which of the following is the correct syntax for copying a string S1 into S2?
a. strcmp(S2,S1);
b. strcpy(S1,S2);
c. strcmp(S1,S2);
d. strcpy(S2,S1);
8. Which of the following should be used for printing using printf statement"?
a. """
b. "\
c \"
d. /"
OUTPUT PREDICTION
1. What will be output when you will execute following c code?
#include<stdio.h>
void main()
{
char arr[7]="Network";
printf("%s",arr);
}
10) What will be output when you will execute following c code?
#include<stdio.h>
void main()
{
int array[2][3]={5,10,15,20,25,30};
int (*ptr)[2][3]=&array;
printf("%d\t",***ptr);
printf("%d\t",***(ptr+1));
printf("%d\t",**(*ptr+1));
printf("%d\t",*(*(*ptr+1)+2));
}
11. What will be output when you will execute following c code?
#include<stdio.h>
void main()
{
static int a=2,b=4,c=8;
static int *arr1[2]={&a,&b};
static int *arr2[2]={&b,&c};
int* (*arr[2])[2]={&arr1,&arr2};
printf("%d %d\t",*(*arr[0])[1], *(*(**(arr+1)+1)));
}
13) What will be output when you will execute following c code?
#include<stdio.h>
typedef struct
{
char *name;
double salary;
}job;
void main()
{
static job a={"TCS",15000.0};
static job b={"IBM",25000.0};
static job c={"Google",35000.0};
int x=5;
job * arr[3]={&a,&b,&c};
printf("%s %f\t",(3,x>>5-4)[*arr]);
}
double myfun(double d)
{
d-=1;
return d;
}
16) What will be output when you will execute following c code?
#include<stdio.h>
void main()
{
int arr[][3]={{1,2},{3,4,5},{5}};
printf("%d %d %d",sizeof(arr),arr[0][2],arr[1][2]);
}
18) What will be output when you will execute following c code?
#include<stdio.h>
#define WWW -1
enum {cat,rat};
void main()
{
int Dhoni[]={2,'b',0x3,01001,'\x1d','\111',rat,WWW};
int i;
for(i=0;i<8;i++)
printf(" %d",Dhoni[i]);
}
A structure is a collection of variables referenced under one name, providing a convenient means
of keeping related information together. The variables which make up a structure are called
structure elements.
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;
} addr_info;
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;
}
Output:
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:
Example:
#include <stdio.h>
struct
{
char initial;
int age;
int grade;
} kids[12];
int main()
{
int index;
for (index = 0 ; index < 12 ; index++)
{
kids[index].initial = 'A' + index;
kids[index].age = 16;
kids[index].grade = 84;
}
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);.
8.5 PASSING ENTIRE STRUCTURES TO FUNCTIONS
When a structure is used as an argument to a function, the entire structure is passed using the
standard call-by-value method. Of course, this means that changes made to the contents of the
structure inside the function do not affect the structure used as the argument.
#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;
}
Output:
Where, identifier refers to new name(s) given to the data type. User defined types obey the same
scope rules as identifiers, so if one defined in a function, it is recognized only within that
function. Few examples of type definitions are
typedef int age;
typedef float average;
typedef char string;
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.
8.8 UNIONS
A union is a memory location, which is shared by two or more different variables, generally of
different types, at different times. The general form of a union definition is:
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.
8.8.1 Accessing Union Elements
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
{
int x;
char name[4];
} dec1;
int i;
dec1.x = 300;
printf(Size of union = %d\n, sizeof(dec1));
printf(The value of x = %u\t, dec1.x);
printf(\n%u %u %u %u, dec1.name[0], dec1.name[1], dec1.name[2],
dec1.name[3]);
}
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)
{
strcpy(stu_data.hostler.name,"Herbert");
strcpy(stu_data.hostler.hostelname,"ss2");
printf("\n student name: %s",stu_data.hostler.name);
printf("\n hostle name: %s",stu_data.hostler.hostelname);
printf("\n Union Data size: %d",sizeof(stu_data) );
printf("\n Hostler Data size: %d",sizeof(stu_data.hostler) );
}
else if(n==2)
{
strcpy(stu_data.dayscholar.name,"Schildt");
strcpy(stu_data.dayscholar.address,"balaji colony");
stu_data.dayscholar.phonenumber=5620;
stu_data.dayscholar.rollno = 1290;
printf("\n student name: %s", stu_data.dayscholar.name);
printf("\n address: %s", stu_data.dayscholar.address);
printf("\n phone number: %d", stu_data.dayscholar.phonenumber);
printf("\n roll number: %d", stu_data.dayscholar.rollno);
printf("\n Union Data size: %d", sizeof(stu_data) );
printf("\n Day Scholar Data size: %d", sizeof(stu_data.dayscholar) );
}
else
printf("\n it is wrong choice ");
getch();
}
Output:
RUN 1:
MENU
1. Hostler
2. Day Scholar
RUN 2:
MENU
1. Hostler
2. Day Scholar
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();
}
8.10 BIT-FIELDS
C has a built-in method for accessing a single bit within a byte. This is useful because:
If memory is tight, several Boolean (true/false) variables can be stored in one byte,
saving memory.
Certain devices transmit information encoded into bits within one byte.
Certain encryption routines need to access individual bits within a byte.
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;
A bit-field must be declared as either int, unsigned, or signed. Bit-fields of length 1 should be
declared as unsigned because a single bit cannot have a sign.
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:
struct status_type
{
unsigned delta_cts: 1;
unsigned delta_dsr: 1;
unsigned tr_edge: 1;
unsigned delta_rec: 1;
unsigned cts: 1;
unsigned dsr: 1;
unsigned ring: 1;
unsigned rec_line: 1;
} status;
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);
status.ring = 0;
As with structures, if an element is referenced through a pointer, the -> operator is used in lieu of
the dot operator.
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;
unsigned int z : 2;
} bits;
} number;
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.
Limitations of bit-fields:
Q3). What are the major differences between arrays and structures?
Ans: a. an array is a collection of similar datatypes where as the stuctrure is a collection of
different data types.
b. an array is derived datatype where as a structure is user defined datatype.
Q9). What is the general format of sending a copy of a structure to the called function?
Ans: The general fomrat of sending a copy of a structure to the called function is
function_name(structure_variable name);
Q10) What is enum?
Ans: It is a special keyword which allows to define symbolic constants.
3. The uninitialized integer data type of a structure contains which of the following default
values?
a. garbage
b. zero
c. one
d. None of the above
4. Which of the following expressions arre correct for accessing the 'num' variable value of
the ith element of a structure array 'student'
a. student[i].num
b. student.num[i]
c. student[i]_>num
d. None of the above
6. What comes after the closing brace when we use typedef definition
a. type_name;
b. type name;
c. type_type;
d. None of the above
(ii) struct B{
int b;
struct B *next;
};
struct A{
int a;
struct B tempB;
struct A *next;
};
(iii)struct B{
int b;
}tempB;
struct {
int a;
struct B *nextB;
};
(iv) struct B {
int b;
struct B {
int b;
struct B *nextB;
}tempB;
struct B *nextB;
}tempB;
18) What are the largest values that can be assigned to each of the bit fields defined in
[Q017] .
(a)a=0 b=2 c=3 d=4 (b)a=1 b=2 c=7 d=15
(c)a=1 b=3 c=7 d=15 (d)None of thes
}bit;
char *p;
struct bitfield *ptr,bit1={1,3,3};
p=&bit1;
p++;
printf("%d",*p);
}
If a file can support random access (sometimes referred to as position requests), opening a file
also initializes the file position indicator to the start of a file. This indicator is incremented as
each character is read from, or written to, the file.
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.
9.1.1 Streams
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:
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.
9.3 FILE POINTER
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.
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.
A file may be opened in text or binary mode. In most implementations, in text mode, CR/LF
sequences are translated to newline characters on input. On output, the reverse occurs. No such
translation occurs on binary files.
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);
}
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.
9.4.3 Writing a Character
Characters are written using putc() or its equivalent fputc(). The prototype for putc() is:
where ch is the character to be output. For historical reasons, ch is defined as an int, but only the
low order byte is used.
If the putc() operation is successful, it returns the character written, otherwise it returns EOF.
9.4.4 Reading a Character
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:
do
{
ch = getc (fp);
} while(ch != EOF);
The following code reads a binary file until end of file is encountered:
while (! feof (fp))
ch = getc(fp);
Of course, this method can be applied to text files as well as binary files.
9.4.6 Working With Strings - fputs() and fgets()
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.
9.4.7 rewind ()
rewind() resets the file position indicator to the beginning of the file. The syntax of rewind() is:
rewind(fptr);
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.
The number of bytes to be read/written is specified by num_bytes. count determines how many
items (each num_bytes in length) are read or written.
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;
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:
fseek() returns 0 when successful and a non-zero value if an error occurs. fseek() may be used to
seek in multiples of any type of data by simply multiplying the size of the data by the number of
the item to be reached, for example:
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().
9.5 THE STANDARD STREAMS
Whenever a C program starts execution, three streams are opened automatically. These are:
Standard input (stdin)
Standard output (stdout)
Standard error (stderr)
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);
}
A command line argument is the information that follows the programs name on the command
prompt of the operating system.
The first argument is argc (argument count) must be an integer value, which
represents the number arguments in the command prompt. It will always be at least
one because the name of the program qualifies as the first argument.
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:
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
# 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
Example
We must declare both argc and argv parameters even if they are not used because the parameter
declarations are position dependent.
Example Programs on File I/O and Command Line Arguments:
The following programs demonstrate the use of C's file I/O functions.
Example
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
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);
}
Example
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 */
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;
if((fp=fopen("testfile", "wb+"))==NULL) /* open for binary read & write */
{
printf("Cannot open file\n");
exit(1);
}
rewind(fp);
printf("%2.3f %d %ld\n",d,i,l);
fclose(fp);
}
Example
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)
}
9.7 THE C PREPROCESSOR
As defined by the ANSI standard, the C preprocessor contains the following directives:
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.
By convention, C programmers use uppercase for defined identifiers. Example macro #defines
are:
#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
#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.
9.7.1 Conditional Compilation
Several directives control the selective compilation of portions of the program code. They are:
#if #else #elif #endif
#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.
#pragma
Example
# 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));
Q6) How many types files are exist in C ?what are they?
Ans: Two types ,they are: i) text file ii) binary file
Q19) How many types of status enquiry library functions are there?what are they?
Ans: Two.They are
1.feof
2.ferror
Q20) What is the use of status enquiry library functions?
ans: they help to detect i/o errors with in the files.
Q21) What is the use of ftell? write the general form of ftell?
Ans: ftell function is useful in saving the current position of file .
it takes the general form:
n=ftell(fp)
it returns a number of type long.