0% found this document useful (0 votes)
51 views190 pages

Unit 1 Pds

- Programming languages can be divided into low-level languages that are closer to machine language like assembly language, and high-level languages that are closer to human language like C, Java, and Python. - Assembly language uses mnemonics instead of machine code but still requires translation, whereas high-level languages can be compiled into machine code or interpreted at runtime. - C is a general purpose high-level language that is compiled into machine code and is widely used because it is portable, efficient, and allows access to low-level system operations.

Uploaded by

monica11css
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views190 pages

Unit 1 Pds

- Programming languages can be divided into low-level languages that are closer to machine language like assembly language, and high-level languages that are closer to human language like C, Java, and Python. - Assembly language uses mnemonics instead of machine code but still requires translation, whereas high-level languages can be compiled into machine code or interpreted at runtime. - C is a general purpose high-level language that is compiled into machine code and is widely used because it is portable, efficient, and allows access to low-level system operations.

Uploaded by

monica11css
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 190

Programming Languages

• Machine language
• Assembly Language
– Mnemonics (opcodes) - low-level programming
language that must be converted into machine code
using software called an assembler.
• Higher level languages
– Compiled languages:
• C, C++, Pascal, Fortran
• Converted to machine code using compilers
– Interpreted Languages: Interpreter translates the code
line-by-line when the program is running.
• Basic,
• Lisp
Programming Languages
• Machine language
– Only the machine understands.
– Varies from one class of computers to another.
– Not portable.
– machine language is referred to as a binary language. It can
be run on a computer directly.
• High-level language
– Easier for the user to understand.
– Fortran, C, C++, Java, Cobol, Lisp, etc.
– Standardization makes these languages portable.
• For example, C is available for DOS, Windows, UNIX, Linux, MAC
platforms.
Contd.
• Assembly Language
– Mnemonic form of machine language.
– Easier to use as compared to machine language.
• For example, use “ADD” instead of “10110100”.

Assembly
language Machine
Assembler language
program
program
– Not portable (like machine language).
– Requires a translator program called assembler.
Contd.
• Assembly language is also difficult to use in
writing programs.
– Requires many instructions to solve a problem.
• Example: Find the average of three
numbers. In C,
MOV A,X ; A = X RES = (X + Y + Z) / 3
ADD A,Y ; A = A + Y
ADD A,Z ; A = A + Z
DIV A,3; A = A / 3
MOV RES,A ; RES = A
High-Level Language
• Machine language and assembly language
are called low-level languages.
– They are closer to the machine.
– Difficult to use.
• High-level languages are easier to use.
– They are closer to the programmer.
– Examples:
• Fortran, Cobol, C, C++, Java.
– Requires an elaborate process of translation.
• Using a software called compiler.
Contd.
Executable
code
HLL
Compiler Object code Linker
program

Library
Number System :: The Basics

• We are accustomed to using the so-called


decimal number system.
– Ten digits :: 0,1,2,3,4,5,6,7,8,9
– Every digit position has a weight which is a power
of 10.
• Example:
234 = 2 x 102 + 3 x 101 + 4 x 100
250.67 = 2 x 102 + 5 x 101 + 0 x 100 +
6 x 10-1+ 7 x 10-2
• A digital computer is built out of tiny
electronic switches.
– From the viewpoint of ease of manufacturing
and reliability, such switches can be in one of
two states, ON and OFF.
– A switch can represent a digit in the so-called
binary number system, 0 and 1.
• A computer works based on the binary
number system.
Digital Information
• Computers store all information digitally:
– Numbers
– Text
– Graphics and images
– Audio
– Video
– Program instructions
• In some way, all information is digitized – broken
down into pieces and represented as numbers
Binary Numbers
• Once information is digitized, it is represented and
stored in memory using the binary number system
• A single binary digit (0 or 1) is called a bit.
• A collection of 8 bits is called a byte.
– 00110010
• Word: Depends on the computer
– 4 bytes
– 8 bytes
The C Programming Language
Why learn C ?
• C is a general-purpose programming language created by
Dennis Ritchie at the Bell Laboratories in 1972.
• "Least common denominator" - good building block for
learning other languages
– Subset of C++
– Similar to JAVA
• Closeness to machine allows one to learn about
system-level details
• Portable - compilers available for most platforms
• Very fast
• It was developed to write DOS, UNIX operating system.
The first C program
#include <stdio.h>
void main ()
{
printf ("Hello, World! \n") ;
}
All programs run from the main function
printf is a function in the library stdio.h
To include any library use #include
Comments

• Any string of symbols placed between the


delimiters /* and */.
• Can span multiple lines
• Can’not be nested! Be careful.
• /* /* /* Hi */ is an example of a comment.
• /* Hi */ */ is going to generate a parse error
Keywords
– Reserved words that have standard, predefined
meanings in C.
– Cannot be used as identifiers.
– OK within comments.
– Standard C keywords:
auto break case char const continue default do
double elseelse enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
Identifiers
A token (word) composed of a sequence of letters,
digits, and underscore (_) character. (NO spaces.)
– First character cannot be a digit
– C is case sensitive, so beware (e.g. printf
≠Printf)
Identifiers such as printf normally would not be
redefined; be careful
Used to give names to variables, functions, etc.
Only the first 31 characters matter
Constants
0, 77, 3.14 examples.
• Strings: double quotes. “Hello”
• Characters: single quotes. ‘a’ , ‘z’
• Have types implicitly associated with them
• 1234567890999 too large for most machines
Variables
• Variables hold the values upon which a program
acts. They are the symbolic reference to values.
• The following declares a variable that will contain
an integer value.
int num_of_students ;
The compiler reserves an integer's worth of memory for
num_of_students
In C, all variables must be declared before they can be
used.
• A variable declaration conveys three pieces
of information
– the variable's identifier
– its type
– its scope - the region of the program in which the
variable is accessible.
(implicitly specified by the place in the code
where the declaration occurs.)
C Program # 2
• #include <stdio.h>
main ()
{
int num_of_students ;
scanf ("%d", &num_of_students) ;
printf ("%d \n", num_of_students) ;
}
Variables, Constants, Memory
Variables and constants
• All temporary variables are stored in
variables and constants.
– The value of a variable can be changed.
– The value of a constant does not change.
• Variables and constants are stored in main
memory.
Variables in Memory
Instruction executed Memory location allocated
to a variable X
X = 10
T
i X = 20 10
m
e X = X +1

