You are on page 1of 38

LECTURE 4-9 INTRODUCTION

THIS SERIES WILL COVER SOFTWARE CONCEPTS AND BASIC C


PROGRAMMING LANGUAGE.

FOLLOWING SLIDES ARE ONLY AN INDICATION OF THE TOPICS TO BE


COVERED IN THESE LECTURES.

A NUMBER OF PROGRAMMING EXERCISES WILL BE DONE ONLINE TO


ILLUSTRATE DIFFERENT FEATURES OF C LANGUAGE.

STEP BY STEP METHOD TO DEVELOP PROGRAMS WILL BE INTRODUCED


TO MAKE PROGRAMMING EASIER.
SOFTWARE
WHAT IS SOFTWARE
-A COMPUTER EXECUTABLE PROGRAM TO DO SOME JOB

CLASSIFICATION
-SYSTEM SOFTWARE
-APPLICATION SOFTWARE

SYSTEM SOFTWARE:
OPERATING SYSTEMS, COMPILERS, LOADERS, LINKERS, ASSEMBLERS,
DEVICE DRIVERS ETC.

APPLICATION SOFTWARE:
WHEN THE PROBLEM TO BE SOLVED IS TOO COMPLEX
WHEN DATA TO BE PROCESSED IS LARGE/ HUGE
Programming Concepts of C Language
Case sensitive language
Performs very little (almost none) limits or type checking
Highly syntax dependent (use of ;)
Provides ample opportunities to experiment and develop new styles

Preprocessor directives:
#include <stdio.h>
#include<conio.h>
#define directive
Macros:
Inline Macros
#define N 10
#define SQR(x) x*x
Multiline macros
Programming Concepts of C Language
main() : int main()/ void main() / main()
Scalar Data types:
5 basic: char,int,float,double,enum
4 modifiers: short,long,signed,unsigned
Aggregate Data types:
Arrays, structures and Unions

Pointers int *a,


Address of a variable: use of &
arrays:
int a[10];
Memory allotment:
Access function formula:
For one dimension array:
&a[i]=a+i*sizeof(type)
Programming Concepts of C Language
For two dimension array:
int a[10][20]; where m=10, n=20.
&a[i][j]= a+ (…………….. )*sizeof(type)
Methods of storing 2-dimension arrays:
Row major format
Column major format
C uses row major format
FORTRAN uses column major format

So in C language &a[i][j]=a+(i*n+j)*sizeof(type)
-----------------------------------------------------------------------
struct
scanf() and printf():
scanf(“%d%c%d”,&x,&y,&z);
char a[10];
scanf(“%s”,a);
Discussions Lecture 4-5:
Arrays: Collection of similar items
Struct: Collection of different but related items.
struct stu_rec{
int rollno;
char name[40];
int marks;
};
typedef struct stu_rec student;
Now we can use student in place of struct stu_rec while declaring variables.
Example: student x;

And items of struct can be accessed as


x.rollno
x.name
x.marks
Discussions Lecture 4-5:
SAMPLE PROGRAM TO CHECK (ON LINUX UBUNTU 64 BIT):
#include<stdio.h>
int main()
{
int a[10],b;
b=15;
printf("value of a:%d, value of &a[0]:%d\n",a,&a[0]);
printf("value of b:%d, value of a[-1]:%d\n",b,a[-1]);
}

value of a:156338880, value of &a[0]:156338880


value of b:15, value of a[-1]:15.
Discussions Lecture 4-5:
SAMPLE PROGRAM TO CHECK (ON LINUX UBUNTU 64 BIT):
#include<stdio.h>
int main()
{
int a,b; char c;
printf("give first integer:");
scanf("%d",&a);
printf("give character:");
scanf("%c",&c);
printf("give second integer:");
scanf("%d",&b);
}

give first integer:45


give character:give second integer:34
Discussions Lecture 4-5:
SAMPLE PROGRAM TO CHECK (ON LINUX UBUNTU 64 BIT):
#include<stdio.h>
int main()
{
int a,b; char c;
printf("give first integer:");
scanf("%d",&a);
printf("give character:");
//fflush(stdin);
scanf ("%*[^\n]");
scanf ("%*c");
scanf("%c",&c);
printf("the char is %d %c\n",c,c);
printf("give second integer:");
scanf("%d",&b);
}
give first integer:34
give character:q
the char is 113 q
give second integer:45
Discussions Lecture 4-5:
scanf ("%*[^\n]");
scanf ("%*c");

