(Theory) Lecture Notes Programming in C
(Theory) Lecture Notes Programming in C
(Theory) Lecture Notes Programming in C
UNIT-I
Introduction to Flowcharts and Algorithms, need of Computer languages and types of computer languages.
EXAMPLE 1:
Step 1: Start
Step 2: Print Welcome to AIT, AAU
Step 3: Stop
EXAMPLE 2:
Step 1: Start
Step 2: INPUT A, B
Step 3: C=A+B
Step 4: Write C
Step 3: Stop
Read A, B
Sum = A + B
Write Sum
Stop
SYMBOLS OF FLOWCHART
Computer languages are the languages by which a user commands a computer to work on the
algorithm which a user has written to get an output.
OR
A computer language is a set of predefined words that are combined into a program according to
predefined rules (syntax). Over the years, computer languages have evolved from machine
language to high-level languages.
UNIT-II
C character set, Identifiers and keywords, Data types, Declarations, Expressions, statements and symbolic constants,
Operators.
HISTORY OF C
C was originally developed in the 1970's by Dennis Ritchie at Bell Telephone Laboratories,
Inc. (now AT&T Bell Laboratories). It is an outgrowth of two earlier languages, called BCPL and B,
which were also developed at Bell Laboratories. C was largely confined to use within Bell
Laboratories until 1978, when Brian Kernighan and Ritchie published a definitive description of
the language.* The Kernighan and Ritchie description is commonly referred to as "K&R c."
STRUCTURE OF A C PROGRAM
Every C program consists of one or more functions, one of which must be called main. The
program will always begin by executing the main function. Additional function definitions may
precede or follow main
The-arguments are symbols that represent information being passed between the function
and other parts of the program. (Arguments are also referred to as parameters.)
Each compound statement is enclosed within a pair of braces, i.e., { and}. The braces
may contain combinations of elementary statements (called expression statements) and other
compound statements. Thus, compound statements may be nested, one within another. Each
expression statement must end with a semicolon (;).
Comments (remarks) may appear anywhere within a program, as long as they are placed
within the delimiters / * and */ (e.g., / * this is a comment */). Such comments are helpful in
identifying the program's principal features or in explaining the underlying logic of various
program features.
}
/* Executable part */
}
Subprogarm section
Function1()
{
} User Defined functions
Function2()
{}
..
Functionn()
Example: Area of a Circle Here is an elementary C program that reads in the radius of a circle,
calculates the area and then writes the calculated result.
*include <stdio.h> /* LIBRARY FILE ACCESS */
/* program to calculate area of a circle */ /* TITLE (COMMENT) */
main() /* FUNCTION HEADING */
{
float radius, area; /* VARIABLE DECLARATIONS */
printf("Radius = ? "); /* OUTPUT STATEMENT (PROMPT) */
scanf( "%f", &radius); /* INPUT STATEMENT */
area = 3.14159 * radius * radius; /* ASSIGNMENT STATEMENT */
printf("Area = ::'.f", area); /* OUTPUT STATEMENT */
}
The comments at the end of each line have been added in order to emphasize the overall
program organization.
Execution of the program results in an interactive dialog such as that shown below. The user's
response is underlined, for clarity.
Radius = ? 3
Area = 28.274309
FEATURES OF C
English like high level language Simple & easy
Rich set of built-in functions and operators helps users to write complex programs Robust
language.
Combined features of low-level and high-level language allow users to develop both system
and customized software Flexible and used to develop any kind of software.
Large set of data types and operators, compiler based Efficient and fast.
Software developed using it can be executed on any computer without none or little
modification highly portable.
Supports may program structure and statements and above all it supports modular or block
programming Structured Programming language.
Preprocessor The Preprocessor accepts source code as input and is responsible for removing
comments interpreting special preprocessor directives denoted by #.
For example
#include -- includes contents of a named file. Files usually called header files. e.g
#include <math.h> -- standard library maths file.
#include <stdio.h> -- standard library I/O file
#define -- defines a symbolic name or constant. Macro substitution.
#define MAX_ARRAY_SIZE 100
C Compiler C compiler translates source to assembly code. The source code is received from
the preprocessor.
Assembler The assembler creates object code. On a Windows OS you may see files with a
.OBJ on MSDOS to indicate object code files and in Unix system with .o suffix
Link Editor If a source file references library functions or functions defined in other source
files the link editor combines these functions (with main()) to create an executable file. External
Variable references resolved here also.
C CHARACTER SET
Alphabets:
A, B, C, .., X, Y, Z
a, b, c, .., x, y, z
Digits:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols:
~!@#$%^&*()_-+=|\{[}]<>,.?/;:
C uses certain combination of these characters such as \b, \t, \n to represent special characters
such as backspace, tab and newline, respectively. These character combination are known as
escape sequences.
Escape Sequences
Certain nonprinting characters, as well as the double quote ("), the apostrophe ('), the question
mark (?) and the backslash (\), can be expressed in terms of escape sequences. An escape
sequence always begins with a backward slash and is followed by one or more special characters.
For example, a line feed (LF), which is referred to as a newline in C, can be represented as \n.
Such escape sequences always represent single characters, even though they are written in terms
of two or more characters.
KEYWORDS
There are certain reserved words, called keywords, that have standard, predefined
meaning in C. These keywords can be used only for their intended purpose; they cannot be
used as programmer-defined identifiers.
DATA TYPES
C supports several different data types of data, each of which may be represented
differently within the computers memory. A C language programmer has to tell the system
before-hand, the type of numbers or characters he is using in his program. These are data types.
There are many data types in C language. A C programmer has to use appropriate data type as
per his requirement.
The basic data types are int, char, float, double and void. Basic data types can be
augmented by using the data type qualifiers/modifier short, long, signed and unsigned.
Typical memory requirements are given below.
CONSTANTS VALUES
C has four basic types of constant values and thus they are classified as integer constants,
floating-point constants, character constants and string constants (there are also enumeration
constants). Integer and floating-point constants represent numbers. They are often referred to
collectively as numeric-type constants. The following rules apply to all numeric-type constants.
1. Commas and blank spaces cannot be included within the constant.
2. The constant can be preceded by a minus ( - ) sign if desired. (Actually, the minus sign is an
operator that changes the sign of a positive constant, though it can be thought of as a part of the
constant itself.)
3. The value of a constant cannot exceed specified minimum and maximum bounds. For each
type of constant, these bounds will vary from one C compiler to another.
Integer Constants
An integer constant is an integer-valued number. Thus it consists of a sequence of digits.
Integer constants can be written in three different number systems: decimal (base 10), octal
(base 8) and hexadecimal (base 16).
Octal integer constant can consist of any combination of digits taken from the set 0
through 7. The first digit must be 0 to identify the constant as an octal number
For e.g.
0 01 0456
Decimal integer constant can consist of any combination of digits taken from the set 0
through 9. If the constant contains two or more digits, the first digit must be something
other than 0.
For e.g.
0 1 234 32767
Hexadecimal integer constant must begin with either 0x or 0X. It can be followed by
any combination of digits taken from the sets 0 through 9 and a through f (either upper or
lowercase). The letters a through f (or A through F) represents the (decimal) quantities 10
through 15.
For e.g.
0 0x23 0X23ab 0x56FF
Unsigned and Long integer constants
An unsigned integer constant can be identified by appending the letter U (either
upper or lowercase) to the end of the constant.
For e.g.
50000U 456u
An long integer constant can be identified by appending the letter L (either upper
or lowercase) to the end of the constant.
For e.g.
123456789L 456789l
Characters Constant
A character constant is a single character, enclosed in apostrophes (single quotation
marks)
For e.g.
A x 2 &
Character constants have integer values that are determined by the computers particular
character set.
String Constants
A string constant consists of any number of consecutive characters (including none)
enclosed in (double) quotation marks.
For e.g.
hello Hello, \nHow are you? 1245487-656 2*(I+3)/J
The compiler automatically places a null character \0 at the end of every string constant, at the
last character within the string (before the closing double quotation mark). This character is not
visible when the string is displayed. However, null character can be easily checked within string.
Thus, the end of every string can be identified.
Character constant A and string constant A are different. Character constant has an equivalent
integer value, whereas a single character string constant doesnt have a equivalent integer value
because in string constant there are minimum two character that is A\0.
VARIABLES
A variable is an identifier that is used to represent some specified type of information
within a designated portion of the program. A variable represents a single data item that is a
numerical quantity or a character constant. The data item must be assigned to the variable at
some point in the program. The data item can then be accessed later in the program simply by
referring to the variable name.
A given variable can be assigned different data items at various places within the program.
Thus the information represented by the variable can change during the execution of the
program, but data type associated with the variable cannot be changed.
In short, variable is an entity which stores different values of same type during program
execution.
Declaration A declaration associates a group of variables with a specific data type. All
variables must be declared before they are assigned values or used in any other executable
statements.
A declaration consists of data type followed by one or more variable names, ending with a
semi-colon. Duplicate variable declaration is not allowed in any programming language.
For e.g.
int marks, total=0;
float average, percentage, area=0;
char flag, gender=M;
short int a, b, c=0;
long int x, y, z;
double i;
long float factor= 0.323E-6;
unsigned int d, e;
Scope Of Variables means in which part of program value of variable will be accessible.
Local: Available only to certain selected statements in the program. It is defined inside a function
Global: It is accessible to all the statements in the function. It is declared outside the function.
Volatile Variable
A volatile variable is the one whose values may be changed at any time by some external
sources.
Example:
volatile int num;
The value of data may be altered by some external factor, even if it does not appear on the left
hand side of the assignment statement. When we declare a variable as volatile the compiler will
examine the value of the variable each time it is encountered to see if an external factor has
changed the value.
CONSTANTS
In C constants are of two types first is symbolic constant or compiler constants and second is
runtime constant. Constants are classified on the basis of when value of constant will be replaced
in an expression.
SYMBOLIC CONSTANTS
Symbolic constant value can be defined as a preprocessor statement and used in the program as
any other constant value. The general form of a symbolic constant is
These values may appear anywhere in the program, but must come before it is referenced in the
program. It is a standard practice to place them at the beginning of the program
The const data type qualifier tells the compiler that the value of the int variableclass_size
may not be modified in the program.
here type represents existing data type and identifier refers to the row name given to the data
type.
Here Units symbolizes int and average symbolizes float. They can be later used to declare
variables as follows:
Therefore dept1 and dept2 are indirectly declared as integer data type and section1 and section2
are indirectly float data type.
The second type of user defined data type is enumerated data type which is defined as follows.
The identifier is a user defined enumerated datatype which can be used to declare variables that
have one of the values enclosed within the braces. After the definition we can declare variables to
be of this new type as below.
The enumerated variables V1, V2, .. Vn can have only one of the values value1, value2 ..
value n
Example:
EXPRESSION
An expression represents a single data item, such as number or a character. The
expression may consist of a single entity, such as a constant, a variable, an array element or a
reference to a function. It may also consist of some combination of such entities interconnected
by one or more operators. Expression can also represent logical conditions that are either true or
false. However, in C the conditions true and false are represented by the integer values 1 and 0
respectively. Thus logical-type expression really represents numerical quantities.
For e.g.
a+b
x=y
c=a+b
x<=y
x == Y
i++
(float) x
&a
( ) , [ ], , . Left to Right
Assignment =, /=, *=, %=, +=, -=, &=, ^=, |=, <<=, Right to Left
>>=
TYPE CASTING
Converting one data type to another is called as casting. For sometimes certain variables
declared as float might be required as int for some expressions. For that purpose the cast is used.
General form
(data type) expression
Eg:
Let a, b are float variables and c integer variable
If we want to use a and b as int in some expression then we can change this as follows
((int)(a+b))+c;
Here a+b is converted to int and then added with c. After the execution of this expression and b
will be returned as float variables.
UNIT III
Basic input/output library functions, control statements, storage types, Defining and accessing, passing
arguments, Function prototypes, Recursion, Library functions.
FORMATED FUNCTIONS
TYPE INPUT OUTPUT
UNFORMATED FUNCTIONS
TYPE INPUT OUTPUT
char getch(), getche(), getchar() putch(), putchar()
int - -
float - -
String gets() puts()
Input Functions These functions are used to accept input from user. User can input data
using standard input device (keyboard) or any other input device.
Scanf:
Syntax:
int scanf(format String (formatting characters separated by space or
separator), <address of variable separated by comma>);
Purpose:
scanf reads characters from the standard input, interprets them according to the
specification in format, and stores the results through the remaining arguments.
The other argument, indicate where the corresponding converted input should be
stored, so address operator is put before each variable. Address operator is used to
get address of a variable in memory.
scanf stops when it exhausts its format string, or when some input fails to match
the control specification.
Example:
scanf(%d,&a);
scanf(%d %d,&b,&c);
scanf(%d/%d/%d,&dd,&mm,&yy);
scanf(%3d,&a); here 3 is field width which specifies max number of
characters user can input.
getch
syntax:
int getch(void)
purpose:
Reads single character from keyboard without echoing on screen.
Example:
int password;
char b;
password = getch();
getch(); when we use this function data entered by the user from the keyboard
is not displayed on the screen, so it can be used to temporary pause
the screen also.
getche
Syntax:
int getche(void)
purpose:
Reads single character from keyboard, it echoes it with current text window, using
direct video or BIOS.
Example:
int a;
char b;
a = getche();
b = getche();
getchar
Syntax:
int getchar(void)
Purpose:
It is a macro defined as getc(stdin) getchar returns the next character on
the input stream stdin.
Example:
char gender;
int a;
gender = getchar();
a = getchar();
gets
Syntax:
char *gets(char *s)
Purpose:
It collects a stream of characters terminated by a new line character from
the standard input stream stdin and puts it into s.
Example:
char name[30];
gets(name);
Output Functions These functions are used to display result or message on standard input
device.
printf
Syntax:
int printf(formatting string, <list of variables separated by comma>);
Purpose:
printf converts, formats, and prints its arguments on the standard output under
control of the formatting string. It returns the number of characters printed. The
format string contains two types of objects: ordinary characters, which are copied
to the output stream, and conversion specifications, each of which causes
conversion and printing of the next successive argument to printf. Each conversion
specification begins with a % and ends with a conversion character.
Example:
printf(Welcome to c programming);
printf(Welcome to \C\ programming);
printf(Sum of %d and %d is %d, a, b, c);
putch
Syntax:
int putch(int c);
Purpose:
It outputs the character c to the current text window.
Example:
int a= 65,b=3;
putch(a);
putch(b);
putchar
Syntax:
int putchar(int c);
Purpose:
It is a macro defined as putc(c, stdout) putchar puts the character given by c on
output stream stdout.
Example:
int a= 65,b=3;
putchar(a);
putchar(b);
puts
Syntax:
int puts(const char *s)
Purpose:
It copies a null terminated string s to the standard output stream stdout and
appends a newline character.
Example:
char name[] = College of A.I.T;
puts(name);
STATEMENTS
Compound Statements: Any <statement> can be replaced with a compound statement.
Compound statements have the form:
{
<optional-statement-list>
}
and are used as the body of a function or anywhere that a single statement is expected. The
statement-list are the actions to be performed. Brackets define their own scope. In simple words,
when there are more than one statement compound statement is used.
Control statements
Looping statements
1. for statement
2. while statement
3. do while statement
1.1. else if
Another use of else is when there are multiple conditional statements that may all
evaluate to true, yet you want only one if statement's body to execute. You can use an "else if"
statement following an if statement and its body; that way, if the first statement is true, the
"else if" will be ignored, but if the if statement is false, it will then check the condition for the
else if statement. If the if statement was true the else statement will not be checked. It is
possible to use numerous else if statements to ensure that only one block of code is executed.
Syntax:
if ( < expression> )
{
// Execute these statements if < expression > is TRUE
}
else
if ( <another expression > )
{
// Execute these statements if <another expression > is TRUE and
// < expression > is FALSE
}
eg:
eg:
#include<stdio.h>
#include<conio.h>
main()
{
int pos;
clrscr();
printf(Enter any no:);
scanf(%d,&pos);
if(pos>0)&&(pos!=0)
printf(The given no is a positive no);
elseif(pos<0)&&(pos!=0)
printf(The given no is a negative no);
else
printf(The given no is a zero);
getch();
}
}
else
{
Statements 1.2;
if (expression 1.2)
statements 1.2.1;
else
statements 1.2.2;
}
In most of the situation nested if can be replaced by using logical && operation in single if
statement.
For e.g.
if(a>b)
{
If(a>c)
printf(a is greater);
}
Can be replaced by
if((a>b) && (a>c)
printf(a is greater);
eg:
#include<stdio.h>
#include<conio.h>
main()
{
char code;
clrscr();
printf(Enter a code[a/m/p]:);
scanf(%c,&code);
switch(code)
{
case a :
printf(Accounts staff);
break;
case m :
Prof M. P. Raj (B. Tech - AIT) Page: 20/48
Programming in C (AIT 112)
LOOPING STATEMENTS
1. while loop
Syntax:
while ( expression)
{
statements;
}
Description:
The expression is evaluated. If it is zero, non statement is executed and
expression is reevaluated. This cycle continues until expression becomes zero, at
which point execution resumes after statement.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int n,i=0;
clrscr();
printf(Enter the range:);
scanf(%d,&n);
while(i<n)
{
printf(i=%d\n,i);
i++;
}
getch();
}
int i,n;
clrscr();
printf(Enter the range:);
scanf(%d,&n);
do
{
printf(i=%d\n,i);
i++;
}while(i<n);
getch();
}
3. for loop
Syntax:
for (expression 1 ; expression 2; expression 3)
statements;
where
expression 1 initialization statement
expression 2 condition checking statement
expression 3 increment or decrement operator
Description:
The first expression is executed as a statement first, the second expression is then
tested to see if the body of the loop should be executed. The third expression is
executed at the end of every iteration of the loop. Any of the three expressions in
the for loop can be omitted. Leaving out the first or the third expressions means
that no additional action is performed either before the loop starts or after each
iteration. Omitting the second expression results in a loop that will always execute,
the value of the controlling expression is assumed to be true. If any expression is
omitted, the separating semi-colons must still be included.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int i,n;
clrscr();
printf(Enter the range:);
scanf(%d,&n);
for(i=0;i<n;i++)
printf(i=%d\n,i);
getch();
}
2. continue statement
This statement will take the control to the beginning of the loop. It can be included only in
a while, do while, for statement.
3. goto statement
It transfers the control to anywhere in the program. Avoid using this statement.
clrscr();
printf("Enter the value to sum:");
scanf("%d",&n);
while(n>0)
{
a=n%10;
sum=sum+a;
n=n/10;
}
printf("The summed digit is %d",sum);
getch();
}
8. Program to check the given no is Armstrong or not
#include<stdio.h>
#include<conio.h>
main()
{
int n,j,s=0,a;
clrscr();
printf("Enter a no:");
scanf("%d",&n);
j=n;
while(n>0)
{
a=n%10;
s=s+a*a*a;
n=n/10;
}
if(s==j)
printf("The given no is an armstrong no");
else
printf("The given no is not an armstrong no");
getch();
}
9. Program to generate prime numbers
#include<stdio.h>
#include<conio.h>
main()
{
int n,i,j;
clrscr();
printf("Enter the range:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=2;j<=i;j++)
{
if(i%j!=0)
continue;
else
break;
}
if(j==i)
printf("%d\t",i);
else
continue;
}
getch();
}
Functions
Definition
Function is a self-contained block of programs that performs a coherent task of some
kind... Every C program can be thought of as a collection of these functions.
There are two types of functions
1. Library functions e.g.: printf() , scanf()
2. User defined functions
User defined functions can be broadly divided into two types
1. Functions without arguments
2. Functions with arguments
1. Functions without arguments
Implementation
Three steps
1. Function prototype declaration
Syntax:
return type function name ();
e.g.:
void message();
void italy();
int sum();
2. Function calling
Syntax:
function name();
e.g.:
----
message();
italy();
sum();
3. Function Definition
Syntax:
return type function name ()
{
body of the function;
}
e.g.:
void message()
{
printf(Welcome to Functions);
}
e.g.:
#include<stdio.h>
#include<conio.h>
void message();
void main()
{
clrscr();
printf("I am in main function\n");
message();
getch();
}
void message()
{
printf("Welcome to c program");
}
Points to remember
1. C program is a collection of one or more functions.
2. If a program function only one function it must be main().
3. Program execution always begin with main().
4. There is no limit on the number of functions that might be present in a C program.
E.g.:
#include<stdio.h>
#include<conio.h>
void message();
void usage();
void main()
{
clrscr();
printf("I am in main function\n");
message();
usage();
printf("I am back in main");
getch();
}
void message()
{
printf("I am in message\n");
}
void usage()
{
printf("I am in usage\n");
}
5. Each of the function is called in a sequence specified by the function calls in the main().
6. After each function has done its thing, its control returns to main().
7. A function gets called when a function name is followed by a semicolon.
8. A function is defined when function name is followed by a pair of braces in which one or more
statements may present.
9. Any function can be called from any other function. Even main() can be called from other
function. For e.g.
main()
{
message();
}
message()
{
printf(I am in C \n);
main();
}
e.g.:
#include<stdio.h>
#include<conio.h>
void italy();
void brazil();
void main()
{
clrscr();
printf("I am in main function\n");
italy();
printf("I am back in main function");
getch();
}
void italy()
{
printf("Welcome to italy\n");
brazil();
printf("I am back in italy\n");
}
void brazil()
{
printf("I am in brazil\n");
}
10. A function can be called any no of times.
11. The order in which the functions are defined in the program and the order in which they are
called need not necessarily be same.
12. A function can call itself. Such a process is called recursion.
13. A function can be called from the other function, but a function cannot be defined in another
function.
Advantages of using functions
1. Writing functions avoids rewriting the same code repeatedly.
2. Using functions it is easier to write programs and keep track of what they are doing.
Call by value
Definition
It is a method of passing a photocopy of the values to the calling functions.
E.g.:
#include<stdio.h>
#include<conio.h>
int add(int x,int y);
void main()
{
int a,b,sum;
clrscr();
printf("Enter any two nos:");
scanf("%d%d",&a,&b);
sum=add(a,b);
printf("Sum=%d\n",sum);
getch();
}
int add(int x,int y)
{ int z;
z=x+y;
return(z);
}
Points to remember
1. In the above program we are passing a photocopy of the value a, b to the function add(). In
add() these values get collected in the variables x and y.
2. The variables a and b is called as actual arguments. whereas the variables x and y are called
as formal arguments.. Any number of arguments can be passed to a function being called.
However, the type, order and number of the actual and formal arguments must always be same.
3. If we want to return some values to the main function then it is done by using the return
statement. The return statement serves two purposes.
a) On executing the return statement, it immediately transfers the control back to the
calling program.
b) It returns the value present in the parentheses, after return to the calling program.
4. There is no restriction on the number of return statements that may be present in a function.
In addition, the return statement need not always be present at the end is called function.
e.g.:
#include<stdio.h>
#include<conio.h>
int code(int d);
void main()
{
int c;
char letter;
clrscr();
printf("Enter a character:");
c=getchar();
letter=code(c);
printf("Letter=%c",letter);
getch();
}
int code(int d)
{
if(d>=65&&d<=97)
return(d+32);
else
return(d);
}
5. Whenever the control returns from a function some value is definitely returned. If we want the
called function should not return any value in that case, we must mention so by using the
keyword void.
6. A function can return one value at a time.
7. If the return statement does not contain any argument then it will return a garbage value.
8. If the value of the formal argument is changed in the called function, the corresponding change
does not take place in the calling function.
E.g.:
#include<stdio.h>
#include<conio.h>
void num(int b);
void main()
{
int a=20;
clrscr();
num(a);
printf("A=%d",a);
getch();
}
void num(int b)
{
int b=60;
printf("B=%d\n",b);
}
Function declaration and prototypes
Prof M. P. Raj (B. Tech - AIT) Page: 29/48
Programming in C (AIT 112)
Eg:
#include<stdio.h>
#include<conio.h>
float square(float x);
void main()
{
float a,b;
clrscr();
printf("Enter any no:");
scanf("%f",&a);
b=square(a);
printf("Square of %f is %f",a,b);
getch();
}
float square(float x)
{
float y;
y=x*x;
return(y);
}
Scope rule of function
This is decided depending upon the variable, where it is declared.
If the variable is declared inside a function then it is called as local variables, and the
corresponding values of the variables are available within that function only.
If the variable is declared outside a function, then it is called as global variables or
external variable and the corresponding values of the variable are available all over the function.
Calling functions with arrays
Array elements can be passed to a function by calling the function by value or by
reference.
In the call by value, we pass values of array elements to the function, whereas in the call
by reference we pass addresses of array elements to the function.
e.g.:
#include<stdio.h>
#include<conio.h>
void display(int m);
void main()
{
int i;
int marks[]={50,60,70,80,90};
clrscr();
for(i=0;i<5;i++)
display(marks[i]);
getch();
}
void display(int m)
{
printf("%d\n",m);
}
Recursive function
A function can call itself . A function is called recursive if a statement within the body of a
function can call the same function. Sometimes called as circular definition. Recursion is thus the
process of defining something in terms of itself.
e.g.:
#include<stdio.h>
#include<conio.h>
int rec(int x);
void main()
{
int a,fact;
clrscr();
printf("Enter any no:");
Prof M. P. Raj (B. Tech - AIT) Page: 30/48
Programming in C (AIT 112)
scanf("%d",&a);
fact=rec(a);
printf("Factorial value=%d",fact);
getch();
}
int rec(int x)
{
int f;
if(x==1)
return(1);
else
f=x*rec(x-1);
return(f);
}
UNIT-IV
Defining and processing Arrays, Passing arrays to a function, Multi dimensional arrays, Define String, Using the String,
Printing a String, String inbuilt Functions (string.h).
Array
Array is nothing but a collection of like data types. These similar elements could be all ints, or all
floats, or all chars etc. Usually the array of characters is called a string, whereas an array of ints
or floats is called simply an array.
Array Declaration
Syntax:
data type variable name[dimension];
e.g.:
int a[10];
float c[5];
char name[40];
Accessing elements of an array
We can access array elements by using a subscript. This subscript variable can take
different values and hence can refer to the different elements in the array in turn.
Points to remember.
1. An array is a collection of similar elements.
2. The first element in the array is numbered 0, so the last element is less then the size of the
array.
3. An array is also known as the subscripted variable.
4. Before using an array its type and dimension must be declared.
5. An array elements are always stored in adjacent memory location.
6. Array starts from the 0th location.
Two types of array
1. Single dimensional array.
e.g.:
#include<stdio.h>
#include<conio.h>
main()
{
int mark[10],avg,n,sum=0,i;
clrscr();
printf("Enter how many nos:");
scanf("%d",&n);
for(i=0;i<n;i++) /* store datas in an array */
{
printf("Enter marks one by one:");
scanf("%d",&mark[i]);
}
for(i=0;i<n;i++)
sum=sum+mark[i]; /* read data from an array */
avg=sum/n;
printf("Average marks=%d",avg);
getch();
}
Array Initialization
1. If the array elements are not given any specific values, they are supposed to contain garbage
values.
2. If the array is initialized where it is declared, mentioning the dimension of the array is optional.
3. If the array is initialized where it is declared, its storage class must be either static or extern.
e.g.:
---
int num[6]={2,4,3,4};
int num[] = { 2,4,4,7,8};
2. Two dimensional array
A two dimensional array is also called as matrix.
Declaration
Prof M. P. Raj (B. Tech - AIT) Page: 32/48
Programming in C (AIT 112)
Syntax:
data type variable name[ row dimension] [ column dimension];
e.g.:
int a[3][3];
e.g.:
#include<stdio.h>
#include<conio.h>
main()
{
int stud[4][2];
int i.j;
clrscr();
for(i=0;i<=3;i++)
{
printf(Enter roll no and marks:);
scanf(%d%d,&stud[i][0],&stud[i][1]);
}
for(i=0;i<=3;i++)
printf(%d\t%d\n,stud[i][0],stud[i][1]);
getch();
}
The array elements are being stored and accessed row wise.
Initializing a 2 dimensional array
While initializing an array it is necessary to mention the second (column) dimension,
whereas the first dimension (row) is optional.
e.g.:
int student [4] [2] = {
{124,89},
{125,90},
{145,90}
};
Multidimensional Array
A three dimensional array can be thoght of as an array of arrays. In practice, one rarely
uses this array.
E.g.:
int stud [2] [2] [2] = {
{
{2,3},
{4,8},
{ 8,10}
},
{
{ 3,8},
{9,7},
{7,5}
}
};
{
char name[10]="Lavanya";
int i=0;
clrscr();
while(name[i]!='\0')
{
printf("%c",name[i]);
i=i+1;
}
getch();
}
Note
1. The length of the string should not exceed the dimension of the character arry.
2. scanf() is not capable of receiving multiword strings. So in that case we can use gets () instead
of scanf ().
Some important programs
Matrix addition
#include<stdio.h>
#include<conio.h>
main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
printf("Enter the first matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:",i+1);
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
printf("Enter the second matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:",i+1);
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
}
clrscr();
printf("The Matrix Addition is below\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("\t%d",c[i][j]);
}
printf("\n");
}
getch();
}
Matrix multiplication
#include<stdio.h>
#include<conio.h>
main()
{
int a[3][3],b[3][3],c[3][3],i,j,k;
clrscr();
printf("Enter the first matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:\n",i+1);
for(j=0;j<3;j++)
Prof M. P. Raj (B. Tech - AIT) Page: 34/48
Programming in C (AIT 112)
scanf("%d",&a[i][j]);
}
printf("Enter the second matrix value one by one:\n");
for(i=0;i<3;i++)
{
printf("Enter the %d row value:\n",i+1);
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
}
clrscr();
printf("The matrix multiplication is below\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<3;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][i];
}
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
Program to find the Maximum of n numbers
#include<stdio.h>
#include<conio.h>
main()
{
int a[10],big,i,n;
clrscr();
printf("Enter no of values:");
scanf("%d",&n);
printf("Enter the values one by one:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
big=a[0];
for(i=1;i<n;i++)
{
if(big<a[i])
{
big=a[i];
}
}
printf("Biggest no is:\n");
printf("%d\n",big);
getch();
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Ascending order values \n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
getch();
}
UNIT-V
Define Pointer, Pointer Arithmetic, passing pointer to function, Function data return with a Pointer,
Define structure, passing structure to a function, Unions, typedef, array of structure and pointer to structure.
Pointers
Pointers are special variables that contain addresses i.e. it represents the location of a data item,
such as variable or an array element.
Like normal variables, pointer variables should be declared in the beginning of the program.
Pointer Declaration
Syntax:
data type *variable name;
e.g.:
int *a;
float *cd;
char *name;
Operators in pointers
& address of operator
* value at address operator.
E.g.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
clrscr();
printf("%d\n",i);
printf("%d\n",&i);
getch();
}
Pointer Expressions
Pointer assignment
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
int *j;
j=&i;
clrscr();
printf("%d\n",i);
printf("%d\n",j);
printf("%d\n",&i);
printf("%d\n",&j);
printf("%d\n",*j);
printf("%d",*(&i));
getch();
}
Pointer Arithmetic
1. Addition of a no to a pointer.
2. Subtraction of one pointer from another pointer.
3. Subtraction of a no from a pointer
4. Comparing two pointers pointing to the objects of the same type.
1. Addition of a no to a pointer
e.g.: 1
#include<stdio.h>
#include<conio.h>
void main()
{
Prof M. P. Raj (B. Tech - AIT) Page: 37/48
Programming in C (AIT 112)
int i=4,*j,*k;
j=&i;
k=&j;
clrscr();
printf("%d\n",i);
printf("%d\n",j);
printf("%d\n",k);
j=j+1;
k=j+3;
printf("%d\n",j);
printf("%d\n",k);
getch();
}
Eg: 2
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3,*x;
float j=1.5,*y;
char k='c',*z;
clrscr();
printf("%d\n",i);
printf("%f\n",j);
printf("%c\n",k);
x=&i;
y=&j;
z=&k;
printf("%d\n",x);
printf("%d\n",y);
printf("%d\n",z);
x++;;
y++;
z++;
printf("%d\n",x);
printf("%d\n",y);
printf("%d",z);
getch();
}
{
static int arr[]={10,20,30,40,67,74};
int *i,*j;
i=&arr[1];
j=&arr[5];
clrscr();
printf("%d\t%d",j-i,*j-*i);
getch();
}
Note:
Here both the pointers should point to the same array.
First difference
In the above program Nagpur gets stored in arr[] and the base address of it is stored in s.
Second difference
E.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
static int arr[10]="Nagpur";
char *s="Nagpur";
clrscr();
s++;
printf("%s\n",s);
arr++;
printf("%s",arr);
getch();
}
Here the Output of s is agpur but the output of an arr is an error message.i.e the compiler
assumes us that we are attempting to change its base address.
Third difference
e.g.
#include<stdio.h>
#include<conio.h>
void main()
{
static char arr[]="Nagpur";
char *s="Nagpur";
clrscr();
printf("Size of arr=%d\n",sizeof(arr));
printf("Size of s=%d",sizeof(s));
getch();
}
Another difference between arrays and pointers are the way the size of operator treats them.
In the above program, size of arr is 7 and size of s is 2.
Array of pointers
Array of pointers is nothing but collection of addresses.
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
int *arr[4];
int i=31,j=5,k=19,l=71,m;
arr[0]=&i;
arr[1]=&j;
arr[2]=&k;
arr[3]=&l;
clrscr();
for(m=0;m<=3;m++)
{
printf("%d\t",arr[m]);
printf("%d\n",*(arr[m]));
}
getch();
}
void main()
{
static int a[]={0,1,2,3,4};
static int *p[]={a,a+1,a+2,a+3,a+4};
clrscr();
printf("%d\t%d\t%d",p,*p,*(*p));
getch();
}
Array of pointers is very popular used for storing several strings in memory.
eg:
Static char *names[]={
kavitha,
anitha,
harini,
};
Pointers to pointers
e.g.:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=3;
int *j;
int **k;
j=&i;
k=&j;
clrscr();
printf("%d\n",i);
printf("%d\n",&i);
printf("%d\n",j);
printf("%d\n",&j);
printf("%d\n",*j);
printf("%d\n",k);
printf("%d\n",&k);
printf("%d\n",*k);
printf("%d\n",*(&i));
printf("%d",**k);
getch();
}
Pointers to functions
eg:1
#include<stdio.h>
#include<conio.h>
void main()
{
void display();
clrscr();
printf("%d\n",display);
display();
getch();
}
void display()
{
printf("Test for function");
Prof M. P. Raj (B. Tech - AIT) Page: 43/48
Programming in C (AIT 112)
EG:2
#include<stdio.h>
#include<conio.h>
void main()
{
void display();
void (*funcptr)();
clrscr();
funcptr=display;
printf("%d\n",funcptr);
(*funcptr)();
getch();
}
void display()
{
puts("Hello");
}
Uses
1. To write memory resident programs.
2. To write viruses or vaccines to remove the viruses
display(b1);
getch();
}
void display(b)
struct book b;
{
printf("%s\n%s\n%d",b.name,b.author,b.bno);
}
Structures
Structures are collection of unlike data types. Like arrays, structure elements are stored in
contiguous memory locations.
There are two steps to define a structure.
1. Declaration of a structure.
2. Accessing of structure elements.
Declaring a structure
Syntax:
struct structure name
{
struct element 1;
struct element 2;
struct element 3;
};
e.g.:
struct book
{
char bookname[25];
float price;
int bookno;
};
};
struct book b1,b2;
clrscr();
printf("Enter the first book details:\n");
scanf("%s%f%d",b1.name,&b1.price,&b1.pages);
Prof M. P. Raj (B. Tech - AIT) Page: 45/48
Programming in C (AIT 112)
Like array variables, structure variables are also directly initialized where they are created.
E.g.:
Struct book
{
char name[2];
float price;
int pages;
};
struct book b1={Basic,150.40,230};
struct book b2={C++,140.60,250};
Array of structures
e.g.:
#include<stdio.h>
#include<conio.h>
main()
{
struct book
{
char name[25];
int pages;
int price;
};
struct book b[10];
int i,n;
clrscr();
printf("Enter how many books:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the name,pages,price:\n");
scanf("%s%d%d",b[i].name,&b[i].pages,&b[i].price);
}
for(i=0;i<n;i++)
printf("Name=%s\nPages=%d\nPrice=%d\n",b[i].name,b[i].pages,b[i].price);
getch();
}
Structures within structures ( Nested structure)
eg:
#include<stdio.h>
#include<conio.h>
main()
{
struct address
{
char phone[15];
char city[25];
int pin;
};
struct emp
{
char name[25];
struct address a;
};
struct emp e={"Kavitha","530146","nagpur",10};
clrscr();
printf("Name=%s\nPhone=%s\n",e.name,e.a.phone);
printf("City=%s\nPin=%d",e.a.city,e.a.pin);
getch();
}
Uses of structures
strcutures are used in variety of applications .The most important are in the database
management system.
Unions
Unions are similar to structures .The main difference between these two is a structure enables us
to treat a number of different variables stored at different places in memory. A union enables us
to treat the same space in memory at a no of different variables.
Uses of unions
They are useful for applications involving multiple elements, where values need not be
assigned to all the elements at any one of time.
OR
Unions like structure contain members whose individual data types may differ from one another.
However the members that compose a union all share the same storage area within the
computers memory where as each member within a structure is assigned its own unique storage
area. Thus unions are used to conserve memory. They are useful for application involving
multiple members. Where values need not be assigned to all the members at any one time. Like
structures union can be declared using the keyword union as follows:
union item
{
int m;
float p;
char c;
}
code;
this declares a variable code of type union item. The union contains three members each with a
different data type. However we can use only one of them at a time. This is because if only one
location is allocated for union variable irrespective of size. The compiler allocates a piece of
storage that is large enough to access a union member we can use the same syntax that we use
to access structure members. That is
code.m
code.p
code.c
are all valid member variables. During accessing we should make sure that we are accessing the
member whose value is currently stored.
For example a statement such as
code.m=456;
code.p=456.78;
printf(%d,code.m);
Would produce erroneous result.
In effect a union creates a storage location that can be used by one of its members at a time.
When a different number is assigned a new value the new value supercedes the previous
members value. Unions may be used in all places where a structure is allowed. The notation for
accessing a union member that is nested inside a structure remains the same as for the nested
structure.
3) Structure: The size in bytes is the sum total of size of all the elements in the structure, plus
padding bytes. Size of in bytes of the union is size of the largest variable element in the union.
While structure enables us treat a number of different variables stored at different in memory, a
union enables us to treat the same space in memory as a number of different variables. That is a
Union offers a way for a section of memory to be treated as a variable of one type on one
occasion and as a different variable of a different type on another occasion.
Structure pointers
A pointer pointing to a structure is known as structure pointer
E.g.
#include<stdio.h>
#include<conio.h>
void main()
{
struct book
{
char name[25];
char author[25];
int bno;
};
static struct book b1={"C","Balagurusamy",120};
struct book *ptr;
ptr=&b1;
clrscr();
printf("%s\n%s\n%d\n",b1.name,b1.author,b1.bno);
printf("%s\n%s\n%d",ptr->name,ptr->author,ptr->bno);
getch();
}