X = X*5
Variables in Memory
Memory location allocated
Instruction executed to a variable X

X = 10
T
i X = 20 20
m
e X = X +1

X = X*5
Variables in Memory
Memory location allocated
Instruction executed to a variable X

X = 10
T
i X = 20 21
m
e X = X +1

X = X*5
Variables in Memory
Memory location allocated
Instruction executed to a variable X

X = 10
T
i X = 20 105
m
e X = X +1

X = X*5
Variables (contd.)

X = 20

20 X
Y=15

X = Y+3 ? Y

Y=x/6
Variables (contd.)

X = 20

20 X
Y=15

X = Y+3 15 Y

Y=x/6
Variables (contd.)

X = 20

18 X
Y=15

X = Y+3 15 Y

Y=x/6
Variables (contd.)

X = 20

18 X
Y=15

X = Y+3 3 Y

Y=X/6
Data Types in C

• int : signed integer, typically 2 / 4 bytes


int numberOfStudents ;
• char: character, typically 1 byte
char lock; char key = ‘Q’ ;
• float: floating point number (4 bytes)
float averageTemp ;
• double: double precision floating point (8 bytes)
double electrondPerSecond ;
Variations of these types
• short int, longed int, unsigned int
short int age;
long int worldPopulation;
unsigned int numberOfDays;
• long double
long double particlesInUniverse;
Values of Data Types
• 2 byte int :
– -32768 to +32767 (-215 to 215-1)
• 4 byte int :
– -2147483648 to +2147483647
• 2 byte unsigned int :
– 0 to 65535 (216-1) E or e means “10 to
• char : 0 to 255 the power of”
– ‘a’, ‘A’, ‘+’, ‘=‘, ......
• float : -2.34, 0.0037, 23.0, 1.234e-5
C Type Conversion

• Convert the value of one data type to


another type.
For example, if you try to divide two integers, 5 by 2, you
would expect the result to be 2.5. But since we are working
with integers (and not floating-point values), the following
example will just output 2:
int x = 5;
int y = 2;
int sum = 5 / 2;
printf("%d", sum); // Outputs 2
There are two types of conversion in C:
•Implicit Conversion (automatically)
Implicit conversion is done automatically by
the compiler when you assign a value of one
type to another.
•For example, if you assign an int value to
a float type:
float myFloat = 9;
printf("%f", myFloat); // 9.000000
int myInt = 9.99;
printf("%d", myInt); // 9
Explicit Conversion
Explicit conversion is done manually by
placing the type in parentheses () in front of
the value.
float sum = (float) 5 / 2;
printf("%f", sum); // 2.500000

int num1 = 5;
int num2 = 2;
float sum = (float) num1 / num2;
printf("%f", sum); // 2.500000
Input and Output
• printf : performs output to the standard output
device (typically defined to be the monitor)
– It requires a format string to which we can provide
• The text to print out
• Specifications on how to print the values
printf ("The number is %d.\n", num) ;
The format specification %d causes the value listed
after the format string to be embedded in the
output as a decimal number in place of %d.
Input
• scanf : performs input from the standard input
device, which is the keyboard by default.
– It requires a format string and a list of
variables into which the value received
from the input device will be stored.
•scanf ("%d", &size) ;
•scanf ("%c", &nextchar) ;
•scanf ("%f", &length) ;
Operators and Expressions
Operators in Expressions
Operators

Arithmetic Relational Logical


Operators Operators Operators
Operators
• Operators are used to manipulate variables.
• They perform
– arithmetic
– logic functions
– comparisons between values
int x = 6 ;
int y = 9;
int z, w;
z=x+y; w=x*y;
Expressions and statements
• Expressions : combine constants and variables with
operators
– x*y
• Expressions can be grouped to form statements
– z=x*y;
Semicolons terminate statements
• One or more simple sentences can be grouped to
form a compound sentence or a block by enclosing
within { }
Assignment operator
int x = 4 ;
x=x+9;
1. The right hand side is evaluated.
2. The left hand side is set to the value of the right
hand side.
All expressions evaluate to a value of a particular
type.
x + 9 evaluates to the integer value of 13.
Assignment Statement
• Used to assign values to variables, using the assignment
operator (=).
• General syntax:
variable_name = expression;
• Examples:
– velocity = 20;
– b = 15; temp = 12.5; /* Multiple assign on same line */
– A = A + 10;
– v = u + f * t;
– s = u * t + 0.5 * f * t * t;
Contd.
• A value can be assigned to a variable at the time
the variable is declared.
– int speed = 30;
– char flag = ‘y’;
• Several variables can be assigned the same value
using multiple assignment operators.
– a = b = c = 5;
– flag1 = flag2 = ‘y’;
– speed = flow = 0.0;
Arithmetic operators
+ : addition • distance = rate * time ;
• netIncome = income - tax ;
- : subtraction
• speed = distance / time ;
* : multiplication • area = PI * radius * radius
/ : division • y = a * x * x + b*x + c;
% : modulus • quotient = dividend/divisor;
operator • remainder=dividend %divisor;
Examples: Arithmetic expressions

• a+b*c–d/e a + (b * c) – (d / e)
• a * -b + d % e – f a * (-b) + (d % e) – f
• a–b+c+d (((a – b) + c) + d)
• x*y*z ((x * y) * z)
• a+b+c*d*e (a + b) + ((c * d) * e)
Operator Precedence
• In decreasing order of priority
1. Parentheses :: ( )
2. Unary minus :: -5
3. Multiplication, Division, and Modulus
4. Addition and Subtraction
• For operators of the same priority, evaluation is
from left to right as they appear.
• Parenthesis may be used to change the
precedence of operator evaluation.
Integer Arithmetic
• When the operands in an arithmetic
expression are integers, the expression is
called integer expression, and the operation
is called integer arithmetic.
• Integer arithmetic always yields integer
values.
Real Arithmetic
• Arithmetic operations involving only real or
floating-point operands.
• Since floating-point values are rounded to the
number of significant digits permissible, the final
value is an approximation of the final result.
– 1.0 / 3.0 * 3.0 will have the value 0.99999 and not
1.0
• The modulus operator cannot be used with real
operands.
Mixed-mode Arithmetic
• When one of the operands is integer and the other
is real, the expression is called a mixed-mode
arithmetic expression.
• If either operand is of the real type, then only real
arithmetic is performed, and the result is a real
number.
– 25 / 10 2
– 25 / 10.0 2.5
• Some more issues will be considered later.
Relational Operators
• Used to compare two quantities.
• Relational operators are specifically used to compare two quantities or values
in a program. It checks the relationship between two operands. If the given
relation is true, it will return 1 and if the relation is false, then it will return 0.
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to
Examples
• 10 > 20 is false
• 25 < 35.5 is true
• 12 > (7 + 5) is false