● %*[^\n] scans everything until a \n, but doesn't scan in the \n. The asterisk(*)
tells it to discard whatever was scanned.
● %*c scans a single character, which will be the \n left over by %*[^\n] in this
case. The asterisk instructs scanf to discard the scanned character.
● Both %[ and %c are format specifiers. You can see what they do. The asterisks in both
the specifiers tell scanf , not to store the data read by these format specifiers.
● fflush(stdout) is permitted to be used.
● However fflush(stdin) in undefined in ANSI C and therefore it may or may not
work.
● Very good reference material for scanf():
http://www.cplusplus.com/reference/cstdio/scanf/
Programming Concepts of C Language
Use of escape sequences in printf():
\n,\t etc….
Use of getch() & getche() in Windows C compilers
#include<conio.h>
char x;
x=getch();

How program is loaded in memory:


- Code area, data area, stack area and heap (area)
- Concept of segment and its size 64KiB(2^16) 64 Kilobytes

- Code area: code in machine language goes here


- Data area: all variables declared in the program are stored here
- Stack area: used to implement function calls and returns
- Heap : Whatever memory remains is heap.
Programming Concepts of C Language
Static and Dynamic Memory Allocation:
Static: Memory allocation at compile time and it goes to data area.
#include<stdio.h>
int main()
{
int a[1025][1025];
printf("memory allocated successfully\n");
}
memory allocated successfully
#include<stdio.h>
int main()
{
int a[2000][2000];
printf("memory allocated successfully\n");
}
Segmentation fault (core dumped)
Programming Concepts of C Language
Dynamic: Memory allocation at run time and it goes to heap area.

malloc(no_of_bytes); returns a pointer of type void

free(pointer); frees the memory allocated by dynamic memory allocation and


attached to this pointer.

To make things compiler independent, normally we do not provide the number of


bytes directly in malloc().

Instead, we use sizeof() function to allocate bytes based on the type of the data so
that it can run on any machine.
Discussions Lecture-6
Array space allocation example:
#include<stdio.h>
int main()
{
int a[10];
int *p;
a[0]=10;
p=a;
printf("%d %d %d\n",p[0],a[0],*a);
}
10 10 10
Discussions Lecture-6
Password program using getch(): (for Windows compiler only)
#include<stdio.h>
#include<conio.h> x This line not required in LINUX
int main()
{
char p[20],x;
int i=0,j;
printf("give password:");
do
{
x=getch(); x=getc(stdin); in LINUX
if (x!=13) 10 instead of 13 in LINUX (10 is LF in LINUX,
{ while13,10 is CRLF in Windows)
p[i]=x;
//printf("*");
}
i++;
}
while(x!=13); 10 instead of 13 in LINUX
printf("\nthe password is:");
for(j=0;j<i;j++)
printf("%c",p[j]);
}
Discussions Lecture-6
How to make a career in IT Industry
(For those who are comfortable with C programming. Those who are not, please
don’t try these).
1. Start using LINUX instead of Windows environment. I will suggest Ubuntu
Latest release.
2. Learn Java (OO Programming language) and JavaScript (OO Scripting
Language) Both these languages have C type syntax.
- Java creates applications that run in a virtual machine or browser.
- JavaScript runs in a browser only and makes your web pages more
interactive.
3. Start learning and using “Sublime Text” for all your text manipulation needs.
4. Start using “Visual Studio Code” for all your coding.
5. Learn language “Go”. See online tutorials for the same.
6. If you have learned these and use them regularly, 50% of your work for
getting a job in IT industry is done.
Programming Concepts of C Language
Conditional statements:
if ….... else …………
switch()
Break;
switch (expression)
{
case constant1:
// statements
break;

case constant2:
// statements
break;
.
.
.
default:
// default statements
}
Programming Concepts of C Language
Looping:
for(i=0; i<10; i++)
{
}
while( )
{
}

do {

} while( );
Programming Concepts of C Language ……….
Functional types of variables:
auto, static, register, extern
Functions:
-Role and concepts
-Procedures and Functions
-Parameter passing mechanisms (by value, by address/reference)
-use of Pointers
scanf and printf :
Use of & in scanf and not in printf
Global and local variables, Formal parameter

Book: C: A Software Engineering Approach by Darnell and Margolis - Springer

The C Programming Language by Kernighan and Ritchie - vPearson Rs. 274/-


Discussions Lecture-7
#include<stdio.h>
int main()
{
int a[10];
int *p;
a[0]=10;
printf("%p %p %p\n",&a,a,&a[0]);
printf("%p %p\n",p,&p);
printf("%ld %ld %ld\n",sizeof(a),sizeof(&a),sizeof(*a));
}
0x7ffc1d3b0640 0x7ffc1d3b0640 0x7ffc1d3b0640
0x55c84de2525d 0x7ffc1d3b0638
40 8 4
Discussions Lecture-7
#include<stdio.h>
#define n 4.5
int main()
{
const int p=6;
int *q;
printf("%f\n",n);
printf("%d %p\n",p,&p);
printf("%ld %ld %ld\n",sizeof(n),sizeof(p),sizeof(&p));
}
4.500000
6 0x7ffdb9d66a04
848

Relationships between different subjects of Computer Science:


Operating System
Compiler Design
Computer Architecture
Microprocessors
Discussions Lecture-7
Concept of lvalue and rvalue:
Lvalue: can be used on both sides of equal to sign - variables
Rvalue: only on the right hand side of the equal to sign - constants

Wikipedia page on C language implementation of arrays says:

Thus, despite this apparent equivalence between array name and pointer variables, there is still a
distinction to be made between them. Even though the name of an array is, in most expression contexts,
converted into a pointer (to its first element), this pointer does not itself occupy any storage; the array
name is not an l-value, and its address is a constant, unlike a pointer variable. Consequently, what an
array "points to" cannot be changed, and it is impossible to assign a new address to an array name.

int sum(int a,int b)


{ int c;
c=a+b;
return c;
}
Discussions Lecture-7
void sumdiff(int a,int b,int s,int d)
{ s=a+b;
d=a-b;
printf(“%d %d\n”,s,d);
}
int main()
{
int p,q,r,s;
p=10;
q=5;
r=50;
s=100;
sumdiff(p,q,r,s);
printf(“%d %d\n”,r,s);
}
Discussions Lecture-7
void sumdiff(int a,int b,int *s,int *d)
{ *s=a+b;
*d=a-b;
printf(“%d %d\n”,*s,*d);
}
int main()
{
int p,q,r,s;
p=10;
q=5;
r=50;
s=100;
sumdiff(p,q,&r,&s);
printf(“%d %d\n”,r,s);
}
Programming Concepts of C Language ……….
Recursion:
Feature of structured programming languages
They allow the a function to call itself.
Based on Rule of Mathematical Induction.
Properties for recursion to work:
1. Function should be definable in terms of itself.
2. While defining in terms of itself, the dimension of the problem should change.
3. There must be a terminating condition. There can be more than one
terminating condition.
4. Change of dimension of step 2 should approach step 3.
Examples:
Factorial
Summing the series
Tower of Hanoi
Jumping Car problem
Programming Concepts of C Language ……….
Recursion:
General format:
If (term_cond)
{
terminating_assignment;
}
else
{
recursive_definition:
}

Head recursion
Tail recursion
#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
printf("%d\n",fact(5));
getch();
}
int fact(int n)
{
int f;
if (n==1)
f=1;
else
{
f=n*fact(n-1);
}
return f;
}
DISCUSSIONS LECTURE-8
Functions & Procedures:

