Unit 1 Pds
Unit 1 Pds
• 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
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 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
• 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
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 ;
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
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 */
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
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
x1 = 1;
do {
x0 = x1;
x1 = x0 – f(x0) / derf(x0);
} while ( fabs(x1 – x0) > FLT_EPSILON ) ;
84
Do While 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
89
BREAK STATEMENTS
● 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;
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
}
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
}
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.
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
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
124
Factorial
long int fact (int n)
{
if (n == 1)
return (1);
else
return (n * fact(n-1));
}
125
Factorial Execution
126
Factorial Execution
fact(4)
127
Factorial Execution
fact(4)
if (4 = = 1) return (1);
else return (4 * fact(3));
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));
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
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
3 times
LV2, RV2,
RA2
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
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
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
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;
fib (0) fib (1) fib (0) fib (1) fib (1) fib (2)
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 (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
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:
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} };
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