PPS Material
PPS Material
GTU # 3110003
USING
Introduction to {C}
Programming
computer and
programming
CONTROL UNIT
PRIMARY MEMORY
(RAM, ROM etc…)
SECONDARY MEMORY
(Hard disk, Pen drive etc…)
Subroutine Arrows
Print no is Print no is
Positive Negative
Stop
Print no is Print no is
Even Odd
Stop
Print a is Print b is
largest largest
Stop
Read a, b, c
True False
Is a>b
Stop
True False
Is a<=10
Stop
Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING
Fundamentals {C}
Programming
of C
Data types in C
a b a&&b a||b
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
Example Explanation
x=100; After the execution the
x++; value of x will be 101.
Example Explanation
x=100; After the execution the
x--; value of x will be 99.
Operator Description
Post increment operator (x++) value of x is incremented after assigning it to the variable on
the left
Example Example
m=2, n=3; m=2, n=3;
r=(m>n) ? m : n; r=(m<n) ? m : n;
Explanation Explanation
Value of r will be 3 Value of r will be 2
Example: Bitwise << (Shift Left) Example: Bitwise >> (Shift Right)
int a=8, b; int a=8, b;
b = a << 1; b = a >> 1;
printf("Output = %d", b); printf("Output = %d", b);
Output Output
16 (multiplying a by a power of two) 4 (dividing a by a power of two)
Operator Meaning
& Address operator, it is used to determine address of the variable.
* Pointer operator, it is used to declare pointer variable and to get value from it.
, Comma operator. It is used to link the related expressions together.
sizeof It returns the number of bytes the operand occupies.
. member selection operator, used in structure.
-> member selection operator, used in pointer to structure.
answer = a + b * c;
Output
Enter a character: a
Entered character is: a
Output
Enter a string: india
Entered string is: india
Object Executable
Are there No Code Code
preprocessor Compiler Linker
directive
Yes
Decision {C}
Programming
making in
C
if number is odd
{
/* code */
}
If statement
if
if is single branch decision making statement.
If condition is true then only body will be executed.
if is a keyword. Flowchart of if
Syntax
if(condition)
{ False
// Body of the if condition
// true part
}
True
Program Output
1 #include<stdio.h> Enter Number:0
2 void main() Zero
3 {
4 int a;
5 printf("Enter Number:");
6 scanf("%d",&a);
7 if(a == 0)
8 {
9 printf("Zero");
10 }
11 }
Program Output
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a >= 0)
8 {
9 printf("Positive Number");
10 }
11 if(a < 0)
12 {
13 printf("Negative Number");
14 }
15 }
Program Output
1 #include<stdio.h> Enter Number:12
2 void main() Even Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:11
6 scanf("%d",&a); Odd Number
7 if(a%2 == 0)
8 {
9 printf("Even Number");
10 }
11 if(a%2 != 0)
12 {
13 printf("Odd Number");
14 }
15 }
If..else statement
if...else
if…else is two branch decision making statement
If condition is true then true part will be executed else false part will be executed
else is keyword
Flowchart of if…else
Syntax
if(condition)
{ True False
// true part condition
}
else
{
// false part … …
}
Program Output
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a >= 0)
8 {
9 printf("Positive Number");
10 }
11 else
12 {
13 printf("Negative Number");
14 }
15 }
Program Output
1 #include<stdio.h> Enter Number:12
2 void main() Even Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:11
6 scanf("%d",&a); Odd Number
7 if(a%2 == 0)
8 {
9 printf("Even Number");
10 }
11 else
12 {
13 printf("Odd Number");
14 }
15 }
Program Output
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 if(a > b)
8 {
9 printf("%d is largest", a);
10 }
11 if(a < b)
12 {
13 printf("%d is largest", b);
14 }
15 }
Program Output
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 if(a > b)
8 {
9 printf("%d is largest", a);
10 }
11 else
12 {
13 printf("%d is largest", b);
14 }
15 }
condition False
1
… …
Program Output
1 #include<stdio.h> Enter Number:5
2 void main() Positive Number
3 {
4 int a; Output
5 printf("Enter Number:"); Enter Number:-5
6 scanf("%d",&a); Negative Number
7 if(a > 0)
8 printf("Positive Number");
9 else if(a==0)
10 printf("Zero");
11 else
12 printf("Negative Number");
13 }
Nested if
Nested if
If condition-1 is true then condition-2 is evaluated. If it is true then statement-1 will
be executed.
If condition-1 is false then statement-3 will be executed.
Syntax
if(condition-1)
{
if(condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
True
Statement Statement
1 2
Next
Statement
Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 85
WAP to print maximum from given three numbers
Program
1 void main(){
2 int a, b, c; Output
3 printf("Enter Three Numbers:"); Enter Three Numbers:7
4 scanf("%d%d%d",&a,&b,&c); 5
5 if(a>b) 9
6 { 9 is max
7 if(a>c)
8 printf("%d is max",a);
9 else
10 printf("%d is max",c);
11 }
12 else
13 {
14 if(b>c)
15 printf("%d is max",b);
16 else
17 printf("%d is max",c);
18 }
19 }
Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 86
Conditional Operator
? : (Conditional Operator)
The conditional works operator is similar to the if-else.
It is also known as a ternary operator.
It returns first value of expression (before colon(:)) if expression is true and second
value of expression if expression is false.
False
True
Program Output
1 #include<stdio.h> Enter Two Numbers:4
2 void main() 5
3 { 5 is largest
4 int a, b, max;
5 printf("Enter Two Numbers:");
6 scanf("%d%d",&a,&b);
7 max = a>b?a:b;
8 printf("%d is largest",max);
9 }
switch…case
switch...case
The switch statement allows to execute one code block among many alternatives.
It works similar to if...else..if ladder.
Syntax The expression is evaluated once and
switch (expression) compared with the values of each case.
{
case constant1: If there is a match, the corresponding
// statements statements after the matching case are
break; executed.
case constant2:
// statements If there is no match, the default
break; statements are executed.
.
. If we do not use break, all statements
. after the matching label are executed.
default:
// default statements The default clause inside the switch
} statement is optional.
Prof. Nilesh Gambhava #3110003 (PPS) – Decision Making 92
WAP that asks day number and prints day name using switch…case
void main(){ case 7:
int day; printf("Saturday");
printf("Enter day number(1-7):"); break;
scanf("%d",&day); default:
switch(day) printf("Wrong input");
{ break;
case 1: }
printf("Sunday"); }
break;
case 2:
printf("Monday");
break;
case 3:
Output
printf("Tuesday");
break; Enter day number(1-7):5
case 4: Thursday
printf("Wednesday");
break;
case 5:
printf("Thursday");
break;
case 6:
printf("Friday");
break;
Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING
Looping {C}
Programming
“Hello” 5
Output
printf("Hello\n"); Hello
printf("Hello\n"); Hello loop(condition)
{
printf("Hello\n"); Hello //statements
printf("Hello\n"); Hello }
printf("Hello\n"); Hello
False False
condition condition
True True
… …
While loop
While Loop
while is an entry controlled loop
Statements inside the body of while are repeatedly executed till the condition is
true
while is keyword
Syntax
while(condition)
{
// Body of the while
// true part
}
Program Output
1 #include <stdio.h> Enter n:10
2 void main() 1
3 { 2
4 int i,n; 3
5 i=1; 4
6 printf("Enter n:"); 5
7 scanf("%d",&n); 6
8 while(i<=n) 7
9 { 8
10 printf("%d\n",i); 9
11 i=i+1; 10
12 }
13 }
Program Output
1 #include<stdio.h> Enter n for multiplication table:5
2 void main() 5 * 1 = 5
3 { 5 * 2 = 10
5 * 3 = 15
4 int i=1,n;
5 * 4 = 20
5 printf("Enter n for multiplication table:"); 5 * 5 = 25
6 scanf("%d",&n); 5 * 6 = 30
7 while(i<=10) 5 * 7 = 35
8 { 5 * 8 = 40
9 printf("%d * %d = %d\n",n,i,n*i); 5 * 9 = 45
10 i=i+1; 5 * 10 = 50
11 }
12 }
Program Output
1 #include<stdio.h> Enter a number=10
2 void main() Enter a number=20
3 { Enter a number=30
Enter a number=40
4 int sum=0, i=1,n;
Enter a number=50
5 while(i<=5) Sum is=150
6 {
7 printf("Enter a number=");
8 scanf("%d",&n);
9 sum=sum+n;
10 i=i+1;
11 }
12 printf("Sum is=%d",sum);
13 }
Syntax Logic
while(condition) int i = 1;
{ while (i <= 5)
// Body of the while {
// true part printf("%d\n", i);
} i=i+1;
}
From this we can infer that loop variable i starts with 1 and incremented by one
for next iteration then ends at value n.
Consider n=10, factors are 1,2,5,10
Consider n=11, factor is 1,11
From this we can infer that 1 and number itself are always factors of any number n.
i=i+1
Stop
Prof. Nilesh Gambhava #3110003 (PPS) – Looping 111
How to build logic? Step-4
Step 4: Writing Pseudo-code
Pseudo-code is an informal way to express the design of a computer program or
an algorithm.
It does not require any strict programming language syntax.
Pseudo-code
Initialize i=1 integer
Declare n as integer
Input n
while i<n
if n%i
print i
end if
increment i=i+1
end while
Program Output
1 #include <stdio.h> Enter n to find factors=12
2 void main() 1,2,3,4,6,12,
3 {
4 int i=1,n;
5 printf("Enter n to find factors=");
6 scanf("%d",&n);
7 while(i<=n)
8 {
9 if(n%i==0)
10 printf("%d,",i);
11 i=i+1;
12 }
13 }
Program Output
1 #include <stdio.h> Enter a number=1234
2 void main() 4321
3 {
4 int n;
5 printf("Enter a number=");
6 scanf("%d",&n);
7 while(n!=0)
8 {
9 printf("%d",n%10);
10 n=n/10;
11 }
12 }
for loop
for Loop
for is an entry controlled loop
Statements inside the body of for are repeatedly executed till the condition is true
for is keyword
Syntax
for (initialization; condition; updateStatement)
{
// statements
}
Program Output
1 #include<stdio.h> Enter a number:5
2 void main() 1
3 { 2
4 int i,n; 3
5 printf("Enter a number:"); 4
6 scanf("%d",&n); 5
7 for(i=1;i<=n;i++)
8 {
9 printf("%d\n",i);
10 }
11 }
Program Output
1 #include <stdio.h> Enter n to find factors=12
2 void main() 1,2,3,4,6,12,
3 {
4 int i,n;
5 printf("Enter n to find factors=");
6 scanf("%d",&n);
7 for(i=1;i<=n;i++)
8 {
9 if(n%i==0)
10 printf("%d,",i);
11 }
12 }
do while loop
do while Loop
do while is an exit controlled loop.
Statements inside the body of do while are repeatedly executed till the condition
is true.
Do and while are keywords. Syntax
do
{
// statement
}
while (condition);
Program Output
1 void main() Enter a number:5
2 { 1,3,5
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 if(i%2!=0)
9 {
10 printf("%d,",i);
11 }
12 i=i+1;
13 }
14 while(i<=n);
15 }
Program Output
1 void main() Enter a number:6
2 { 1,2,3,6,
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 if(n%i==0)
9 {
10 printf("%d,",i);
11 }
12 i=i+1;
13 }
14 while(i<=n);
15 }
Program Output
1 void main() Enter a number=1234
2 { 4321
3 int n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 do
7 {
8 printf("%d",n%10);
9 n=n/10;
10 }
11 while(n!=0);
12 }
goto statement
goto Statement
goto is an virtual loop
The goto statement allows us to transfer control of the program to the specified
label.
goto is keyword
Syntax Syntax
goto label; label:
. .
. .
. .
label: goto label;
The label is an identifier. When the goto statement is encountered, the control of
the program jumps to label: and starts executing the code.
Program Output
1 void main() Enter a number:5
2 { 1,3,5
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 odd:
7 if(i%2!=0)
8 {
9 printf("%d,",i);
10 }
11 i=i+1;
12 if(i<=n)
13 {
14 goto odd;
15 }
16 }
Program Output
1 void main() Enter a number:6
2 { 1,2,3,6,
3 int i=1,n;
4 printf("Enter a number:");
5 scanf("%d",&n);
6 odd:
7 if(n%i==0)
8 {
9 printf("%d,",i);
10 }
11 i=i+1;
12 if(i<=n)
13 {
14 goto odd;
15 }
16 }
False
Loop Body Label Statement
condition
True True
condition condition
Loop Body
False True False
goto
Pattern
Always detect pattern in pattern
Pattern
There are important points to note in pattern
1. Determine, how many rows?
2. Determine, how many numbers/characters/columns in a row?
3. Determine, Increment/Decrement among the number of rows.
4. Determine, starting in each row
1 1 1 *
11 12 23 * *
111 123 456 * * *
1111 1234 78910 * * * *
11111 12345 * * *
* *
*
Starting: *
Starting: 1
Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING
Strings
float
Each character in the array occupies one byte of memory, and the last character
must always be null('\0').
The termination character ('\0') is important in a string to identify where the
string ends.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10] D A R S H A N \0
Initialization method 1:
char name[10]={'D','A','R','S','H','A','N','\0'};
Initialization method 2:
char name[10]="DARSHAN";
//'\0' will be automatically inserted at the end in this type of declaration.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
name[10] D A R S H A N \0
gets(): Reads characters from the standard input and stores them as a string.
puts(): Prints characters from the standard.
scanf(): Reads input until it encounters whitespace, newline or End Of File(EOF)
whereas gets() reads input until it encounters newline or End Of File(EOF).
gets(): Does not stop reading input when it encounters whitespace instead it
takes whitespace as a string.
Program
1 #include <stdio.h> Output
2 #include <string.h> //header file for string functions Enter string: CE Darshan
3 void main() 10
4 {
5 char s1[10];
6 printf("Enter string:");
7 gets(s1);
8 printf("%d",strlen(s1)); // returns length of s1 in integer
9 }
strchr(s1,c) Returns a pointer to the first occurrence of a given character in the string s1.
printf("%s",strchr(s1,'i'));
Output : ir
strstr(s1,s2) Returns a pointer to the first occurrence of a given string s2 in string s1.
printf("%s",strstr(s1,"he"));
Output : heir
Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING
Functions {C}
Programming
Why function ?
Avoids rewriting the same code over and over.
Using functions it becomes easier to write programs and keep track of what they doing.
void main()
{
....
func1(); Function call
}
void func1()
{
.... Function definition
//function body
....
}
Syntax Example
return-type function-name (arg-1, arg 2, …); void addition(int, int);
Syntax Example
return-type function-name (arg-1, arg 2, …) void addition(int x, int y)
{ {
//... Function body printf("Addition is=%d“,(x+y));
} }
Syntax
return;
Or
return (expression);
Output
Enter the number :7
The number 7 is a prime number.
Storage Initial
Storage Scope Life Example
Specifier Value
Automatic int a;
Stack Garbage Within block End of block
{auto} auto int a;
Till end of
Static Data Zero Within block static extern int var;
program
{static} segment static int var;
Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING
Recursion {C}
Programming
void main()
{
....
func1();
.... Function
} call
void func1()
{ Recursive
.... function call
func1();
....
}
Example call
return 0
Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING
Pointer {C}
Programming
Example
1 void main()
2 { Variable Value Address
3 int a=10, *p; // assign memory address of a
4 to pointer variable p a 10 5000
5 p = &a;
6 printf("%d %d %d", a, *p, p); p 5048
7 }
5000
Output
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Syntax
1 datatype *name[size];
Example
1 int *ptr[5]; //declares an array of integer pointer of size 5
ptr 0 1 2
ptr[0]
ptr[1]
ptr[2]
ptr[3]
ptr[4]
Output
Enter value of num1 and num2: 5
10
Before Swapping: num1 is: 5, num2 is: 10
After Swapping: num1 is: 10, num2 is: 5
Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING
Structure {C}
Programming
Data types in C
C language has built-in datatypes like primary and derived data types.
But, still not all real world problems can be solved using those data types.
We need custom datatype for different situation.
Prof. Nilesh Gambhava #3110003 (PPS) – Structure 220
User Defined Datatype
We need combination of various datatypes to understand different entity/object.
Example-1:
Book Title: Let Us C Datatype: char / string
Author: Yashavant Kanetkar Datatype: char / string
Page: 320 Datatype: int
Price: 255.00 Datatype: float
Example-2:
Student Name: ABC Datatype: char / string
Roll_No: 180540107001 Datatype: int
CPI: 7.46 Datatype: float
Backlog: 01 Datatype: int
Example
1 struct student
2 {
3 char name[30]; // Student Name
4 int roll_no; // Student Roll No
5 float CPI; // Student CPI
6 int backlog; // Student Backlog
7 };
8 struct student student1; // Declare structure variable
Syntax Example
1 structure_variable.member_name; 1 // Assign CPI of student1
2 student1.CPI = 7.46;
2. Arrow operator (->)
In C language it is illegal to access a structure member from a pointer to structure variable
using dot operator.
We use arrow operator to access structure member from pointer to structure.
Syntax Example
1 pointer_to_structure->member_name; 1 // Student1 is a pointer to student type
2 student1 -> CPI = 7.46;
Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING
Union {C}
Programming
Basic The separate memory location is allotted to All members of the 'union' share the same memory location.
each member of the structure.
keyword 'struct' 'union'
Size Size of Structure = sum of size of all the data Size of Union = size of the largest member.
members.
Store Value Stores distinct values for all the members. Stores same value for all the members.
At a Time A structure stores multiple values, of the A union stores a single value at a time for all members.
different members, of the structure.
Declaration struct ss union uu
4 bytes
{ 1 byte for c {
int a; int a; c
float f; 2 bytes for a float f; a
f
char c 4 bytes for f char c
}; };
Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING
Dynamic {C}
Programming
Memory
Allocation
Computer Engineering Department,
Darshan Institute of Engineering & Technology, Rajkot
Dynamic Memory Allocation (DMA)
If memory is allocated at runtime (during execution of program) then it is called
dynamic memory.
It allocates memory from heap (heap: it is an empty area in memory)
Memory can be accessed only through a pointer.
Program
1 #include <stdio.h>
2 void main()
3 {
4 int *fp; //fp is a pointer variable
5 fp = (int *)malloc(sizeof(int)); //returns a pointer to int size storage
6 *fp = 25; //store 25 in the address pointed by fp
7 printf("%d", *fp); //print the value of fp, i.e. 25
8 free(fp); //free up the space pointed to by fp
9 }
Output
25
Syntax Description
ptr_var = (cast_type *) This statement returns a pointer to new space, or NULL if the request
realloc (void *fp, cannot be satisfied.
size_t);
Example: fp = (int *)realloc(fp,sizeof(int)*20);
Output
25
Syntax Description
void free(void *); This statement free up the memory not needed anymore.
Example: free(fp);
Thank you
Programming for Problem Solving (PPS)
GTU # 3110003
USING
File {C}
Programming
Management
Open the file for reading only. If it exists, then the file is opened with the current contents;
r
otherwise an error occurs.
Open the file for writing only. A file with specified name is created if the file does not exists.
w
The contents are deleted, if the file already exists.
Open the file for appending (or adding data at the end of file) data to it. The file is opened
a with the current contents safe. A file with the specified name is created if the file does not
exists.
r+ The existing file is opened to the beginning for both reading and writing.
Note: The main difference is w+ truncate the file to zero length if it exists or create a new file if it doesn't.
While r+ neither deletes the content nor create a new file if it doesn't exist.
Prof. Nilesh Gambhava #3110003 (PPS) – Introduction to C 264
File Handling Functions
Basic file operation performed on a file are opening, reading, writing, and closing a
file.
Syntax Description
fp=fopen(file_name, This statement opens the file and assigns an identifier to the FILE type pointer
mode); fp.
Example: fp = fopen("printfile.c","r");
fclose(filepointer); Closes a file and release the pointer.
Example: fclose(fp);
fprintf(fp, Here fp is a file pointer associated with a file. The control string contains items
“control string”, to be printed. The list may includes variables, constants and strings.
list);
Example: fprintf(fp, "%s %d %c", name, age, gender);
Example: c = getc(fp);
int putc(int c, putc() writes or appends the character c to the FILE fp. If a putc function is
FILE *fp); successful, it returns the character written, EOF if an error occurs.
Program
1 #include <stdio.h>
2 void main()
3 {
4 FILE *fp; //p is a FILE type pointer
5 char ch; //ch is used to store single character
6 fp = fopen("file1.c","r"); //open file in read mode and store file pointer in p
7 do { //repeat step 9 and 10 until EOF is reached
8 ch = getc(fp); //get character pointed by p into ch
9 putchar(ch); //print ch value on monitor
10 }while(ch != EOF); //condition to check EOF is reached or not
11 fclose(fp); //free up the file pointer pointed by fp
12 }
13
Syntax Description
fseek(FILE *fp, fseek() function is used to move the file position to a desired location within
long offset, the file. fp is a FILE pointer, offset is a value of datatype long, and position
int position); is an integer number.
Example: /* Go to the end of the file, past the last character of the file */
fseek(fp, 0L, 2);
long ftell(FILE *fp); ftell takes a file pointer and returns a number of datatype long, that
corresponds to the current position. This function is useful in saving the current
position of a file.
Syntax Description
rewind(fp); rewind() takes a file pointer and resets the position to the start of the file.
Example: /* The statement would assign 0 to n because the file position has been set
to the start of the file by rewind. */
rewind(fp);
Thank you