1. Whenever an array is declared, in addition to the storage space for actual elements, an
additional constant with array name of type pointer is created with address of first
element stored in it.
2. Arrays are always passed to functions as address. This is called call by reference.
3. For variables declared as global or static, storage space is provided on data area; while
for auto variables storage space is provided on the stack.
4. No global variables to be used. Globals will be used only for macros and definitions.
5. The compiler implements functions by just creating variables as defined in formal
parameter list and passing values to them from calling program. Whether it will be call
by value or call by reference will be decided how variables have been defined in formal
parameter list.
6. In C, it is possible to write functions behaving as both classical functions and classical
procedures.
7. We will try to write functions in C which are totally independent. This will make our
programming fully modular. All values used in the function will either be in formal
parameter list or defined locally in the function.
DISCUSSIONS LECTURE-8
Recursion:

1. Recursion itself implements a loop. Normally no loops will be used in a recursive


function. It will always be if……...else……… statement.
2. Recursive functions can have more than one terminating conditions.
3. In head recursion, lines following recursive call are executed in the return path.
4. In tail recursion, lines above recursive call are executed in the forward path.
5. If lines are present before as well as after the recursive call, lines before recursive call
are executed in forward path; those following recursive call are executed in reverse
path.
6. A lot many problems can only be solved by recursion only. Any other method to solve
them will automatically implement recursion indirectly.
7. A function can have multiple recursive calls in it. This helps in solving many a problems
which otherwise will require a lot more effort in solving them through computer
programs.
DISCUSSIONS LECTURE-8
Complexity of algorithms:
Asymptotic notations (Large Number of values almost infinite):