• When arithmetic expressions are used on either


side of a relational operator, the arithmetic
expressions will be evaluated first and then the
results compared.
– a + b > c – d is the same as (a+b) > (c+d)
Logical Operators
• Logical operators act upon logical expressions. An expression containing a
logical operator in C language returns either 0 or 1 depending upon the
condition whether the expression results in true or false.
– && : and (true if both operands are true)
– || : or (true if either or both operands true
– ! : negates the value of the logical expression
• Example
– (n >= lo_bound) && (n <= upper_bound)
– ! (num > 100)
Example: Logical Operators
int main () {
int i, j;
for (i=0; i<2; i++) {
for (j=0; j<2; j++)
printf (“%d AND %d = %d,
%d OR %d=%d\n”,
i,j,i&&j, i,j, i||j) ;
}
}
$ ./a.out
0 AND 0 = 0 0 OR 0 = 0
0 AND 1 = 0 0 OR 1 = 1
1 AND 0 = 0 1 OR 0 = 1
1 AND 1 = 1 1 OR 1 = 1
$
Conditional Operators (Ternary operator)

❖ A ternary operator pair “? :” is available in C language.


❖ It can able to construct conditional expressions.
❖ The general form is

exp1 ? exp2 : exp3;

❖ Where exp1, exp2, and exp3 are expressions.


❖ First, exp1 is evaluated.
❖ If it is nonzero (true), then the expression exp2 is evaluated.
❖ Otherwise, exp1 will be false, exp3 is evaluated.
Conditional Operators (Ternary operator)

Example:
#include<stdio.h>
main()
{
int a,b,c;
printf(“\nGive two numbers:”);
scanf(“%d%d”,&a,&b); /*a=15, b=10*/
c = (a > b) ? a : b;
printf(“\nThe Biggest value: %d”,c);
}
Output:
The Biggest value: 15
C’s special operators
• ++ and -- : a trademark of C programming
• ++ : increments a variable ;
• -- : decrements a variable
• x++
– In an expression, value of this expression is the
value of x prior to increment
• ++x
– In an expression, value of this expression is the
value of x after the increment.
x = 4; x = 4;
y = x++; y = ++x ;

y=4, x=5 after y=5, x=5 after evaluation


evaluation
x += 5 equivalent to x=x+5
h %= f equivalent to h = h%f
product *= num equivalent to product = product *
num
void main ()
{
int x = 10;
printf (“ x = %d\n”, ++x) ;
printf (“x = %d\n”, x++) ;
}
Question : What will get printed ?
Control Constructs
If statement

if statement Syntax

if (condition)
• It work if the given condition {
returns true . //These statements will
• If the condition returns false only execute if the
then the statements skipped. condition is true
}

63
Execution Flow of if Statement

if statement-Flow Diagram

64
if Statement Program

multiple if statements
#include <stdio.h>
int main()
{
int x, y; Output:
printf("enter the value of x:"); enter the value of x
scanf("%d", &x); 7
printf("enter the value of y:"); enter the value of y
scanf("%d", &y); 3
if (x>y) x is greater than y
{printf("x is greater than y\n");}
if (x<y)
{printf("x is less than y\n");}
if (x==y)
{printf("x is equal to y\n"); }
printf("End of Program");
return 0;}
65
If else statement

If else statement Syntax


if(condition)
If condition is true then the
{
statements are executed. //Statements inside
body of if}
If condition false then the else
“else” statements are executed. {
//Statements inside
body of else
}

66
If else statement

#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
printf("You are eligible for voting"); }
else
{
printf("You are not eligible for voting"); }
return 0; 67
}
If statement

Syntax
if(condition)
Nested If else statement { //Nested if else inside the body of
"if"
if(condition2)
• if else statement is { //Statements inside the body of
nested "if“
present inside the body of }
another “if” or “else” else
{ //Statements inside the body of
nested "else"
}
}
else
{ //Statements inside the body of
"else“
}
68
/* FIND THE LARGEST OF THREE NUMBERS */
main()
{
int a, b, c;
scanf (“%d %d %d”, &a, &b, &c);
if ((a>b) && (a>c)) /* Composite condition
check*/
printf (“\n Largest is %d”, a);
else
if (b>c) /* return result */

printf (“\n Largest is %d”, b);


else
printf (“\n Largest is %d”, c);
}
Switch
● The syntax of switch statement is
switch (expression) {
case const-expression1 : statement1
case const-expression2 : statement2
:
default : statementn
}
● All case expressions must be different. Expression must evaluate to an
integer.
● First the expression is evaluated. Then the value of expression is
compared with the case expressions. The execution begins at the case
statement, whose case expression matches. All the statements below are
executed.
● If default is present and if no other case matches then default statement
is executed.

70
Switch Case Statements
Flow Diagram

