EC22303 UNIT 1 notes
EC22303 UNIT 1 notes
3 0 0 3
R1. Anita Goel and Ajay Mittal, “Computer Fundamentals and Programming in C”, First
Edition, Pearson Education, 2013.
R2. Paul J. Deitel, Harvey Deitel, “C How to Program”, Seventh Edition, Pearson Education,
2013.
R3. Alfred V. Aho, John E. Hopcroft, Jeffrey D. Ullman, “Data Structures and Algorithms”,
Pearson Education, 2016.
R4. Ellis Horowitz, Sartaj Sahni and Susan Anderson, “Fundamentals of Data Structures”,
Galgotia, 2018.
R5. Kernighan, B.W and Ritchie, D.M, “The C Programming language”, Second Edition,
Pearson Education, 2015.
Additional References
Books (AR):
AR1. Reema Thareja, “Data structures using C”, Second Edition, 2014.
Journals/Magazines (J):
J1.https://www.routledge.com/Data-Structures-using-C-A-Practical-Approach-for-Beginners/
Jagtap-Mali/p/book/9780367616311
J2.
https://www.researchgate.net/publication/259058750_Programming_and_Data_Structure_usin
g_C
Program 1.1
/* Program to find the area of a circle */ /* Documentation Section
*/ # include<stdio.h> /* Preprocessor Section */
# include<conio.h>
# define PI 3.14 /* Definition Section */
void main() /* main( ) function */
{
float area,r; /* Local variable declaration */
clrscr(); // Executable part of the program
printf("\n Enter the radius:\
n"); scanf("%f",&r);
area= PI*(r*r);
printf("\n Area of the Circle = %8.2f", area);
getch();
}
Output
Enter the radius: 4.5
Area of the Circle = 63.58
Program 1.2
/* Program to find the sum of two numbers using function */
/*Documentation Section */
# include<stdio.h> /* Preprocessor Section
*/ # include<conio.h>
int a,b; /* Global Variable declaration */
int add(int,int); /* Function declaration */
void main() /* main( ) function */
{
int c; /* Local Variable declaration */
clrscr(); // Executable part of the main()
program printf("\n Enter the values for a and b:\n");
scanf("%d
%d",&a,&b); c =
add(a,b);
printf("\n Sum of %d + %d = %d",
a,b,c); getch();
}
int add(int a,int b) /* Subprogram of add() function definition */
{
int c; /* Local Variable declaration */
c=a+b; // Executable part of the
function return(c);
}
Output
Enter the values for a and b: 5 3
Sum of 5 + 3 = 8
Documentation section
The documentation section is included in the comments, which contains the author
name, the date of development and the program details.
Preprocessor section
The preprocessor section provides preprocessor statements which direct the
compiler to link functions from the system library.
Definition section
The definition section defines all symbolic constants refer to assigning a macro
of a name to a constant. The general syntax of a symbolic constant is
#define constant_name constant_value
Global declaration section
The global declaration section contains variable declarations which can be
accessed anywhere within the program.
Main section
Main section is divided into two portions, the declaration part and the executable
part. The declaration part used to declare any variables in the main block of the
program. The executable part contains set of statements within the open and close
braces. Execution of the program begins at the opening braces and ends at the closing
braces.
User defined function section
The user defined function section (or) the Sub program section contains user
defined functions which are called by the main function. Each user defined function
contains the function name, the argument and the return value.
www.poriyaa
n.in
1.5.6 Constants
Constants are fixed values and they remain unchanged during the execution of
the program. The constants are classified as follows:
Integer constants
It consist of a sequence of digits without any decimal point. Integer constant can
be written in three different number systems: decimal, octal and hexadecimal. A
decimal integer constant can consist of any combination of digits taken from the
set 0 through 9.
1. Decimal number – 0 to 9
2. Octal number – 0 to 7
3. Hexadecimal number – 0 to 9, A, B, C, D, E, F
Examples
Decimal number – 10, 145,-89, 067 etc.
Octal number – 037, 0, 057, 0456 etc.
Hexadecimal number – 0x4, 0x9C, 0xAFE etc.
Rules for an integer constant
o It must have at least one digit.
o Decimal point is not allowed.
o It can be either positive or negative.
o If it is negative the sign must be preceded. For positive the sign is not
necessary.
o No commas or blank spaces are allowed.
o The allowable range for integer constant is –32,768 to +32,767
Real Constant
It is made up of a sequence of numeric digits with presence of a decimal point.
It is to represent quantities that vary continuously such as distance, height,
temperature etc.
Example:
Distance=134.9;
Height=88.10;
Rules for a real constant
o It must have one digit.
o It must have decimal point.
o It can be either positive or negative.
o If it is negative the sign must be preceded. For positive the sign is not
necessary.
o No commas or blank spaces are allowed.
Character constants
Single Character Constant
It contains a single character enclosed within a pair of single quote marks.
Example
‘d’, ‘r’, ‘6’, ‘_’
String Constant
It is a sequence of characters enclosed in double quotes.
The characters may be letters, numbers, special characters and blank spaces
At the end of string ‘\0’ is automatically placed.
Example
“hai”
“4565”
1.6 OPERATORS IN C
Operator: An operator is a symbol that specifies an operation to be performed on
operands. Eg: x= a+b; where + is an operator.
Operands: An operand is an entity on which an operation is to be performed. An
operand can be a variable name, a constant, a function call or a macro name.
Eg. x= a+b; where x, a, b are the operands.
Expression: An expression is a sequence of operands and operators that specifies the
computations of a value. An expression is made up of one or more operands. Eg. x= a+b.
Example:
void main()
{
int a=5, b=4, c;
c=a-b;
printf(“%d”,
c);
}
The following table show the division operator on various data types.
Operation Result Example
int/int int 2/5=0
real/int real 5.0/2=2.5
int/real real 5/2.0=2.5
real/real real 5.0/2.0=2.5
Arithmetic operators can be classified as
o Unary arithmetic – it requires only one operand.
Example: +a, -b
o Binary arithmetic – it requires two operands.
Example: a+b, a-b, a/b, a%b
o Integer arithmetic – it requires both operands to be integer type for
arithmetic operation.
Example:
a=4, b=3
a+b =4+3 =7
a-b =4-3=1
o Floating Point arithmetic – It requires both operands to be float type for
arithmetic operation.
Example:
a=6.5, b=3.5
a+b =6.5+3.5 =10.0
a-b =6.5-3.5=3.0
Program 1.3
#include<stdio.h>
#include<conio.h
> void main()
{
int b,c;
int sum, sub,
mul; float div;
clrscr();
printf(“enter the value of
b,c:”); scanf(“%d%d”, &b,
&c);
sub=b-c;
mul=b*c
;
div=b/c;
printf(“\n sum=%d,sub=%d,mul=%d,div=
%f”,sum,sub,mul,div); getch();
}
Output:
Enter the value of b,c: 8 4
sum=12,sub=4,mul=32,div=
2
Syntax
AE1 operator AE2
where, AE- Arithmetic Expression or Variable or Value.
These operators provide the relationship between two expressions.
If the condition is true it returns a value 1, otherwise it returns 0.
These operators are used in decision making process. They are generally used in
conditional or control statement.
1.6.1.3 Logical Operators
Logical Operators are used to combine the result of two or more conditions.
The logical relationship between the two expressions is checked with logical
operators.
After checking the condition, it provides logical true (1) or false (0).
Operators Descriptions Example Return Value
&& Logical AND 5>3 && 1
5<10
|| Logical OR 8>5 || 8<2 1
!= Logical NOT 8!=8 0
&& - This operator is usually used in situation where two or more expressions
must be true.
Syntax:
(exp1) && (exp2)
|| – This is used in situation, where at least one expression is true.
Syntax:
(exp1) || (exp2)
! – This operator reverses the value of the expression it operates on. (i.e.,) it
makes a true expression false and false expression true.
Syntax:
!(exp1)
Program 1.4
/* Program using Logical operators */
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr( );
printf("\n Condition : Return values ");
printf("\n 5<=8 && 4>2: %5d",5<=8 && 4>2);
printf("\n !(7==7): %5d",!(7==7));
getch( );
}
Output
Condition : Return values
5<=8 && 4>2 : 1
5>=3 || 6<8 : 1
!(7==7) : 0
Program 1.5
/* Program using Assignment and Short-hand Assignment operators */
#include<stdio.h>
#include<conio.h
> void main( )
{
int a=20,b=10,c=15,d=25,e=34,x=5;
clrscr( );
printf("\n Value of a=%d",a);
printf("\n Value of b=
%d",b); a+=x;
b- =x;
c*=x;
d/=x;
e
%=x;
printf("\n Value of a=
%d",a); printf("\n Value of
b=%d",b); printf("\n Value
of c=%d",c); printf("\n Value
of d=%d",d); printf("\n
Value of e=%d",e); getch();
Outpu }
t
Value of a = 20
Value of b = 10
Value of a = 25
Value of b = 5
Value of c = 75
Value of d = 5
Value of e = 4
Pre-increment operator
This operator increment the value of a variable first and then perform other
Program 1.6
#include
<stdio.h> void
main()
{
int
a,b;
a=10;
b=++a;
printf(“a=
%d”,a);
printf(“b=%d”,b);
}
output: a=11
b=11 #include
<stdio.h> void
main()
{
int
a,b;
a=10;
b=—a; printf(“a=
%d”,a);
printf(“b=%d”,b);
}
Output:
a=9 b=9
Post-increment operator
This operator perform other actions first and then increment the value of a
variable.
Program 1.7
#include
<stdio.h> void
main()
int
a,b;
a=10;
b=a++;
printf(“a=
%d”,a);
printf(“b=%d”,b);
}
Output:
a=11 b=10
Program 1.8
#include
<stdio.h> void
main()
{
int
a,b;
a=10;
b=a--; printf(“a=
%d”,a);
printf(“b=%d”,b);
}
Output:
a=9 b=10
a) Comma operator(,):
The comma operator is used to separate the statement elements such as
variables, constants or expression etc.,
This operator is used to link the related expression together.
Such expression can be evaluated from left to right and the value of right most
Example:
val=(a=3,b=9,c=77,a+c);
Where,
First assigns the value 3 to a
Second assigns the value 9 to b
Third assigns the value 77 to c
Last assigns the value 80.
b) The sizeof() operator:
The sizeof() is a unary operator that returns the length in bytes of the specified
variable and it is very useful to find the bytes occupied by the specified variable
in memory.
Syntax:
sizeof(var);
Example:
void main()
{
int a;
printf(“size of variable a is…%d”, sizeof(a));
}
Output:
size of variable a is…….2
c) Pointer operator:
& : This symbol specifies the address of the variable.
* : This symbol specifies the value of the variable.
d) Member selection operator:
. and — >: These symbols are used to access the elements from a structure.
1.7 EXPRESSIONS AND STATEMENTS
1.7.1 Expressions
An expression represents data item such as variables, constants and are
interconnected with operators as per the syntax of the language.
An expression is evaluated using assignment operators.
Syntax
Variable = expression;
Example: 1
x=a*b-c;
In example 1, the expression evaluated from left to right. After the evaluation of
the expression the final value is assigned to the variable from right to left.
Example: 2
a++;
In example 2, the value of variable a is incremented by 1, i.e, this expression is
equivalent to a = a + 1.
1.7.2 Statements
A statement is an instruction given to the computer to perform an action. There
are three different types of statements in C:
1. Expression Statements
2. Compound Statements
3. Control Statements
Expression Statement
An expression statement or simple statement consists of an expression followed
by a semicolon (;).
Example
a=100;
b=20;
c=a/b;
Compound Statement
A compound statement also called a block, consists of several individual
statements enclosed within a pair of braces { }.
Example
{
a=3;
b=10;
c=a+b;
}
Control Statement
A single statement or a block of statements can be executed depending upon a
condition using control statements like if, if-else, etc.
Example
a=10;
if (a>5)
{
b= a+10;
}
Program 1.20
/* Program to Generate the Even numbers to a given limit*/
#include<stdio.h>
#include<conio.h
> void main()
{
int n,i;
printf(“\n Enter the
limit:”); scanf(“%d”,&n);
i=1;
while(i<=n)
{ if(i
%2==0)
printf(“%d\
t”,i); i++;
}
getch( );
}
Output
Enter the limit: 10
2 4 6 8 10
Do While Statement
The do while loop varies from the while loop in the checking condition. The
condition of the loop is not tested until the body of the loop has been executed
once. If the condition is false, after the first loop iteration the loop terminates.
The statements are executed atleast once even if the condition fails for the first
time itself. It is otherwise called as exit control loop.
auto
register
static
extern
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be used within functions,
i.e., local variables.
The register should only be used for variables that require quick access such as counters. It should also be noted
that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be
stored in a register depending on hardware and implementation restrictions.
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the
program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making
local variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to
be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that member to be shared
by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
The extern storage class is used to give a reference of a global variable that is visible to ALL the program
files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage
location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be used in other files,
then extern will be used in another file to provide the reference of defined variable or function. Just for
understanding, extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same global variables
or functions as explained below.
First File: main.c
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Second File: support.c
void
write_extern(
void) {
printf("count
is %d\n",
count);
}
Here, extern is being used to declare count in the second file, where as it has its definition in the first file, main.c.
Now, compile these two files
it produces the following result −
count is 5
Compilation process:
Once a C program is written, it should run through a compiler to create an executable
file
i.e. a machine readable file. The compiler translates the source code into an
object code i.e. machine instructions for CPU, call to OS API etc.
The compilation process composed of the following steps:
1. The pre-processor programs read the source file as the text to produce another
output text file.
2. The linker combines the object file with the library routine to produce the final
executable file.
Steps in executing the C program:
1. Save the program with .c extension.
2. Compile the C program using a compiler.
3. Execute or run the program.
4. The output is generated on giving the required input to the
program which can be stored if needed.
FUNCTIONS
Introduction
A function is a sub program which contains a set of instructions that are used to
perform specified tasks
A function is used to provide modularity to the software. By using function can
divide complex task into manageable tasks. The function can also help to avoid
duplication of work.
Advantages of Functions
Code reusability
Better readability
Reduction in code redundancy
Easy to debug & test.
How Does Function Work?
Once a function is called, it takes some data from the calling function and
returns back some value to the called function.
Whenever function is called control passes to the called function and working of
the calling function is temporarily stopped, when the execution of the called
function is completed then a control return back to the calling function and
executes the next statement.
The function operates on formal and actual arguments and send back the result
to the calling function using return() statement.
Types of Functions
Functions are classified into two types
a) User defined functions
b) Predefined functions or Library functions or Built-in functions
a) User-defined functions
User-defined functions are defined by the user at the time of writing a program.
Example: sum( ), square( )
b) Library functions [Built-in functions]
Library functions are predefined functions. These functions are already developed
Example: printf( ), scanf( )
Terminologies used in functions
A function f that uses another function g is known as the calling function, and g
is known as the called function.
The inputs that a function takes are known as arguments.
When a called function returns some result back to the calling function, it is said
to return that result.
The calling function may or may not pass parameters to the called function. If
the called function accepts arguments, the calling function will pass parameters,
else not.
Function declaration is a declaration statement that identifies a function’s
name, a list of arguments that it accepts, and the type of data it returns.
Function definition consists of a function header that identifies the function,
followed by the body of the function containing the executable code for that
function.
Function prototype
User Defined Function
The function defined by the users according to their requirements is called user
defined functions. The users can modify the function according to their
requirement.
Need For user Defined Functions
While it is possible to write any complex program under the main () function
and it leads to a number of problems, such as
The program becomes too large and complex
The users cannot go through at a glance.
The task of debugging, testing and maintenance becomes difficult.
Advantages of user Defined Functions
The length of the source program can be reduced by dividing it into the smaller
functions.
By using functions it is very easy to locate and debug an error.
The user defined function can be used in many other source programs whenever
necessary.
Functions avoid coding of repeated programming of the similar instructions.
Functions enable a programmer to build a customized library of repeatedly used
routines.
Functions facilitate top-down programming approach.
1.9.1.2 Elements of user Defined Functions
In order to write an efficient user defined function, the programmer must be
familiar with the following three elements.
Function declaration
Function definition
Function call
Function Declaration
A function declaration is defined as a prototype of a function which consists of
the functions return type, function name and arguments list
It is always terminated with semicolon (;)
Function prototypes can be classified into four types
a) Function with no arguments and no return values
b) Function with arguments and no return values
c) Function with arguments and with return values
d) Function with no arguments and with return values
Syntax
return_type function_name (parameter_list);
Where,
return_type can be primitive or non-primitive data type
function_name can be any user specified name
parameter_list can consist of any number of parameter of any type
Example
void add(void);
void
add(int,int); int
add(int,int); int
add(void);
a) Function with No Arguments and No Return Values
In this prototype, no data transfer takes place between the calling function and
the called function. (i.e) the called program does not receive any data from the
calling program and does not send back any value to the calling program.
Syntax:
void
function_name(void);
void main()
{
…….
function_name()
;
…..
}
void function_name(void)
{
…..
……
}
Program 1.22
/*Implementation of function with no return type and no argument list*/
#include<stdio.h>
#include<conio.h
>
void add(void); //function declaration with no return type and
no arguments list
void main()
{
}
void add()
{
}
Output:
int a,b,c;
printf(“Enter the two numbers . . .
“); scanf(“ %d %d”,&a,&b);
c=a+b;
printf(“sum is . . . %d”,c);
Enter the two numbers . . . 10 20
Sum is . . . 30
b) Function with Arguments and No Return Values
In this prototype, data is transferred from calling function to called function. i.e
the called program receives some data from the calling program and does not
send back any values to calling program.
Syntax:
void
function_name(arguments_list);
void main()
{
…….
function_name(argument_list)
;
…..
}
void function_name(arguments_list)
{
//function body
}
Program 1.23
/*Implementation of function with no return type and with argument list*/
#include<stdio.h>
#include<conio.h
>
int add(int,int); ); //function declaration with no return type and with
arguments list
void main()
{
int a,b,;
clrscr();
printf(“enter the two values:
“); scanf(“ %d %d”,&a,&b);
add(a,b); /*calling a function with arguments
*/ getch();
}
void add(int x,int y)
{
int z;
z=x+y
;
printf(“Sum is........%d”,z);
Output:
Enter two values: 10 20
Sum is.........30
c) Function with arguments and With Return Values
In this prototype, data is transferred between calling function and called
function.( i.e) the called program receives some data from the calling program
and send back a return value to the calling program.
Value received from a function can be further used in rest of the program.
Syntax:
return_type
function_name(arguments_list); void main()
{
…….
variable_name=function_name(argument_list)
;
…..
}
return_type function_name(arguments_list)
{
//function body
}
Program 1.24
#include<stdio.h>
#include<conio.h
>
int add(int,int); //function declaration with return type and with arguments
list void main()
{
int a,b,c;
clrscr();
printf(“enter the two numbers:
“); scanf(“ %d %d”,&a,&b);
c=add(a,b); /*calling function with
arguments*/ printf(“sum is . . . %d “, c);
getch();
}
int add(int x,int y)
{
int z;
z=x+y
;
} return(z); /*returning result to calling function*/
Output:
Enter the two numbers: 10 20
sum is. . 30
d) Function with No Arguments and with Return Values
In this prototype, the calling program cannot pass any arguments to the called
program. i.e) program may send some return values to the calling program.
Syntax:
return_type
function_name(void); void main()
{
…….
variable_name=function_name()
;
…..
}
return_type function_name(void)
{
//function body
}
Program 1.25
/*Implementation of function with return type and no argument
list*/ #include<stdio.h>
#include<conio.h>
int add(void); //function declaration with no return type and no arguments
list void main()
int c;
c=add(); //function call
printf(“sum is . . . %d”,c);
}
int add(void)
{
int a,b,c;
printf(“Enter the two numbers . . .
“); scanf(“ %d %d”,&a,&b);
c=a+b;
return(c)
;
}
Function Definition
It is the process of specifying and establishing the user defined function by
specifying all of its elements and characteristics.
When a function is defined, space is allocated for that function in the memory.
A function definition comprises of two parts:
Function header
Function Body
Syntax
return_type function_name(argument_list)
{
//function body
}
Example
int add(int x, int y)
{
int z;
return(z);
}
Program 1.26
#include<stdio.h>
// function prototype, also called function
declaration float square ( float x );
// main function, program starts from here
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
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 some number for finding square
2
Square of the given number 2.000000 is 4.00000
Function Call
The function can be called by simply specifying the name of the function, return
The function call statement invokes the function. When a function is invoked,
the compiler jumps to the called function to execute the statements that are a part
of that function. Once the called function is executed, the program control passes
back to the calling function.
Syntax
function_name();
function_name(parameter);
variable_name=function_name(parameter)
; variable_name=function_name();
Example
add();
add(a,b);
c=add(a,b)
; c=add;
There are two ways that a C function can be called from a program. They are,
a) Call by value
b) Call by reference
a) Function-Call by value
In the call by value method the actual arguments are copied to the formal
arguments, hence any operation performed by function on arguments doesn’t
affect actual parameters.
b) Function-Call by Reference
Unlike call by value, in this method, address of actual arguments (or parameters)
is passed to the formal parameters, which means any operation performed on
formal parameters affects the value of actual parameters.
Actual parameters: The parameters that appear in function calls.
Formal parameters: The parameters that appear in function declarations.
Program 1.27
//Example program for Actual Parameter and Formal Parameters
int sum(int a, int b)
{
int
c=a+b;
return c;
}
int main(
{
int var1 =10;
int var2 = 20;
int var3 = sum(var1,
var2); printf("%d", var3);
return 0;
}
In the above example variable a and b are the formal parameters (or formal
arguments). Variable var1 and var2 are the actual arguments (or actual parameters). The
actual parameters can also be the values. Like sum(10, 20), here 10 and 20 are actual
parameters.
Program 1.28
//Example of Function call by Value
#include <stdio.h>
int increment(int var)
{
var =
var+1;
return var;
}
int main()
{
int num1=20;
int num2 = increment(num1);
printf("num1 value is: %d", num1);
printf("\nnum2 value is: %d",
num2); return 0;
}
Output
Before swapping:
num1 value is 35
num2 value is 45
After swapping:
num1 value is 45
num2 value is 35
#include<
stdio.h>
#include<conio.h
> void main()
{
int
fact(int);
int num,f;
clrscr();
printf(“enter the
number”);
scanf(“%d”,&num);
f=fact(num);
printf(“ the factorial of %d= %d”, num, f);
int f;
if(x==1)
return(1)
; else
f=x*fact(x-1); //recursive function
call return (f);
}
Output:
Enter the number 5
The factorial of 5=120
ARRAYS
Introduction to Arrays
An Array is a collection of similar data elements
These data elements have the same data type
The elements of the array are stored in consecutive memory locations and are
referenced by an index
Definition
An array is a data structure that is used to store data of the same type. The
position of an element is specified with an integer value known as index or
subscript.
Example
Declaration of an Array
Array has to be declared before using it in C program. Declaring array means
specifying three things.
Data_type Data Type of Each Element of the array
Array_name Valid variable name
Size Dimensions of the Array
Arrays are declared using the following syntax:
type name[size]
Here the type can be either int, float, double, char or any other valid data type. The
number within the brackets indicates the size of the array, i.e., the maximum number of
elements that can be stored in the array.
Example: i) int marks[10]
ii) int a[5]={10,20,5,56,100}
The declaration of an array tells the compiler that, the data type, name of the
array, size of the array and for each element it occupies memory space. Like for int data
type occupies 2 bytes for each element and for float occupies 4 bytes for each element
etc. The
size of the array operates the number of elements that can be stored in an array.
Initialization of arrays
Elements of the array can also be initialized at the time of declaration as in the
case of every other variable. When an array is initialized, we need to provide a value for
every element in the array. Arrays are initialized using the following syntax:
type array_name [size] = { list of values};
The values are written with curly brackets and every value is separated by a comma.
It is a compiler error to specify more number of values than the number of elements in
the array.
Example: int marks [5] = {90, 92, 78, 82, 58};
Example
int a[4]; // a is an array of 4 integers
Initialization of single dimensional array
Elements of an array can also be initialized. After declaration, the array elements
must be initialized otherwise they hold garbage value. An array can be initialized
at compile time or at run time.
Elements of an array can be initialized by using an initialization list. An
initialization list is a comma separated list of initializers enclosed within braces.
Example
1. int a[3]={1,3,4};
2. int i[5] ={1, 2, 3, 4, 5};
3. float a[5]={1.1, 2.3, 5.5, 6.7, 7.0};
4. int b[ ]={1,1,2,2};
In the fourth example the size has been omitted (it can be) and have been
declared as an array with 4 elements having 1, 1, 2 and 2 as initial values.
Character arrays that hold strings allow a shortcut initialization of the form:
char array_name[size]=”string”
For example,
char mess[ ]={‘w’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’};
If the number of initializers in the list is less than array size, the leading array
locations gets initialized with the given values. The rest of the array locations
gets initialized to
0 - for int array
0.0 - for float array
\0 - for character array
Example
int a[2]={1}; a
1 0
char b[5]={‘A’.’r’,’r’}; b
Output:
Enter 5 numbers one by one
57364
The maximum number in the array is 7
Program 1.33
/*Program for reversing an array*/
#include<stdio.h>
{
int a[10],
i; int n;
printf(“Enter the maximum number of elements\
n”); scanf(“%d”, &n);
for(i=0; i<n; i++)
{
scanf(“%d”,&a[i]);
}
printf(“Array in the reverse order\
n”); for(i=n–1; i>=0; i--)
{
printf(“%d\t”, a[i]);
}
getch( );
}
Output
Enter the maximum number of elements
5 11 12 13 14 15
Array in the reverse order
15 14 13 12 11
Program 1.34
/* Program to calculate sum of array content */
#
include<stdio.h>
void main( )
{
int a[20], n, i, sum = 0;
print f(“\n Enter the size of the array:”);
scanf(“%d”, &n)
printf (“\n Enter the %d numbers one by
one:”); for (i=0; i<n; i++)
{
scanf(“%d”,
&a[i]); sum = sum
+ a[i];
}
printf (“The sum of array content = %d”,
sum); getch( );
}
Output
MULTI-DIMENSIONAL ARRAY
A multi-dimensional array is an array that has more than one dimension. It is an
array of arrays; an array that has multiple levels. The simplest multi-dimensional
array is the 2D array, or two-dimensional array and 3D or three-dimensional
array.
Declaration
datatype arrayname [row size][column size]
a 1 4 6
2 0 0
}
}
/* Program module to sum colwise
*/
for(i=0;i<n;i++)
{
colsum=0;
for(j=0;j<n1;j+
+) colsum+=a[j]
[i];
printf(“col no=%d sum=%d\n “,i,colsum);
}
diasum=0;
for(i=0;i<n;i++)
for(j=0;j<n1;j++)
if(i==j) diasum+=a[i]
[j];
printf(“Principle diagonal sum %d\n”,diasum);
/ * Program module to sum off diagonal */
diasum=0;
for(i=0;i<n;i+
+)
{
j= -n1;
diasum +=a[i][j];
} }
Output printf(“Off diagonal sum%d\n”,diasum);
Enter order [row][col] of the matrix
33
Enter 9 elements
123456789
Sum of all elements 45
row no = 0 sum = 6
row no = 1 sum = 15
row no = 2 sum = 24
col no = 0 sum = 12
col no = 1 sum = 15
col no = 2 sum = 18
Principle diagonal sum 15
Off diagonal sum 15
1.13.2 Three-Dimensional Arrays
Initialization of a 3d array
Initialize a three-dimensional array in a similar way to a two-dimensional array.
Example
int test[2][3][4] = {
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
Program 1.36
Write a C Program to store and print 12 values entered by the user
#include <stdio.h>
int main()
{
int test[2][3][2];
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}
// Printing values with the proper index.
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}
return 0;
}
Output
Enter 12 values:
1
2
3
4
5
6
7
8
9
10
11
12
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
String Functions:
C Programming allows us to perform different string processing operations through the
functions defined in <string.h> header file. The <string.h> header file contains various methods for
performing mathematical operations such as
Illustrations
Program: Output:
strstr()
#include <stdio.h> Output string is: Programming
#include <string.h>
int main()
{
char inputstr[70] = "String Function in C
Programming";
printf ("Output string is: %s", strstr(inputstr,
"Pro"));
}
strchr( )
#include <stdio.h> String after '.' is ".google.com"
#include <string.h>
int main () {
const char str[] =
"http://www.google.com"; const char ch =
'.';
char *ret;
ret = strchr(str, ch);
printf("String after \'%c\' is \"%s\"\n", ch, ret);
}
strrev( )
#include<stdio.h> The given string is =C Programming
#include<string.h> After reversing string is =gnimmargorP
int main() C
{
char str[50] = "C Programming";
printf("The given string is =%s\n",str);
printf("After reversing string is
=%s",strrev(str));
return 0;
}
strupr( )
#include<stdio.h> PROGRAMMING IN C
#include<string.h>
int main()
{
char str[ ] = "programming in C";
//converting the given string into uppercase.
printf("%s\n", strupr (str));
return 0;
}
strlwr( )
#include<stdio.h> Programming in C
#include<string.h>
int main()
{
char str[ ] = " PROGRAMMING IN C";
// converting the given string into lowercase.
printf("%s\n",strlwr (str));
return 0;
}
strstr( )
#include<stdio.h> Substring is: C Programming
#include <string.h>
int main(){
char str[100]="this is C
Programming"; char *sub;
sub=strstr(str,"C Pro");
printf("\nSubstring is: %s",sub);
return 0;
}
strset( ), strnset( )
#include <stdio.h> This is the string: abcdefghi
#include <string.h> This is the string after strnset:
int main(void) xxxxefghi This is the string after strset:
kkkkkkkkk
{
char str[] = "abcdefghi";
printf("This is the string: %s\n", str);
printf("This is the string after strnset: %s\n",
strnset((char*)str, 'x', 4));
printf("This is the string after strset: %s\n",
strset((char*)str, 'k'));
return 0;
}
strtok( )
#include <string.h> /* Splits str[] according to given delimiters
#include <stdio.h> returns next token. It needs to be called i
int main () { loop to get all tokens. It returns NULL w
char str[80] = "This is - www.google.com - there are no more tokens.*/
website";
const char s[2] =
"-"; char *token; This is
/* get the first token */ www.google.com
token = strtok(str, s); website
/* walk through other tokens */
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, s);
}
return(0);
}
REVIEW QUESTIONS
PART-A
1. List down the Primary Data Types in C
Integer – We use these for storing various whole numbers, such as 5, 8, 67,
2390, etc.
Character – It refers to all ASCII character sets as well as the single alphabets,
such as ‘x’, ‘Y’, etc.
Double – These include all large types of numeric values that do not come
under either floating-point data type or integer data type.
Floating-point – These refer to all the real number values or decimal points,
such as 40.1, 820.673, 5.9, etc.
Void – This term refers to no values at all. We mostly use this data type when
defining the functions in a program.
2. What is Variable?
Variables are containers for storing data values.
Its value can be changed, and it can be reused many times.
Syntax for creating variables
type variableName = value;
Example: int a = 5;
3. What is Operator?
An operator is a special symbol that tells the compiler to perform specific
mathematical or logical operations.
Operators in programming languages are taken from mathematics.
C language supports a rich set of built-in operators.
4. List the types of operators supported in C
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Type Information Operators(Special operators)
5. What is Ternary operators or Conditional operators?
Ternary operators is a conditional operator with symbols? and :
Syntax: variable = exp1 ? exp2 : exp3
If the exp1 is true variable takes value of exp2. If the exp2 is false, variable
takes the value of exp3.
6. What is an Operator and Operand?
An operator is a symbol that specifies an operation to be performed on
operands.
Example: *, +, -, / are called arithmetic operators.
The data items that operators act upon are called operands.
7. What is type casting?
Type casting is the process of converting the value of an expression to a
particular data type.
Example: int x,y.
c = (float) x/y; where a and y are defined as integers. Then the result of x/y is
converted into float.
8. What is the difference between while loop and do while loop?
while do while
In the while loop the condition is first In the do…while loop first the
executed. statement is executed and then the
condition is checked.
If the condition is true, then it executes The do…while loop will execute at
the body of the loop. When the least one time even though the
condition is false it comes of the loop. condition is false at the very first time.
PART-B
1. Explain the different types of operators with neat examples.
2. Illustrate the different conditional statements available in C with syntax and
examples
3. Explain the looping statements with neat examples.
4. What is an Array? Explain Single and Multi-Dimensional arrays with neat examples.
5. Write a C program for Matrix Multiplication with a 3*3 matrix.
6. Create a C program for Matrix Addition.
7. Write a C program to calculate the total, average and grade for 50 Students.
8. Write a C program to calculate the factorial of a given number.
9. Write a C program to check whether a given number is odd or even.
10. Write a C program to check whether a given number is prime or not.
11. Write a C program to check whether a given number is a palindrome or not.
12. Write a C program to check whether a given number is a Armstrong number or not.