Theta notation: Used to analyze average case complexity of an algorithm


Big-O notation: Used to represent worst case complexity of an algorithm
Omega notation: Used to represent best case complexity of an algorithm
General complexity notations(for data size very large N): (1 Year = 31536000 secs.)
N= 10 100 1000 10000
O(1) -----------------FIXED- ASSUME 1 SEC-------------------

O(log2N) 4 7 10 14

O(N log2N) 40 700 10,000 140000

O(N2) 100 10,000 1000000 100000000 (>3 yrs.)

O(2N) 1024 1.26765x1030 CALCULATEYOURSELF--------------


4.02X1022 YEARS
TOWER OF HANOI PROBLEM:

{ ¥, / /
The objective of the problem is as follows:

N disks
A
1. There are three pegs named A.B and C as shown above.
¥5 c-
2. N disks are present on peg A in decreasing order from bottom to top.
3. These N disks are to be moved from peg A (source) to peg C (destination) (using peg B
called intermediate) following two rules in minimum number of steps:
a. Move only one disk at a time.
b. At no time, on no peg, a larger disk should come over a smaller disk.
As can be seen, a solution to this problem is impossible; unless we think recursively.
RECURSIVE SOLUTION TO PROBLEM OF TOWER OF HANOI:
To move N disks from peg A to peg C, do the following:
1. Move top N-1 disks from peg A to peg B (using peg C as intermediate).
2. Now move one disk from peg A to peg C. (of course no intermediate peg is required).
3. Now move N-1 disks from peg B to peg C (using peg A as intermediate).
How to move N-1 disks as mentioned above:
Think recursively. Do the same with N-2 disks.
The disk will actually be moved when N=1. (Terminating Condition)
RECURSIVE FUNCTION FOR TOWER OF HANOI PROBLEM:

void move(int n,int a,int b,int c) // n: number of disks; a: source


{ // c: destination, b: intermediate
static int i=1; // i: for printing step number
If (n==1)
{
printf(“%d.move one disk from %d to %d\n”,i,a,c);
i++;
}
else
{
move(n-1,a,c,b);
move(1,a,b,c);
move(n-1,b,a,c);
}
}

Let’s say, this will be called for four disks in main() as:
move(4,1,2,3);
Let’s see how it will work:
else part else part else part term. Cond.
------------- ------------- -------------- ----------------
move(4,1,2,3): see move(3,1,3,2); → move(2,1,2,3); → move(1,1,3,2); 1 to 2
move(1,1,2,3); move(1,1,3,2); move(1,1,2,3); →→ 1 to 3

I
tell
move(3,2,1,3); move(2,3,1,2); move(1,2,1,3); 2 to 3
1 to 2
move(1,3,2,1); 3 to 1
move(1,3,1,2); 3 to 2
move(1,1,3,2); 1 to 2
1 to 3
move(2,2,3,1); move(1,2,1,3); 2 to 3
move(1,2,1,3); move(1,2,3,1); 2 to 1

←÷
-

move(2,1,2,3); move(1,3,2,1) 3 to 1
2 to 3
move(1,1,3,2); 1 to 2
move(1,1,2,3); 1 to 3
move(1,2,1,3); → 2 to 3
Time complexity of Tower of Hanoi Problem:

1. For N=1; Movements: 1


2. For N=2; Movements: 3
3. For N=3; Movements: 7

4. For N disks; Movements: 2N - 1 (Exponential time)


Jumping Cars Problem: Problem statement:

# i¥ ¥

1. On a single lane road, N cars from left side and N cars from right side approach
each other; touching bumper to bumper. They stop with exactly a gap of one car
in between as shown above. (It can be different number of cars on both the
sides).
2. None of these cars have reverse gears. The can’t go reverse.
3. All these cars have a push button called HOP. When pressed, the car can hop one
car at a time in forward direction.
4. The rule of mathematical induction says: if somethin proved for N=1 and N=2, it
should be true for all values of N.
5. In this case it can be seen that cars can pass for N=1 as well as N=2.
6. Try solving the problem for N=4. Actually any number of cars can pass through in
this problem.
7. GOOD LUCK.
Reserved words in C language:

You might also like