71
Switch Case
Example
#include <stdio.h>
int main()
{
int num = 8; Output:
switch (num) {
case 7:
Value is 8
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break;
}
return 0; } 72
Iterations(Looping Statements)
Loop – A segment of the program that is executed repeatedly until
a condition is satisfied
● The three types of loops are given below.
while (expression) statement
for (expression1opt; expression2opt; expression3opt)
statement
do statement while(expression);
● In while loop the expression (which must be arithmetic) is evaluated and
if the value is nonzero, then the statement is executed. The process is
continued till the expression becomes zero. The expression is evaluated
before the iteration.
● For statement is equivalent to
expression1;
while ( expression2 ) {
statement
expression3;
}
73
for loop
❑ Most commonly and popularly used loop structure
❑ Structure of the for loop
❑ Initialize loop counter variable
❑ Check for condition
❑ Increment / Decrement the loop counter variable
❑ Syntax
for(initialization; condition; increment / decrement)
Flowchart - for
/* Program to Add n Numbers using for loop
*/
#include<stdio.h> int main( ) Output
{ Enter the value for n: 3
int i, n, sum=0; The sum of n Numbers is:
printf(“\n Enter the value for n: ”); 6
scanf(“%d”, &n);
for (i =1; i<=n; i++)
{
sum = sum + i;
}
printf(“The sum of n Numbers is: %d”, sum);
return 0;
}
Various forms of for loop
1.int num=10;
for (;num<20;num++)
2. for (num=10; num<20; )
{
//Statements
num++;
}
3. for (i=1,j=1;i<10 && j<10; i++, j++)
4. for(;;) Infinite for loop
5.for(i=0;i<10;i++); for loop with no body
Nested for

❑One loop inside another loop


❑ Syntax
for(initialization; condition; increment / decrement)
{
for ( init; condition; increment / decrement )
{
statement(s);
}
statement(s);
}
Flow chart - Nested for
#include<stdio.h>
int main() output
{ i=0 j=0
int i, j; i=0 j=1
for (i =0; i<2; i++) i=1 j=0
{ for (j =0; j<2; j++) i=1 j=1
{ printf("i=%d j=%d\n",i,j);
}
}
return 0;
}
While Loop Statement

Definitions: Syntax:
Initialize loop counter
•Simplest Loop Structure variable;
while (condition)
• Is called as Entry Controlled Loop
{
• Execution of the loop happened based //Statements;
on test conditions.
// increment / Decrement
loop counter variable;
}

* Looping Statements
81
* Looping Statements
82
While Statement Program

/* Program to Add n Numbers*/


#include<stdio.h>
int main( ){
int i=1,n, sum=0;
printf(“\n Enter the value for n: ”);
scanf(“%d”, &n);
while (i<=n)
{
sum = sum + i; i++; }
printf(“The sum of n Numbers is: %d”,
sum);
return 0; }
Output
Enter the value for n: 3
The sum of n *Numbers is: 6 Looping Statements
83
Iterations
● In the do loop, the statement is executed and then the expression is
evaluated. If the expression is nonzero the process is repeated. Thus
the condition is evaluated at the end of each iteration.
● Example

x1 = 1;
do {
x0 = x1;
x1 = x0 – f(x0) / derf(x0);
} while ( fabs(x1 – x0) > FLT_EPSILON ) ;

● We needed to evaluate x1 before we could apply the convergence


criterion.

84
Do While Loop

* The body of the loop is executed at least once.


* Called as Exit Controlled Loop

Syntax
do
{
statements;
}
while (condition);

* Looping Statements 85
* Looping Statements
86
#include <stdio.h>
int main()
{
int j=0;
do
{
printf("Value of variable j is: %d\n", j);
j++;
}while (j<=3);
printf("Out of loop");
return 0;
}

* Looping Statements
87
Difference Between While and Do-While

While Do Loop Do While Loop

Entry Controlled Loop Exit Controlled Loop

Test condition is checked Test condition is checked after


before body of the loop is the body of the loop is executed
executed
Loop will not be executed Loop will be executed at least
if condition is false once even if condition is false
Top tested loop Bottom tested loop
Break and Continue
● The loops have one expression that decides whether the iterative
process should be terminated. It is sometimes convenient to be able to
exit from the loop.
● break statement provides an early exit from the for, while and do
loops.
● It also provides an exit from switch statement.
● continue statement causes the jump to the end of the loop body,
skipping the statements only once. The loop may continue.

while (...) { do { for (...) {


... ... ...
continue; continue; continue;
... ... ...
cont: ; cont: ; cont: ;
} } }

89
BREAK STATEMENTS

● Terminates the execution of current loop


and continues with statement following
the loop.
● Used with while, do while, for and switch
statements.
● Syntax
break;
CONTINUE STATEMENTS

● Skips the statement below the keyword


‘continue’ and continue with the next
iteration.

● Syntax
continue;
Break and continue
● Example
for ( i = 0; i < n; i++ ) {
if ( a[i] < 0 ) continue;
/* Process only non-negative elements of the array */
...
}

● Example
for ( i = 2; i <= (int)sqrt(n); i++ ) {
if ( n % i == 0 ) break;

if ( n % i ) printf(“Prime\n”);
else printf(“Not prime\n”);

92
GOTO STATEMENTS
● Used to transfer the program control from
one place to another.
● Label name included for transferring
control.

● Syntax :
goto label;
.............
.............
.............
label:
statement;
GOTO STATEMENTS EXAMPLE
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b;

printf(“enter the number “);


scanf“%d %d“,&a,&b);
if (a==b)
goto equal;
else
{
printf(“ a and b are not equal “);
exit (0);
}
equal:
printf(“ a and b are equal “);
return 0;
}
Structure of a C program
• Every C program consists of one or more
functions.
– One of the functions must be called main.
– The program will always begin by executing the
main function.
Function
• Each function must contain:
– A function heading, which consists of the function
name, followed by an optional list of arguments
enclosed in parentheses.
– A list of argument declarations.
– A compound statement, which comprises the
remainder of the function.
Compound Statement
• Each compound statement is enclosed within
a pair of braces (‘{‘ and ‘}’).
– The braces may contain combinations of
elementary statements and other compound
statements.
• Comments may appear anywhere in a
program, enclosed within delimiters
• ‘/*’ and ‘*/’.
Compound Statement (or block)
{
definitions-and-declarations (optional)
statement-list
}
Used for grouping, as function body, and to
restrict identifier visibility
• Need for function:
– Divide complex tasks into sub tasks-Divide and
conquer
– Code reusability
• Types of Functions
There are two types of functions in C:
• Library Functions
• User Defined Function
Library Function

A library function is also referred to as a “built-in


