C Programming Unit 1-14-112
C Programming Unit 1-14-112
in/
in
C PROGRAMMING
n.
FUNDAMENTALS
aa
Data Types – Variables – Operations – Expressions and Statements – Conditional
iy
Statements – Functions – Recursive Functions – Arrays – Single and Multi-Dimensional
Arrays.
or
.p
1.1 INTRODUCTION TO PROGRAMMING PARADIGMS
w
➢ Paradigm can also be termed as method to solve some problem or do some task.
➢ Programming paradigm is an approach to solve problem using some
w
in
Disadvantage
n.
1. Complex problem cannot be solved
2. Less efficient and less productive
aa
3. Parallel programming is not possible
iy
Examples of Imperative programming paradigm: C, FORTAN, Basic
or
.p
w
w
w
in
➢ Example: C, C++, JAVA, Pascal.
n.
[Link] Object Oriented Programming
aa
➢ It is a type of programming in which programmers define not only the data type
of a data structure, but also the types of operations (functions) that can be applied
iy
to the data structure.
➢ In this way, the data structure becomes an object that includes both data and
or
functions. In addition, programmers can create relationships between one object
.p
and another. For example, objects can inherit characteristics from other objects.
➢ One of the principal advantages of object-oriented programming techniques over
w
programmer can simply create a new object that inherits many of its features from
w
existing objects. This makes object-oriented programs easier to modify. The basic
concepts of OOP are as follows:
1. Objects 2. Classes
3. Data abstraction and encapsulation 4. Inheritance
5. Polymorphism 6. Dynamic binding
7. Message passing.
Objects:
Objects are the basic run-time entities in an object oriented system. They may
represent a person, place or a bank a/c or a table of data that the program has to handle.
When a program is executed the objects interact by sending messages to one another.
They can interact without knowing the details of each other’s data or code. Thus an object
is considered to be a partitioned area of computer memory that stores data and set of
functions that can access the data.
1.4 C Programming Fundamentals
[Link] [Link]
Classes:
The entire set of data and code of an object can be made a user-defined data type
with the help of a class. Objects are variables of the type class. Each object is associated
with the data of type class with which they are created. A class is thus a collection of
objects of similar type.
in
n.
aa
iy
or
.p
w
Encapsulation:
The wrapping up of data and functions in to a single unit (that unit is called a
class) is known as encapsulation. The data is not accessible to the outside world (other
functions which are not the members of that class) and only those functions which are
wrapped in the class can access it. This insulation of data from the direct access by the
program is called data hiding or information hiding.
Abstraction:
Abstraction refers to the act of representing essential features without including
the background details or explanations. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, weight and cost and functions to operate
on these attributes. The attributes are sometimes called data members because they hold
information. The functions that operate on these data are called member functions.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of
C Programming and Data Structures 1.5
[Link] [Link]
concept of inheritance provides the idea of reusability. This means that we can include
additional features to an existing class without modifying it. It is important because it
supports the concept of classification. C++ supports different types of inheritance such as
single inheritance, multiple inheritance, multilevel inheritance and hierarchical
inheritance.
To understand the concept of inheritance, let us consider an example of vehicles
in
as shown in Fig.1.3. Here the class car is a subclass of automatic vehicle, which is again
n.
a subclass of the class vehicle. This implies that the class car has all the characteristics of
automatic vehicles which in turn has all the properties of vehicles. However, car has some
aa
unique features which differentiate it from other subclasses. For example, it has four
wheels and five gears, while scooter has two wheels and four gears.
iy
or
.p
w
w
w
in
OOP consists of a set of objects that communicate with each other by sending and
receiving information. A message for an object is a request for execution of a procedure
n.
(function) and therefore will invoke a function in the receiving object that generates the
aa
desired result.
Benefits of OOP
iy
➢ Through inheritance we can eliminate redundant code and extend the use of
existing classes.
or
➢ We can build secure programs by the principle of data hiding.
.p
➢ It is easy to partition the work in a project based on objects.
➢ Object oriented systems can be easily upgraded from small to large systems.
w
passing techniques.
➢ Software complexity can be easily managed.
w
Applications of OOP
OOP can be applied in the following areas:
➢ Real time systems
➢ Simulation and modeling
➢ Object oriented data bases
➢ Hypertext, hypermedia and expertext
➢ Artificial Intelligence and expert systems.
➢ Neural networks and parallel programming
➢ Office automation systems
➢ CIM / CAM / CAD systems
Example: Simula, JAVA, Python, [Link], Ruby.
C Programming and Data Structures 1.7
[Link] [Link]
[Link] Parallel processing approach
➢ Parallel processing is the processing of program instructions by dividing them
among multiple processors. A parallel processing system possess many numbers
of processor with the objective of running a program in less time by dividing
them. This approach seems to be like divide and conquer.
in
➢ Examples are NESL (one of the oldest one) and C/C++ also supports because of
some library function.
n.
1.1.2 Declarative programming paradigm
aa
➢ It is divided as Logic, Functional, and Database. In computer science
the declarative programming is a style of building programs that expresses logic
iy
of computation without talking about its control flow.
➢ It often considers programs as theories of some logic. It may simplify writing
or
parallel programs. The focus is on what needs to be done rather how it should
.p
be done basically emphasize on what code is actually doing.
➢ It just declare the result we want rather how it has be produced. This is the only
w
programming paradigms.
w
in
[Link] Database/Data driven programming approach
n.
➢ This programming methodology is based on data and its movement. Program
aa
statements are defined by data rather than hard-coding a series of steps.
➢ A database program is the heart of a business information system and provides
iy
file creation, data entry, update, query and reporting functions. There are several
programming languages that are developed mostly for database application.
or
➢ For example SQL. It is applied to streams of structured data, for filtering,
.p
transforming, aggregating (such as computing statistics), or calling other
programs. So it has its own wide application.
w
➢ A programming language must be simple, easy to learn and use, have good
w
in
laboratories. The various stages in evolution of C language is given in Fig 1.4.
n.
CPL (Combined Programming Language)
Developed by Cambridge and University of London in 1963
aa
iy
BCPL (Basic Combined Programming Language)
Developed by Martin Richards in 1967
or
.p
B Language Developed by Ken Thompson at AT and T Bell
Laboratory in 1970
w
w
in
4. structured programming language
n.
5. Rich Library
aa
6. Memory Management
7. Fast Speed
iy
8. Pointers
9. Recursion or
10. Extensible
.p
1.3 APPLICATIONS OF C LANGUAGE
w
systems, like Windows or Linux, but also in the development of GUIs (Graphical
User Interfaces) and, IDEs (Integrated Development Environments).
w
in
5. Google
Google file system and Google chromium browser were developed using C/C++.
n.
Not only this, the Google Open Source community has a large number of projects being
handled using C/C++.
aa
6. Mozilla Firefox and Thunderbird
Since Mozilla Firefox and Thunderbird were open-source email client projects,
iy
they were written in C/C++.
7. MySQL or
MySQL, again being an open-source project, used in Database Management
.p
Systems was written in C/C++.
w
8. Compiler Design
One of the most popular uses of the C language was the creation of
w
compilers. Compilers for several other programming languages were designed keeping in
w
in
global declaration section
n.
main( )
{
aa
declaration part;
executable part;
iy
}
or
sub program
{
.p
body of the subprogram;
w
}
w
Program 1.1
w
in
Program 1.2
n.
/* Program to find the sum of two numbers using function */
aa
/*Documentation Section */
# include<stdio.h> /* Preprocessor Section */
iy
# include<conio.h>
int a,b;
int add(int,int);
or
/* Global Variable declaration */
/* Function declaration */
.p
void main() /* main( ) function */
w
{
w
in
name, the date of development and the program details.
n.
Preprocessor section
aa
The preprocessor section provides preprocessor statements which direct the
compiler to link functions from the system library.
iy
Definition section
The definition section defines all symbolic constants refer to assigning a macro of
or
a name to a constant. The general syntax of a symbolic constant is
.p
#define constant_name constant_value
Global declaration section
w
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.
in
i) Character set
n.
ii) Delimiters
aa
iii) Keywords
iv) Identifiers
iy
v) Data types
vi) Constants
vii) Variables
or
.p
1.5.1 Character Set
w
➢ The set of characters used to write the program words, expressions and statements.
w
It is the basic building block to form program elements. The set of characters used
in a language is known as its character set. These characters can be represented
w
in the computer.
➢ The C character set consists of upper and lower case alphabets, digits, special
characters and white spaces. The alphabets and digits are together called the
alphanumeric characters.
i) Alphabets
A, B, C,…..Z
a, b, c,….z
ii) Digits
0123456789
1.16 C Programming Fundamentals
[Link] [Link]
iii) Special Characters
Table 1.1 List of Special Characters
in
n.
aa
iy
or
.p
w
v) Trigraph characters
The trigraph characters are used to type certain characters that are not
available on some keyboards. It consists of three characters. Two question
marks followed by character.
C Programming and Data Structures 1.17
[Link] [Link]
1.5.2 Delimiters
➢ The language pattern of C uses a special kind of symbols, which are called
delimiters. They are given in Table. 1.3.
in
n.
aa
iy
or
.p
Table 1.3 Delimiters
1.5.3 Keywords
w
➢ These are certain reserved words called keywords, which are standard, predefined
w
in
i) The first character must be a letter followed by a letter or a digit.
n.
ii) Special characters are not allowed except underscore.
iii) The length of the variable varies from one compiler to another. Generally,
aa
most of the compilers support eight characters excluding extension. However,
the ANSI standard recognizes the maximum length of a variable up to 31
iy
characters.
iv) The variable should not be a C keyword.
or
v) The variable names may be a combination of upper and lower characters. For
.p
example, suM and sum are not the same variable.
vi) The variable name should not start with a digit.
w
Examples
w
in
n.
aa
iy
or
.p
w
w
w
in
type. For example the size of a floating point data type in a 16 bit computer is
n.
4 bytes. For Example: float rate = 5.6;
o Double: Double data type is similar to floating data type except that it
aa
provides up to ten digits of precision and occupies eight bytes of memory. For
Example: double d = 11676.2435676542;
iy
o Void Data Type: Void is an empty data type that has no value. This can be
or
used in functions and pointers.
Type modifiers in C
.p
➢ In c language Data Type Modifiers are keywords used to change the current
w
properties of data type. Data type modifiers are classified into the following types.
o Long
w
o Short
w
o Unsigned
o signed
➢ Modifiers are prefixed with basic data types to modify (either increase or
decrease) the amount of storage space allocated to a variable. For example, storage
space for int data type is 4 bytes for a 32 bit processor. We can increase the range
by using long int which is 8 bytes. We can decrease the range by using short int
which is 2 bytes.
long
➢ This can be used to increase the size of the current data type by 2 more bytes,
which can be applied on int or double data types. For example int occupy 2 bytes
of memory; if we use long with integer variable, then it occupies 4 bytes of
memory.
C Programming and Data Structures 1.21
[Link] [Link]
in
n.
aa
Syntax
iy
long a; —> by default which represent long int
short or
➢ In general int data type occupies different memory spaces for a different operating
.p
systems; to allocated fixed memory space a short keyword can be used.
w
Syntax
short int a; —> occupies 2 bytes of memory space in every operating system
w
unsigned
w
➢ This keyword can be used to make the accepting values of a data type of positive
data type.
Syntax
unsigned int a = 100; // right
unsigned int a = -100; // wrong
Signed
➢ This keyword accepts both negative and positive values and this is the default
property or data type modifier for every data type.
int a = 10; // right
int a = -10; // right
signed int a = 10; // right
signed int a = -10; // right
1.22 C Programming Fundamentals
[Link] [Link]
in
n.
aa
Table 1.5 Size and range of Integer type on 16-bit machine
iy
or
.p
w
w
in
n);
n.
Syntax for function definition
<return type> function name (parameter list)
aa
parameter declarations
{
iy
body of the function;
or
return (expression);
}
.p
Example
w
{
w
int z;
z = x;
x = y;
y = z;
}
➢ Pointers
o Pointer is a variable which stores the address of another variable.
Example
int *p; // declaration of pointer
int x; // declaration of variable
p=&x; // pointer variable stores the address of x variable.
x=5 ; // x variable assigned with value 5.
1.24 C Programming Fundamentals
[Link] [Link]
User defined data types
➢ The user defined data types enable a program to invent his own data types and
define what values it can taken on. Thus these data types can help a programmer
to reducing programming errors.
➢ C supports the following user defined data types.
in
o Structures
n.
A structure is a single entity representing a collection of data items of
different data types.
aa
Example
struct student
iy
{
int roll_no;
char fname[25];
or
.p
char branch[15];
w
int marks;
w
}s1;
o Unions
w
A union is a data type in ‘c’ which allows overlay of more than one variable
in the same memory area.
Example
union emp
{
char name[20];
char eno[10];
}
union emp e1;
o Enumerated data type
A enumerated data type is a set of values represented by identifiers called
enumeration constants. It is a user-defined data type and the general format of
C Programming and Data Structures 1.25
[Link] [Link]
enum name {number 1, number 2, ... number n};
In above format enum is a keyword, name is given by the programmer by the
identifier rules. number 1, number 2, ... number n are the member of
enumerated datatype.
o Type definition
in
“type definition” that allows user to define an identifier that would represent
a data type using an existing data type.
n.
Syntax:
aa
typedef type identifier;
typedef <existing_data_type> <new_user_define_data_type>;
iy
Example
typedef int number; or
typedef long big_ number;
.p
typedef float decimal;
w
1.5.6 Constants
1.26 C Programming Fundamentals
[Link] [Link]
➢ 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
in
decimal integer constant can consist of any combination of digits taken from the
set 0 through 9.
n.
1. Decimal number – 0 to 9
aa
2. Octal number – 0 to 7
3. Hexadecimal number – 0 to 9, A, B, C, D, E, F
iy
➢ Examples
or
Decimal number – 10, 145,-89, 067 etc.
Octal number – 037, 0, 057, 0456 etc.
.p
Hexadecimal number – 0x4, 0x9C, 0xAFE etc.
w
in
necessary.
o No commas or blank spaces are allowed.
n.
Character constants
aa
Single Character Constant
➢ It contains a single character enclosed within a pair of single quote marks.
iy
Example
‘d’, ‘r’, ‘6’, ‘_’ or
String Constant
.p
➢ It is a sequence of characters enclosed in double quotes.
w
➢ The characters may be letters, numbers, special characters and blank spaces
w
“hai”
“4565”
in
5. char char;
Variable declaration with qualifiers
n.
Examples
aa
1. short int number;
2. unsigned int total;
iy
3. long int ser_no;
4. long double volume;
Variable Initialization
or
.p
➢ Assigning a relevant value to a variable for the first time in a program is known
as initialization. Sometimes a variable may be initialized on its declaration itself.
w
Syntax:
w
in
where, const is a keyword, a is a variable name and 20 is a constant value. The
compiler protects the value of ‘a’ from modification. The user cannot assign any
n.
value to a; by scanf ( ) statement the value can be replaced.
aa
Volatile variable
➢ The volatile variables are those variables that are changed at any time by any other
iy
external program or the same program. The syntax is as follows.
Example
volatile int b;
or
.p
where volatile is a keyword and b is a variable If the value of a variable in the
current program is to be maintained constant and desired not to be changed by any
w
other external operation, then the declaration of the variable will be as follows;
w
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.
in
[Link] Arithmetic Operators
➢ Addition, subtraction, multiplication, division and modulo are the arithmetic
n.
operations.
➢ The arithmetic operators are used for numerical calculations between two
aa
Constants
iy
Operators Explanations Examples
+ Addition 2+2=4
-
or
Subtraction 3-2=1
.p
* Multiplication 5 * 4 =20
/ Division 10 / 2 = 5
w
% Modular Division 11 % 2 = 1
w
Example:
w
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
C Programming and Data Structures 1.31
[Link] [Link]
➢ 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
in
o Integer arithmetic – it requires both operands to be integer type for
n.
arithmetic operation.
Example:
aa
a=4, b=3
a+b =4+3 =7
iy
a-b =4-3=1
or
o Floating Point arithmetic – It requires both operands to be float type for
arithmetic operation.
.p
Example:
w
a=6.5, b=3.5
w
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);
1.32 C Programming Fundamentals
[Link] [Link]
sub=b-c;
mul=b*c;
div=b/c;
printf(“\n sum=%d,sub=%d,mul=%d,div=%f”,sum,sub,mul,div);
getch();
in
}
n.
Output:
aa
Enter the value of b,c: 8 4
sum=12,sub=4,mul=32,div=2
iy
[Link] Relational Operators
or
➢ Relational operators are used to compare two or more operands.
➢ Operands may be variable, constant or expression
.p
Operators Descriptions Example Return Value
w
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.
[Link] Logical Operators
C Programming and Data Structures 1.33
[Link] [Link]
➢ 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
in
5<10
n.
|| Logical OR 8>5 || 8<2 1
!= Logical NOT 8!=8 0
aa
➢ && - This operator is usually used in situation where two or more expressions
must be true.
iy
Syntax:
(exp1) && (exp2)
or
.p
➢ || – This is used in situation, where at least one expression is true.
Syntax:
w
(exp1) || (exp2)
w
➢ ! – This operator reverses the value of the expression it operates on. (i.e.,) it makes
w
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);
1.34 C Programming Fundamentals
[Link] [Link]
printf("\n !(7==7): %5d",!(7==7));
getch( );
}
Output
Condition : Return values
in
5<=8 && 4>2 : 1
n.
5>=3 || 6<8 : 1
aa
!(7==7) : 0
iy
➢ Assignment Operator are used to assign constant or a value of a variable or an
expression to another variable.
or
Syntax
.p
variable =expression (or) value;
w
Example
x=10;
w
x=a+b;
w
x=y;
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;
C Programming and Data Structures 1.35
[Link] [Link]
b-=x;
c*=x;
d/=x;
e%=x;
printf("\n Value of a=%d",a);
in
printf("\n Value of b=%d",b);
n.
printf("\n Value of c=%d",c);
printf("\n Value of d=%d",d);
aa
printf("\n Value of e=%d",e);
getch();
iy
}
Output
Value of a = 20
or
.p
Value of b = 10
w
Value of a = 25
w
Value of b = 5
Value of c = 75
w
Value of d = 5
Value of e = 4
Pre-increment operator
➢ This operator increment the value of a variable first and then perform other
1.36 C Programming Fundamentals
[Link] [Link]
Program 1.6
#include <stdio.h>
void main()
{
int a,b;
in
a=10;
n.
b=++a;
printf(“a=%d”,a);
aa
printf(“b=%d”,b);
iy
}
output: a=11 b=11 or
#include <stdio.h>
.p
void main()
{
w
int a,b;
w
a=10;
w
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()
C Programming and Data Structures 1.37
[Link] [Link]
int a,b;
a=10;
b=a++;
printf(“a=%d”,a);
printf(“b=%d”,b);
in
}
n.
Output:
a=11 b=10
aa
Program 1.8
#include <stdio.h>
iy
void main()
{
or
.p
int a,b;
a=10;
w
b=a--;
w
printf(“a=%d”,a);
w
printf(“b=%d”,b);
}
Output:
a=9 b=10
in
[Link] Bitwise Operators
n.
➢ Bitwise operators are used to manipulate the data at bit level.
aa
➢ It operates on integers only.
➢ It may not be applied to float or real.
iy
Operator Meaning
&
|
or Bitwise AND
Bitwise OR
.p
^ Bitwise XOR
w
~ One’s complement
w
in
{
n.
int a;
aa
clrscr( );
printf("\n Enter the value for a : ");
iy
scanf("%d",&a);
printf("\n The One's complement value for a is : %d", ~a);
or
getch( );
.p
}
Output
w
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
1.40 C Programming Fundamentals
[Link] [Link]
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
in
Third assigns the value 77 to c
n.
Last assigns the value 80.
aa
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
iy
in memory.
Syntax: or
sizeof(var);
.p
Example:
w
void main()
w
{
w
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.
C Programming and Data Structures 1.41
[Link] [Link]
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.
in
Syntax
n.
Variable = expression;
aa
Example: 1
x=a*b-c;
iy
➢ 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
or
.p
a++;
➢ In example 2, the value of variable a is incremented by 1, i.e, this expression is
w
equivalent to a = a + 1.
w
1.7.2 Statements
w
in
a=3;
n.
b=10;
c=a+b;
aa
}
Control Statement
iy
➢ A single statement or a block of statements can be executed depending upon a
or
condition using control statements like if, if-else, etc.
Example
.p
a=10;
w
if (a>5)
w
{
w
b= a+10;
}
in
➢ The syntax for a simple if statement is
n.
if (expression)
aa
{
block of statements;
iy
}
➢ In this statement, if the expression is true, the block of statements are executed
or
otherwise false and it comes out of the if condition.
.p
w
w
w
in
{
n.
printf(“\n The given number%d is divisible by 2", n);
aa
}
getch();
iy
}
Output or
Enter the number : 10
.p
The given number 10 is divisible by 2
w
Program 1.11
/* Program to check the given numbers are equal or not */
w
#include<stdio.h>
w
#include<conio.h>
void main()
{
int m,n;
clrscr();
printf(“\n Enter two numbers:”);
scanf(“%d %d”, &m,&n);
if (m==n)
printf(“\n Two numbers are equal”);
getch();
}
Output
C Programming and Data Structures 1.45
[Link] [Link]
Two numbers are equal.
❖ If –else statement
➢ The syntax for the if-else statement is
if(expression)
{
in
block of statements1;
n.
}
aa
else
{
iy
block of statements2;
} or
.p
w
w
w
in
int n;
n.
printf(“\n Enter the number:”);
scanf(“%d”,&n);
aa
if(n>0)
iy
{
printf(“\n The given number %d is positive”, n);
or
}
.p
else
{
w
}
w
}
Output
Enter the number : 5
The given number 5 is positive.
Program 1.13
/* Program to find the given number is even or odd */
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
C Programming and Data Structures 1.47
[Link] [Link]
printf(“\n Enter the number:”);
scanf(“%d”,&a);
if (a%2==0)
printf(“\n %d is an even number”,a);
else
in
printf(“%d is an odd number”,a);
n.
getch();
aa
}
Output
iy
Enter the number: 10
10 is an even number. or
❖ Conditional Expression
.p
➢ The ternary operator is used to form a conditional expression. It uses three
operands and hence it is called as a ternary operator. The syntax for a conditional
w
expression is:
w
expression-3 is evaluated.
1.48 C Programming Fundamentals
[Link] [Link]
Program 1.14
/* Program to find biggest of two given numbers */
#include<stdio.h>
void main()
{
in
int x,y,z;
n.
printf(“\n Enter the value of x and y:”);
scanf(“%d%d”,&x,&y);
aa
z = ((x>y)?x:y);
iy
printf(“The biggest value is %d”,z);
getch(); or
}
.p
Output
Enter the value of x and y: 5 10
w
❖ If-else-if statement
w
in
otherwise the expression2 is evaluated, if it is true then statements2 is executed,
n.
otherwise the expression3 is evaluated, if it is true then statements3 is executed,
otherwise statements4 is executed.
aa
iy
or
.p
w
w
w
in
}
n.
elseif((Avg_Mark>=60) && (Avg_Mark<75))
aa
{
printf(“First Class”);
iy
}
elseif((Avg_Mark>=50) && (Avg_Mark<60))
or
{
.p
printf(“Second Class”);
}
w
{
w
printf(“Third Class”);
}
else
{
printf(“Fail”);
}
}
Output
Enter the Average Mark : 65
First Class
Program 1.16
Write a program to calculate the gross salary for the conditions given below:
C Programming and Data Structures 1.51
[Link] [Link]
in
n.
/* Program to Calculate the gross salary */
#include<stdio.h>
aa
#include<conio.h>
void main()
iy
{
float bs, hra, da, cv, ts;
or
.p
clrscr();
printf(“\n Enter Basic salary:”);
w
scanf(“%f”,&bs);
w
if(bs>=5000)
w
{
hra = bs*20/100;
da = bs*110/100;
cv = 500;
}
else if(bs>=3000 && bs<5000)
{
hra = bs*15/100;
da = bs*100/100;
cv = 400;
}
else if(bs<3000)
1.52 C Programming Fundamentals
[Link] [Link]
hra = bs*10/100;
da = bs*90/100;
cv = 300;
}
ts = bs+hra+da+cv;
in
printf(“\nBasic salary: %5.2f”,bs);
n.
printf(“\nHRA: %5.2f”,hra);
printf(“\nDA: %5.2f”,da);
aa
printf(“\nConveyance: %5.2f”,cv);
iy
printf(“\nGross Salary: %5.2f”,ts);
getch(); or
}
.p
Output
Enter basic salary: 5400
w
HRA: 1080
w
DA: 5940
Conveyance: 500
Gross salary: 12920
❖ Nested if statement
➢ The syntax for the nested if statement is
if(expression1)
{
statements1;
}
else
{
if(expression2)
C Programming and Data Structures 1.53
[Link] [Link]
statements2;
}
else
{
statements3;
in
}
n.
}
aa
iy
or
.p
w
w
w
in
printf(“The Biggest number = %d”,x);
n.
}
aa
else
{
iy
if(y>z)
{ or
printf(“The Biggest number =%d”,y);
.p
}
else
w
{
w
}
}
getch();
}
Output
Enter the three numbers: 5 2 8
The Biggest number = 8
❖ Switch () Case Statement
➢ The switch ( ) case statement is like if statement that allows us to make a decision
from a number of choices. The switch statement requires only one argument of
any data type, which is checked with a number of case options.
➢ The switch statement evaluates the expression and then looks for its value among
the case constants.
C Programming and Data Structures 1.55
[Link] [Link]
➢ If the value matches with a case constant, this particular case statement is
executed. If not, the default is executed. The general syntax for the switch - case
statement is:
switch<exprn>
{
in
case constant_1:
{
n.
statements1;
aa
break;
}
iy
case constant_2:
{
statements2;
or
.p
break;
w
}
w
case constant_3:
{
w
statements3;
break;
}
case constant_n:
{
statementsn;
break;
}
default:
{
default statements;
}
1.56 C Programming Fundamentals
[Link] [Link]
in
n.
aa
iy
or
.p
Fig. 1.12 Flowchart for Switch - Case statement
w
Program 1.18
w
in
{
n.
case 1:
aa
c = a + b;
printf(“\n Addition: %d”,c);
iy
break;
case 2: or
c = a - b;
.p
printf(“\n Subtraction: %d”,c);
break;
w
case 3:
w
c = a * b;
w
in
2. Subtraction
n.
3. Multiplication
aa
4. Division
5. Exit
iy
Enter your choice: 2
Enter two numbers: 40 20 or
Subtraction: 20
.p
[Link] Looping Statements
w
1. for statement
w
2. while statement
3. do-while statement
❖ For Loop Statement
➢ The for loop allows to execute a set of instructions until a certain condition is
satisfied. Condition may be predefined or open-ended.
➢ The syntax for loop this is follows:
for<initial value>;<condition>;<incrementation/decrementation>)
{
block of statements;
}
C Programming and Data Structures 1.59
[Link] [Link]
in
n.
aa
iy
or
.p
w
➢ Here the initial value means the starting value assigned to the variable and
condition in the loop counter to determine whether the loop should continue or
w
in
Enter the limit: 10
n.
1
aa
2
3
iy
4
5 or
6
.p
7
8
w
9
w
10
w
in
n.
aa
iy
or
.p
w
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)
{
1.62 C Programming Fundamentals
[Link] [Link]
printf(“%d\t”,i);
i++;
}
getch( );
}
in
Output
n.
Enter the limit: 10
aa
2 4 6 8 10
❖ Do While Statement
iy
➢ 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
or
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
.p
itself. It is otherwise called as exit control loop.
w
w
w
in
#include<conio.h>
n.
void main()
aa
{
int n,t,s,r;
iy
clrscr();
printf(“\n Enter the number”);
or
scanf(“%d”,&n);
.p
t=n;
s=0;
w
do
w
{
w
r=n%10;
s=(s*10)+r;
n=n/10;
} while(n>0);
if(t==s)
printf(“%d is a palindrome”,t);
else
printf (“%d is not a palindrome”, t);
getch( );
}
Output
Enter the number 242
1.64 C Programming Fundamentals
[Link] [Link]
1.9 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
in
divide complex task into manageable tasks. The function can also help to avoid
duplication of work.
n.
Advantages of Functions
aa
✓ Code reusability
✓ Better readability
iy
✓ Reduction in code redundancy
✓ Easy to debug & test.
How Does Function Work?
or
.p
➢ Once a function is called, it takes some data from the calling function and returns
w
the calling function is temporarily stopped, when the execution of the called
w
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
C Programming and Data Structures 1.65
[Link] [Link]
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.
in
➢ When a called function returns some result back to the calling function, it is said
n.
to return that result.
➢ The calling function may or may not pass parameters to the called function. If
aa
the called function accepts arguments, the calling function will pass parameters,
else not.
iy
➢ Function declaration is a declaration statement that identifies a function’s name,
or
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,
.p
followed by the body of the function containing the executable code for that
function.
w
➢ 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.
1.66 C Programming Fundamentals
[Link] [Link]
➢ 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.
in
➢ Functions facilitate top-down programming approach.
n.
[Link] Elements of user Defined Functions
➢ In order to write an efficient user defined function, the programmer must be
aa
familiar with the following three elements.
− Function declaration
iy
− Function definition
− Function call
or
.p
Function Declaration
➢ A function declaration is defined as a prototype of a function which consists of
w
in
the called function. (i.e) the called program does not receive any data from the
n.
calling program and does not send back any value to the calling program.
Syntax:
aa
void function_name(void);
void main()
iy
{
……. or
function_name();
.p
…..
w
}
w
void function_name(void)
w
{
…..
……
}
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()
{
1.68 C Programming Fundamentals
[Link] [Link]
}
void add()
{
int a,b,c;
printf(“Enter the two numbers . . . “);
in
scanf(“ %d %d”,&a,&b);
n.
c=a+b;
printf(“sum is . . . %d”,c);
aa
}
iy
Output:
Enter the two numbers . . . 10 20
or
Sum is . . . 30
.p
b) Function with Arguments and No Return Values
➢ In this prototype, data is transferred from calling function to called function. i.e
w
the called program receives some data from the calling program and does not
w
Syntax:
void function_name(arguments_list);
void main()
{
…….
function_name(argument_list);
…..
}
void function_name(arguments_list)
{
//function body
}
C Programming and Data Structures 1.69
[Link] [Link]
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
in
list
n.
void main()
{
aa
int a,b,;
clrscr();
iy
printf(“enter the two values: “);
or
scanf(“ %d %d”,&a,&b);
.p
add(a,b); /*calling a function with arguments */
getch();
w
}
w
{
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.
1.70 C Programming Fundamentals
[Link] [Link]
Syntax:
return_type function_name(arguments_list);
void main()
{
…….
in
variable_name=function_name(argument_list);
n.
…..
aa
}
return_type function_name(arguments_list)
iy
{
//function body or
}
.p
Program 1.24
w
#include<stdio.h>
#include<conio.h>
w
int add(int,int); //function declaration with return type and with arguments list
w
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)
{
C Programming and Data Structures 1.71
[Link] [Link]
int z;
z=x+y;
return(z); /*returning result to calling function*/
}
Output:
in
Enter the two numbers: 10 20
n.
sum is. . 30
aa
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.
iy
Syntax:
or
return_type function_name(void);
.p
void main()
{
w
…….
w
variable_name=function_name();
w
…..
}
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()
1.72 C Programming Fundamentals
[Link] [Link]
int c;
c=add(); //function call
printf(“sum is . . . %d”,c);
}
int add(void)
in
{
n.
int a,b,c;
printf(“Enter the two numbers . . . “);
aa
scanf(“ %d %d”,&a,&b);
iy
c=a+b;
return(c); or
}
.p
Function Definition
➢ It is the process of specifying and establishing the user defined function by
w
➢ When a function is defined, space is allocated for that function in the memory.
w
in
float square ( float x );
n.
// main function, program starts from here
aa
int main( )
{
iy
float m, n ;
or
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
.p
// function call
w
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
w
}
w
in
function_name();
function_name(parameter);
n.
variable_name=function_name(parameter);
aa
variable_name=function_name();
Example
iy
add();
add(a,b);
c=add(a,b);
or
.p
c=add;
w
➢ There are two ways that a C function can be called from a program. They are,
w
a) Call by value
b) Call by reference
w
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
C Programming and Data Structures 1.75
[Link] [Link]
int sum(int a, int b)
{
int c=a+b;
return c;
}
in
int main(
n.
{
aa
int var1 =10;
int var2 = 20;
iy
int var3 = sum(var1, var2);
printf("%d", var3); or
return 0;
.p
}
In the above example variable a and b are the formal parameters (or formal
w
arguments). Variable var1 and var2 are the actual arguments (or actual parameters). The
w
actual parameters can also be the values. Like sum(10, 20), here 10 and 20 are actual
parameters.
w
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;
1.76 C Programming Fundamentals
[Link] [Link]
printf("num1 value is: %d", num1);
printf("\nnum2 value is: %d", num2);
return 0;
}
Output
in
num1 value is: 20
n.
num2 value is: 21
aa
Program 1.29
//Example 2: Swapping numbers using Function Call by Value
iy
#include <stdio.h>
or
void swapnum( int var1, int var2 )
{
.p
int tempnum ;
w
var1 = var2;
/*Copying temporary variable value into var2 */
var2 = tempnum;
}
int main( )
{
int num1 = 35, num2 = 45;
printf("Before swapping: %d, %d", num1, num2);
/*calling swap function*/
swapnum(num1, num2);
printf("\nAfter swapping: %d, %d", num1, num2);
}
C Programming and Data Structures 1.77
[Link] [Link]
Output
Before swapping: 35, 45
After swapping: 45, 35
Program 1.30
Example 2: Function Call by Reference – Swapping numbers
in
#include
n.
void swapnum ( int *var1, int *var2 )
aa
{
int tempnum ;
iy
tempnum = *var1;
*var1 = *var2; or
*var2 = tempnum;
.p
}
int main( )
w
{
w
printf("Before swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
/*calling swap function*/
swapnum( &num1, &num2 );
printf("\nAfter swapping:");
printf("\nnum1 value is %d", num1);
printf("\nnum2 value is %d", num2);
return 0;
}
Output
Before swapping:
1.78 C Programming Fundamentals
[Link] [Link]
num2 value is 45
After swapping:
num1 value is 45
num2 value is 35
in
1.10 RECURSIVE FUNCTIONS
➢ Recursion is the process of calling the same function again and again until some
n.
condition is satisfied.
aa
➢ This process is used for repetitive computation.
Syntax:
iy
function_name()
{
function_name();
or
.p
}
w
Types of Recursion
a) Direct Recursion
w
b) Indirect Recursion
w
a) Direct Recursion
➢ A function is directly recursive if it calls itself.
Functionname1( )
{
….
Functionname1 ( ); // call to itself
….
}
Example
➢ A function is said to be directly recursive if it explicitly calls itself. Here, the
function Func() calls itself for all positive values of n, so it is said to be a directly
recursive function.
C Programming and Data Structures 1.79
[Link] [Link]
{
if (n == 0)
return n;
else
return (Func (n–1));
in
}
n.
b) Indirect Recursion
➢ Function calls another function, which in turn calls the original function.
aa
Functionname1 ( )
iy
{
…
Functionname2 ( );
or
.p
…
}
w
Functionname1 ( )
w
{
…
w
in
Program 1.31
n.
/*C program to find factorial of a given number using recursion*/
aa
#include< stdio.h>
#include<conio.h>
iy
void main()
{
int fact(int);
or
.p
int num,f;
w
clrscr();
printf(“enter the number”);
w
scanf(“%d”,&num);
w
f=fact(num);
printf(“ the factorial of %d= %d”, num, f);
}
int fact(int x)
{
int f;
if(x==1)
return(1);
else
f=x*fact(x-1); //recursive function call
return (f);
}
C Programming and Data Structures 1.81
[Link] [Link]
Output:
Enter the number 5
The factorial of 5=120
1.11 ARRAYS
in
Introduction to Arrays
➢ An Array is a collection of similar data elements
n.
➢ These data elements have the same data type
aa
➢ The elements of the array are stored in consecutive memory locations and are
referenced by an index
iy
Definition
or
➢ 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.
.p
Example
w
w
w
in
➢ Fixed Size: Whatever size, we define at the time of declaration of array, we can’t
exceed the limit. So it doesn’t grow the size dynamically like Linked List
n.
Classifications
aa
➢ In general arrays are classified as:
➢ One-Dimensional Array
iy
➢ Two-Dimensional Array
➢ Multi-Dimensional Array or
.p
1.11.1 Declaration of an Array
Array has to be declared before using it in C program. Declaring array means
w
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
C Programming and Data Structures 1.83
[Link] [Link]
1.11.2 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:
in
The values are written with curly brackets and every value is separated by a comma.
n.
It is a compiler error to specify more number of values than the number of elements in
the array.
aa
Example: int marks [5] = {90, 92, 78, 82, 58};
iy
1.12 ONE DIMENSIONAL ARRAY
➢ It is also known as single-dimensional arrays or linear array or vectors
or
➢ It consists of fixed number of elements of same type
.p
➢ Elements can be accessed by using a single subscript
w
Example
w
w
Example
int a[4]; // a is an array of 4 integers
1.84 C Programming Fundamentals
[Link] [Link]
1.12.2 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
in
initialization list is a comma separated list of initializers enclosed within braces.
Example
n.
1. int a[3]={1,3,4};
aa
2. int i[5] ={1, 2, 3, 4, 5};
3. float a[5]={1.1, 2.3, 5.5, 6.7, 7.0};
iy
4. int b[ ]={1,1,2,2};
➢ In the fourth example the size has been omitted (it can be) and have been declared
or
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:
.p
char array_name[size]=”string”
w
For example,
w
➢ 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’};
in
{
n.
int a[5], i, max;
printf(“Enter 5 numbers one by one \n”);
aa
for(i=0;i<5;i++)
iy
{
scanf(“%d”, & a[i]);
or
}
.p
max=a[0];
for(i=1;i<5;i++)
w
{
w
if (max<a[i])
w
max =a[i];
}
printf(“\n The maximum number in the array is %d”,max);
getch( ) ;
}
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>
1.86 C Programming Fundamentals
[Link] [Link]
{
int a[10], i;
int n;
printf(“Enter the maximum number of elements\n”);
scanf(“%d”, &n);
in
for(i=0; i<n; i++)
n.
{
scanf(“%d”,&a[i]);
aa
}
iy
printf(“Array in the reverse order\n”);
for(i=n–1; i>=0; i--)or
{
.p
printf(“%d\t”, a[i]);
}
w
getch( );
w
}
w
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:”);
C Programming and Data Structures 1.87
[Link] [Link]
scanf(“%d”, &n)
printf (“\n Enter the %d numbers one by one:”);
for (i=0; i<n; i++)
{
in
scanf(“%d”, &a[i]);
sum = sum + a[i];
n.
}
aa
printf (“The sum of array content = %d”, sum);
getch( );
iy
}
Output
or
.p
Enter the size of the array: 5
Enter the 5 number one by one:
w
10 20 30 40 50
w
in
Declaration
n.
datatype arrayname [row size][column size]
aa
Example: int a [2][3]; //a is an integer array of 2 rows and 3 columns
iy
Number of elements=2*3=6
Initialization or
1. By using an initialization list, 2D array can be initialized.
.p
e.g. int a[2][3] = {1,4,6,2}
w
a 1 4 6
w
2 0 0
w
in
for(i=0;i<n;i++)
n.
for(j=0;j<n1;j++)
aa
sum+=a[i][j];
printf(“Sum of all elements%d\n”,sum);
iy
/ * Program to module to sum row wise */
for(i=0;i<n;i++) or
{
.p
rowsum=0;
for(j=0;j<n1;j++)
w
{
w
rowsum+=a[i][j];
w
}
}
/* 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);
}
1.90 C Programming Fundamentals
[Link] [Link]
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);
in
/ * Program module to sum off diagonal */
n.
diasum=0;
aa
for(i=0;i<n;i++)
{
iy
j= -n1;
diasum +=a[i][j];
or
}
.p
printf(“Off diagonal sum%d\n”,diasum);
}
w
Output
w
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
C Programming and Data Structures 1.91
[Link] [Link]
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] = {
in
{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
n.
{{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};
aa
Program 1.36
Write a C Program to store and print 12 values entered by the user
iy
#include <stdio.h>
int main()
{
or
.p
int test[2][3][2];
w
{
w
in
}
n.
}
aa
}
return 0;
iy
}
Output or
Enter 12 values:
.p
1
2
w
3
w
4
w
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
C Programming and Data Structures 1.93
[Link] [Link]
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
in
test[1][1][1] = 10
n.
test[1][2][0] = 11
aa
test[1][2][1] = 12
iy
or
.p
w
w
w
1.94 C Programming Fundamentals
[Link] [Link]
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.
in
• Character – It refers to all ASCII character sets as well as the single alphabets,
n.
such as ‘x’, ‘Y’, etc.
• Double – These include all large types of numeric values that do not come under
aa
either floating-point data type or integer data type.
• Floating-point – These refer to all the real number values or decimal points,
iy
such as 40.1, 820.673, 5.9, etc.
•
or
Void – This term refers to no values at all. We mostly use this data type when
defining the functions in a program.
.p
2. What is Variable?
w
in
✓ If the exp1 is true variable takes value of exp2. If the exp2 is false, variable
n.
takes the value of exp3.
6. What is an Operator and Operand?
aa
✓ An operator is a symbol that specifies an operation to be performed on
operands.
iy
✓ Example: *, +, -, / are called arithmetic operators.
or
✓ The data items that operators act upon are called operands.
7. What is type casting?
.p
✓ Type casting is the process of converting the value of an expression to a
w
in
function.
n.
✓ The syntax for recursive function is:
function recurse() {
aa
// function code
recurse();
iy
// function code
}
or
.p
recurse();
12. Write short notes about main() function in ’C’ program.
w
in
✓ One-dimensional arrays
n.
✓ Multidimensional arrays
16. Write short notes on One-dimensional arrays.
aa
✓ A One-Dimensional Array in C programming is a special type of variable that
can store multiple values of only a single data type such as int, float, double, char
iy
etc.
or
✓ The syntax of declaring Two-dimensional arrays is:
➢ datatype array name [size]
.p
✓ Example
w
in
✓ Short
✓ Long
n.
✓ Signed
aa
✓ Unsigned
✓ long long
iy
21. What is the explanation for prototype function in C?
or
✓ Prototype function is a declaration of a function with the following information
to the compiler.
.p
• Name of the function.
w
• int sum(int,int);
22. What do you mean by the Scope of the variable?
✓ Scope of the variable can be defined as the part of the code area where the
variables declared in the program can be accessed directly. In C, all identifiers
are lexically (or statically) scoped.
23. Can a C program be compiled or executed in the absence of a main()?
✓ The program will be compiled but will not be executed. To execute any C
program, main() is required.
24. What is the main difference between the Compiler and the Interpreter?
Interpreter Compiler
Translates program one statement at a Scans the entire program and translates
time. it as a whole into machine code.
C Programming and Data Structures 1.99
[Link] [Link]
Interpreters usually take less amount of Compilers usually take a large amount
time to analyze the source code. of time to analyze the source code.
However, the overall execution time is However, the overall execution time is
comparatively slower than compilers. comparatively faster than interpreters.
No Object Code is generated, hence are Generates Object Code which further
in
memory efficient. requires linking, hence requires more
memory.
n.
Programming languages like Programming languages like C, C++,
JavaScript, Python, Ruby use Java use compilers.
aa
interpreters.
iy
or PART-B
.p
1. Explain the different types of operators with neat examples.
2. Illustrate the different conditional statements available in C with syntax and
w
examples
w
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.