function”. A compiler package already exists that
contains these functions, each of which has a specific
meaning and is included in the package. Built-in
functions have the advantage of being directly usable
without being defined, whereas user-defined functions
must be declared and defined before being used.
•For Example:
pow(), sqrt(), strcmp(), strcpy() etc.
Math
• #include <math.h>
• Use any math function
• If c1 = 13.0, d = 3.0 and f = 4.0, then the
statement
printf( "%.2f", sqrt( c1 + d * f ) );
©1992-2013 by Pearson Education, Inc. All
Rights Reserved.
©1992-2013 by Pearson Education, Inc. All
Rights Reserved.
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
1.Function Declaration
A function declaration tells the compiler that there is a function with the
given name defined somewhere else in the program.
Syntax:
return_type name_of_the_function (parameter_1, parameter_2);
2. Function Definition
The function definition consists of actual statements which are executed
when the function is called
Syntax:
return_type function_name (para1_type para1_name, para2_type
para2_name) { // body of the function }
3. Function Calls
A function call is a statement that instructs the compiler to execute the
function. We use the function name and parameters in the function call.
User Defined Function

• Functions that the programmer creates are known as


User-Defined functions . User-defined functions can be
improved and modified according to the need of the
programmer. Whenever we write a function that is
case-specific and is not defined in any header file, we need to
declare and define our own functions according to the syntax.
Create your function
• Choose a name
– Function should perform a single well defined task
– If you can’t find a concise descriptive name, you may have too
many jobs for the function
• Define a contract
– Inputs
• Arguments – choose type
• None should be noted as void
• Will the function change the parameter’s value?
– Output
• Only one ; by convention, 0 means good
• Write prototype
– Looks like function header but has ;
– int square( int y );
– Tells compiler what is valid input and output
– Forces type conversion
• Write body
• Call the function
Sample Function
#include <stdio.h>
int square ( int y ); // function declaration
// function main begins program execution
int main ( void )
{ int x; // counter
for ( x = 1; x <= 10; x++ ) {// loop 10 times and calc square of x each time
printf ( "%d ", square ( x ) ); // function call
}
puts (""); // add a blank line
}
// square function returns the square of its parm
int square ( int y ) // y is a copy of the x sent //function definition
{
return y * y; // returns square of y as an int
}
D From Deitel C How to Program
return
• A function in C can return only one value.
• In C, if we do not specify a return type, compiler
assumes an implicit return type as int.
• return serves two purposes:
– It tells the computer the value to return as the
result
– It tells the computer to leave the function
immediately and return the calling function (or the
main program).
• Void return:
– Ex: void printit ( int x );
– You can still return to leave, but without a value
Parameter Passing Mechanisms
There are different ways in which parameter data can be passed into and out
of functions. Let us assume that a function B() is called from another
function A(). In this case, A is called the “caller function” and B is called
the “called function or callee function”. Also, the arguments which A sends
to B are called actual arguments and the parameters of B are called formal
arguments.
Call by value
Changes made to formal
parameters do not get
transmitted back to the caller.
Any modifications to the
formal parameter variable
inside the called function or
method affect only the separate
storage location and will not be
reflected in the actual
parameter in the calling
environment. This method is
also called call by value.

110
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b
in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do
not change by changing the formal parameters in call by value, a = 10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b =
10
}

Before swapping the values in main a = 10, b = 20


After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
111
Parameter passing & return
void main()
Output
{
int x=10, y=5;
printf (“M1: x = %d, y = %d\n”, x, y);
interchange (x, y);
printf (“M2: x = %d, y = %d\n”, x, y);
}

void interchange (int x, int y)


{ int temp;
printf (“F1: x = %d, y = %d\n”, x, y);
temp= x; x = y; y = temp;
printf (“F2: x = %d, y = %d\n”, x, y);
}

112
Parameter passing & return
void main()
Output
{
int x=10, y=5; M1: x = 10, y = 5
printf (“M1: x = %d, y = %d\n”, x, y);
F1: x = 10, y = 5
interchange (x, y);
printf (“M2: x = %d, y = %d\n”, x, y); F2: x = 5, y = 10
}
M2: x = 10, y =
void interchange (int x, int y) 5
{ int temp;
printf (“F1: x = %d, y = %d\n”, x, y);
temp= x; x = y; y = temp;
printf (“F2: x = %d, y = %d\n”, x, y);
}

113
Parameter passing & return
int x=11,y=6;
void interchange (int a, int b); Homework
int main()
{
{ int x=6,y=11;
interchange (x,y);
}
printf("x=%d y=%d",x,y);
}
void interchange (int x, int y)
{ int temp;
temp=x;
x=y;
y=temp;
}
114
Call by reference
Changes made to formal
parameter do get transmitted
back to the caller through
parameter passing. Any
changes to the formal
parameter are reflected in the
actual parameter in the calling
environment as formal
parameter receives a reference
(or pointer) to the actual data.
This method is also called
as call by reference.

115
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b
in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters d
o change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20,
b = 10
}

Before swapping the values in main a = 10, b = 20


After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
116
When to Use Value and Reference
Parameters
• We use value parameters when:
– We are not going to change the parameters’ value
– We may change it but the main program should
not know about it
• When we are simply printing the value
– We use reference parameters when:
– We are going to change the parameter’s value and
the main program MUST know about it.
– We are reading in a new value
No. Call by value Call by reference

1 A copy of the value is passed into the An address of value is


function passed into the function

2 Changes made inside the function is limited Changes made inside the
to the function only. The values of the function validate outside of
actual parameters do not change by the function also. The
changing the formal parameters. values of the actual
parameters do change by
changing the formal
parameters.

3 Actual and formal arguments are created at Actual and formal


the different memory location arguments are created at the
same memory location
Nested Functions
Nested function is not supported by C because we cannot define a function within
another function in C. We can declare a function inside a function, but it’s not a nested
function.
Because nested functions definitions can not access local variables of the surrounding
blocks, they can access only global variables of the containing module.
#include <stdio.h>
int main(void)
{
printf("Main");
int fun()
{
printf("fun"); // defining view() function inside fun() function.
int view()
{
printf("view");
}
return 1;
}
view(); }
Output:
Compile time error: undefined reference to `view'
An extension of the GNU C Compiler allows the declarations of nested
functions. The declarations of nested functions under GCC’s extension need
to be prefix/start with the auto keyword.
#include <stdio.h>
int main(void)
{
auto int view(); // declare function with auto keyword
view(); // calling function
printf("Main\n");

int view()
{
printf("View\n");
return 1;
}
printf("GEEKS");
return 0;
}
Output:
view
Main
GEEKS
Recursion

121
Recursion
■ A process by which a function calls itself
repeatedly
◻ Either directly.
■ X calls X
◻ Or cyclically in a chain.
■ X calls Y, and Y calls X

■ Used for repetitive computations in which each


action is stated in terms of a previous result
fact(n) = n * fact (n-1)

122
Contd.
■ For a problem to be written in recursive form,
two conditions are to be satisfied:
◻ It should be possible to express the problem
in recursive form
■ Solution of the problem in terms of solution of the
same problem on smaller sized data
◻ The problem statement must include a
stopping condition
Stopping condition
fact(n) = 1, if n = 0
= n * fact(n-1), if n > 0
Recursive definition

123
■ Examples:

◻ Factorial:
fact(0) = 1
fact(n) = n * fact(n-1), if n > 0

◻ Fibonacci series (1,1,2,3,5,8,13,21,….)


fib (0) = 1
fib (1) = 1
fib (n) = fib (n-1) + fib (n-2), if n > 1

124
Factorial
long int fact (int n)
{
if (n == 1)
return (1);
else
return (n * fact(n-1));
}

125
Factorial Execution

long int fact (int n)


{
if (n = = 1) return (1);
else return (n * fact(n-1));
}

126
Factorial Execution
fact(4)

long int fact (int n)


{
if (n = = 1) return (1);
else return (n * fact(n-1));
}

127
Factorial Execution
fact(4)

if (4 = = 1) return (1);
else return (4 * fact(3));

long int fact (int n)


{
if (n = = 1) return (1);
else return (n * fact(n-1));
}

128
Factorial Execution
fact(4)

if (4 = = 1) return (1);
else return (4 * fact(3));

if (3 = = 1) return (1);
else return (3 * fact(2));

long int fact (int n)


{
if (n = = 1) return (1);
else return (n * fact(n-1));
}

129
Factorial Execution
fact(4)

if (4 = = 1) return (1);
else return (4 * fact(3));

if (3 = = 1) return (1);
else return (3 * fact(2));

if (2 = = 1) return (1);
else return (2 * fact(1));
long int fact (int n)
{
if (n = = 1) return (1);
else return (n * fact(n-1));
}

130
Factorial Execution
fact(4)

if (4 = = 1) return (1);
else return (4 * fact(3));

if (3 = = 1) return (1);
else return (3 * fact(2));

if (2 = = 1) return (1);
else return (2 * fact(1));
long int fact (int n)
{ if (1 = = 1) return (1);
if (n = = 1) return (1);
else return (n * fact(n-1));
}

131
Factorial Execution
fact(4)

if (4 = = 1) return (1);
else return (4 * fact(3));

if (3 = = 1) return (1);
else return (3 * fact(2));

if (2 = = 1) return (1);
else return (2 * fact(1)); 1
long int fact (int n)
{ if (1 = = 1) return (1);
if (n = = 1) return (1);
else return (n * fact(n-1));
}

132
Factorial Execution
fact(4)

if (4 = = 1) return (1);
else return (4 * fact(3));

if (3 = = 1) return (1);
else return (3 * fact(2)); 2

if (2 = = 1) return (1);
else return (2 * fact(1)); 1
long int fact (int n)
{ if (1 = = 1) return (1);
if (n = = 1) return (1);
else return (n * fact(n-1));
}

133
Factorial Execution
fact(4)

if (4 = = 1) return (1);
else return (4 * fact(3));

if (3 = = 1) return (1);
else return (3 * fact(2)); 2

if (2 = = 1) return (1);
else return (2 * fact(1)); 1
long int fact (int n)
{ if (1 = = 1) return (1);
if (n = = 1) return (1);
else return (n * fact(n-1));
}

134
Factorial Execution
fact(4)

if (4 = = 1) return (1);
else return (4 * fact(3)); 6

if (3 = = 1) return (1);
else return (3 * fact(2)); 2

if (2 = = 1) return (1);
else return (2 * fact(1)); 1
long int fact (int n)
{ if (1 = = 1) return (1);
if (n = = 1) return (1);
else return (n * fact(n-1));
}

135
Factorial Execution
fact(4) 24

if (4 = = 1) return (1);
else return (4 * fact(3)); 6

if (3 = = 1) return (1);
else return (3 * fact(2)); 2

if (2 = = 1) return (1);
else return (2 * fact(1)); 1
long int fact (int n)
{ if (1 = = 1) return (1);
if (n = = 1) return (1);
else return (n * fact(n-1));
}

136
How are function calls
implemented?
■ The following applies in general, the implementation
details of function call
◻ The system maintains a stack in memory
■ Stack is a last-in first-out structure
■ Two operations on stack, push and pop
◻ Whenever there is a function call, the activation
record gets pushed into the stack
■ Activation record consists of the return address
in the calling program, the return value from the
function, and the local variables inside the
function
137
◻ Pop activation record, whenever the function
returns

◻ Activation record looks like:

Local
Variables
Return
Value
Return Addr

138
void main()
{ int gcd (int x, int y)
…….. {
x = gcd (a, b); ……..
…….. ……..
} return (result);
}

Local
Activation Variables
record Return
STACK

Value
Return Addr

Before call After call After return


139
void main()
{
…….. int ncr (int n, int r)
x = ncr (a, b); {
…….. x=fact(n); y=fact(r); int fact (int n)
} z=fact(n-r); 3 times {
p=x/(y*z) ………
return (p); return (result);
} }

3 times
LV2, RV2,
RA2

LV1, RV1, LV1, RV1, LV1, RV1,


RA1 RA1 RA1

Before call Call ncr Call fact fact returns ncr returns
140
Push activation record

a, b (Local
x
Variables)
Return
Value
mai
Return Addr n
141
Push activation record

Paramete n, r, p (Local
Variables)
r passing Return
Value
nCr
Return Addr
a, b (Local
x
Variables)
Return
Value
mai
Return Addr n
142
void main()
{
…….. int ncr (int n, int r)
x = ncr (a, b); {
…….. x=fact(n); y=fact(r); int fact (int n)
} z=fact(n-r); 3 times {
p=x/(y*z) ………
return (p); return (result);
} }

3 times
LV2, RV2,
RA2

LV1, RV1, LV1, RV1, LV1, RV1,


RA1 RA1 RA1

Before call Call ncr Call fact fact returns ncr returns
143
Push activation record
n, result
(Local
Variables)
Return result
fact
Value
Return Addr Return
Paramete n, r (Local x
Variables)
r passing Return
Value
nCr
Return Addr
a, b (Local
x
Variables)
Return
Value
mai
Return Addr n
144
Pop activation record

Local
Variables
Return
Value nCr
Return Addr
Local
Variables
Return
Value mai
Return Addr
n

145
void main()
{
…….. int ncr (int n, int r)
x = ncr (a, b); {
…….. x=fact(n); y=fact(r); int fact (int n)
} z=fact(n-r); 3 times {
p=x/(y*z) ………
return (p); return (result);
} }

3 times
LV2, RV2,
RA2

LV1, RV1, LV1, RV1, LV1, RV1,


RA1 RA1 RA1

Before call Call ncr Call fact fact returns ncr returns
146
Push activation record
Local
Variables
Return result fact
Value
Return Addr
Local y
Variables
Return
Value nCr
Return Addr
Local
Variables
Return
Value mai
Return Addr
n

147
Pop activation record

Local
Variables nCr
Return
Value p
Return Addr Return
Local x
Variables
Return
Value mai
Return Addr
n

148
Pop activation record

a, b (Local
x
Variables)
Return
Value
mai
Return Addr n
149
What happens for recursive
calls?
■ What we have seen ….
◻ Activation record gets pushed into the stack
when a function call is made
◻ Activation record is popped off the stack
when the function returns
■ In recursion, a function calls itself
◻ Several function calls going on, with none of
the function calls returning back
■ Activation records are pushed onto the stack
continuously
■ Large stack space required 150
◻ Activation records keep popping off, when the
termination condition of recursion is reached

■ We shall illustrate the process by an example of


computing factorial
◻ Activation record looks like:

Local
Variables
Return
Value
Return Addr

151
Example:: main() calls fact(3)
void main()
{ int fact (n)
int n; int n;
n = 3; {
printf (“%d \n”, fact(n) if (n = = 0)
); return (1);
} else
return (n *
fact(n-1));
152
TRACE OF THE STACK DURING EXECUTION

n=0
1
RA ..
fact fact
n=1 n=1 n=1 returns
main - - 1*1 = 1
calls RA .. RA .. RA ..
to main
fact fact fact fact
n=2 n=2 n=2 n=2 n=2
- - - - 2*1 = 2
RA .. RA .. RA .. RA .. RA ..
fact fact fact fact fact
n=3 n=3 n=3 n=3 n=3 n=3 n=3
- - - - - - 3*2 = 6
RA .. RA .. RA .. RA .. RA .. RA .. RA ..
main main main main main main main

153
Look at the variable addresses (a slightly
different program) !
void main()
Output
{
int x,y; 4
scanf("%d",&x); F: data = 4, &data = 3221224528
y = fact(x); &val = 3221224516
printf ("M: x= %d, y = %d\n", x,y); F: data = 3, &data = 3221224480
} &val = 3221224468
F: data = 2, &data = 3221224432
int fact(int data)
&val = 3221224420
{ int val = 1;
printf("F: data = %d, &data = %u \n F: data = 1, &data = 3221224384
&val = %u\n", data, &data, &val); &val = 3221224372
if (data>1) val = data*fact(data-1); M: x= 4, y = 24
return val;
} 154
Fibonacci Numbers

Fibonacci recurrence:
fib(n) = 1 if n = 0 or 1;
= fib(n – 2) + fib(n – 1)
otherwise;

int fib (int n) {


if (n == 0 or n == 1)
return 1; [BASE]
return fib(n-2) + fib(n-1) ;
[Recursive]
} 155
int fib (int n) { Fibonacci recurrence:
if (n == 0 || n == 1)
return 1;
fib(n) = 1 if n = 0 or 1;
return fib(n-2) + fib(n-1) ; = fib(n – 2) + fib(n –
}
1)
otherwise;
fib (5)

fib (3) fib (4)

fib (1) fib (2) fib (2) fib (3)

fib (0) fib (1) fib (0) fib (1) fib (1) fib (2)

fib (0) fib (1)

156
int fib (int n) { Fibonacci recurrence:
if (n == 0 || n == 1)
return 1;
fib(n) = 1 if n = 0 or 1;
return fib(n-2) + fib(n-1) ; = fib(n – 2) + fib(n –
}
1)
otherwise;
fib (5)

fib (3) fib (4)

fib (1) fib (2) fib (2) fib (3)


1

fib (0) fib (1) fib (0) fib (1) fib (1) fib (2)
1 1 1 1 1
fib (0) fib (1)
1 1
fib.c 157
int fib (int n) { Fibonacci recurrence:
if (n==0 || n==1)
return 1;
fib(n) = 1 if n = 0 or 1;
return fib(n-2) + fib(n-1) ; = fib(n – 2) + fib(n –
}
1)
8
otherwise;
fib (5)
3 5
fib (3) fib (4)
1 2 2 3
fib (1) fib (2) fib (2) fib (3)
1 2
1 1 1 1 1
fib (0) fib (1) fib (0) fib (1) fib (1) fib (2)
1 1 1 1 1 1
1
fib (0) fib (1)
1 1
158
ARRAY Overview
• Array Basic and Types
• Array Declaration
• Array Initialization
• Accessing and Indexing one dimensional Array
• Array Operations
• Example Programs
Definition
• Stores a fixed-size sequential collection of elements of the same type
• Contiguous memory locations
• Specific element in an array is accessed by an index.
• The lowest address ----first element=n[0]
• highest address ----last element (size-1)=6-1=n[5]
Types

• Single Dimensional Array / One Dimensional Array


• Multi Dimensional Array
Single Dimensional Array / One Dimensional
Array

• Also called as one-dimensional arrays, Linear Arrays or simply 1-D


Arrays.
• Used to store list of values of same data type.
• Arrays are used to store a row of values.
• Data is stored in linear form.
Declaration of Single Dimensional Array
• Syntax
datatype arrayName [ size ] ;
• Example
int studNo [20] ; studNo[0] …….studno[19]
Reserves 20 continuous memory locations of 2 bytes each with the
name studNo and tells the compiler to allow only integer values into
those memory locations.
Initialization of Single Dimensional
Array
• Syntax
datatype arrayName [ size ] = {value1, value2, ...} ;
• Example
int studMarks [5] = { 98, 96, 88, 75, 83 } ;
Reserves 5 contiguous memory locations of 2 bytes each with the
name studMarks and initializes with value 98 in first memory location, 96 in
second memory location, 88 in third memory location, 75 in fourth memory
location, 83 in fifth memory location.
studMarks[0] = 98
studMarks[1]= 96
studMarks[2]= 88
studMarks[3]= 75
studMarks[4]= 83
Initialization of Single Dimensional
Array
• To initialize a single dimensional array without specifying size and with
initial values...
• Syntax
datatype arrayName [ ] = {value1, value2, ...} ;
• Example
int studMarks [] = {98, 96, 88, 75, 83 } ;
char studentName [] = “firstvirtualclass" ;
Size of the array ‘studMarks' is 5 and the size of the
array 'studentName' is 18. This is because in case of character array,
compiler stores one extra character called \0 (NULL) at the end.
Accessing Elements of Single
Dimensional Array
• To access the elements use array name followed by index value of the
element that to be accessed.
• Index value must be enclosed in square braces.
• Index value of an element in an array is the reference number given to
each element at the time of memory allocation.
• The index value of single dimensional array starts with zero (0) for first
element and incremented by one for each element.

arrayName [ indexValue ]
studMarks [2]
Example: Write a program to calculate the average marks of a particular
student:
#include<stdio.h>
#include<conio.h>
int main(){
int i, marks[5], n, sum = 0;
float avg;
printf("Enter the no.of subjects:\n");
scanf("%d",&n);
printf("Enter the marks obtained in your %d subjects\n", n);
for(i=0;i<n;i++)
{
scanf("%d", &marks[i]);
}
for(i=0;i<5;i++)
{
sum = sum + marks[i];
}
• i=0
• Sum=0+20
• Sum =20
• i=1
• -------
• i=1
• Sum=20+30
• Sum= 50
• i=2
• ----
• i=2
• Sum=50+40
• Sum=90
• i=3
• i=3
• Sum=90+50
• Sum = 140
• i=4

• i=4
• Sum=140+60
• Sum=200
• i=5
Reversing elements of an array:

• Reversing an array means that the sequence of elements of array will be


reversed.
• For instance if your array ‘A’ has two elements : A[0] = 1; A[1] = 2; then
after reversal A[0] = 2 and A[1] = 1.
Algorithm
• Take input from user into array A.
• Store value of element of A in B, starting with last element of A and
placing it as first element in B.
• Loop for each value of A.
• Store each value of element B into A as it is. (Copying the reversed array
back to source array).
• Loop for each value of B.
Example-Reversing
#include <stdio.h>
int main()
{
int n, i, j, a[20], b[20];
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter array elements\n");
for (i = 0; i < n ; i++)
scanf("%d", &a[i]);
//Copying elements into array b starting from end of array a
for (i = n - 1, j = 0; i >= 0,j<n; i--, j++)
b[j] = a[i];
//Copying reversed
for (i = 0; i < n; i++)
a[i] = b[i];
printf("Reversed array is\n");
for (i = 0; i < n; i++)
printf("%d\n", a[i]);
• n=5,
• i=n-1= 4, j=0
• i=4,j=o
• i=4
• i=4-1=3
• i=3,j=1
• B[1]=a[3=
• B[1]=14
• i=2,j=2
• B[2]=a[2]
• B[2]=13
i=1 , j=3
B[3]=a[1]
B[3]=12

i=0,j=4
B[4]=a[0]
B[4]=11
Sorting elements of an array:
• Sorting elements if array means to order the elements in ascending or
descending order – usually in ascending order.
• The basic approach to sorting is Bubble sort method where in nested
loop is used to sort elements of array.
Algorithm
• Create an array of fixed size.
• Take n, a variable which stores the number of elements of the array,
less than maximum capacity of array.
• Iterate via for loop to take array elements as input, and print them.
• The array elements are in unsorted fashion, to sort them, make a nested
loop.
• In the nested loop, the each element will be compared to all the
elements below it.
• In case the element is greater than the element present below it, then
they are interchanged.
• After executing the nested loop, we will obtain an array in ascending
order arranged elements.
Example-Sorting
#include <stdio.h>
int main()
{
int i, j, temp, n, arr[30];
printf("Enter the number of elements in your array: \n");
scanf("%d", &n);
printf("Enter the array elements: \n");
for (i = 0; i < n; ++i)
scanf("%d", &arr[i]);
for (i = 0; i< n-1; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (arr[i] > arr[j]) //to check if current element greater than i+1th element, if yes; perform swap.
{ temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}}}
printf("\nThe array sorted in ascending order is as given below: \n");
• Temp=arr[i] 22
• Arr[i]=arr[j] 10
• Arr[j]=temp 22
Two dimensional array
• A 2D array is also known as a matrix (a table of
rows and columns).
• To create a 2D array of integers, take a look at the
following example:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
Access the Elements of a 2D Array
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

printf(“%d", matrix[0][2]); // Outputs 2


Change Elements in a 2D Array
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;

printf("%d", matrix[0][0]); // Now outputs 9 instead


of 1
Loop Through a 2D Array
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("%d\n", matrix[i][j]);
}
}
• Matrix multiplication in C: We can add, subtract,
multiply and divide 2 matrices. To do so, we are
taking input from the user for row number, column
number, first matrix elements and second matrix
elements. Then we are performing multiplication
on the matrices entered by the user.
• In matrix multiplication first matrix one row
element is multiplied by second matrix all column
elements.
• Let's try to understand the matrix multiplication
of 2*2 and 3*3 matrices by the figure given below:
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("multiply of the matrix=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0; }
Desirable programming style
• Clarity
• The program should be clearly written.
• It should be easy to follow the program logic.
• Meaningful variable names
• Make variable/constant names meaningful to enhance
program clarity.
• ‘area’ instead of ‘a’
• ‘radius’ instead of ‘r’
Program Documentation
• Insert comments in the program to make it easy to
understand.
• Put a comment for each function.
• Put comments for the important variables.
• Do not give too many comments.
Program indentation
• Use proper indentation.
• C has standard indentation conventions.
• Followed by any book on C
• Followed in the class
190

You might also like