04. Programming in C
04. Programming in C
1
Cloud IT Online Batch Programming in C -04
Lecture Sheet-04
Programming in C
Syllabus:
2
Cloud IT Online Batch Programming in C -04
binary instructions, but their method of execution is Executable File- The binary executable file is
different. The complier converts the entire source generated by the linker. The linker links the various
code into machine level program, while the interpreter object files to produce a binary file that can be directly
takes 1 statement, translates it, executes it & then executed
again takes the next statement.
Assembler: The software that reads a program written COMPLIATION & EXECUTION OF A C
in assembly language and translates it into an PROGRAM
equivalent program in machine language is called as
assembler.
Linker: A linker or link editor is a computer program
that takes one or more object files generated by a
compiler and combines them into a single executable
file, library file, or another object file.
3
Cloud IT Online Batch Programming in C -04
Hierarchy of operations variable with any of the case inside the
While executing an arithmetic statement, which has switch. If it matches the case defined in the
two or more operators. We may have some problems switch then that match will be executed. If
as to how exactly does it get executed. To solve these none of the cases match the statement then
problems one has to understand hierarchy of default will be executed.
operations. The priority precedence in which the Loops
operation in an or arithmetic statement are performed These are used to execute a block of code several
is called the hierarchy of operations. number of times. The statements are executed
Priority Operations Description sequentially. Loop executes a statement or a group of
1st *,/, % Multiplication, statements multiple times. When the execution of
division, modular statements in the loop is unknown, then this concept is
division known as odd loop. Loops are of the following three
2nd +,- Addition, subtraction types:
3rd = Assignment 1. while loop: It repeats a statement or group of
statements while a given condition is true. It
tests the condition before executing the loop
Example a = 2*3/4 + 4/4 + 8 - 2 + 5/8
body.
= 6 /4+4/4+8-2+5/8
2. for loop: It executes a sequence of statements
=1+4/4+8-2+5/8
multiple times.
=1+1+8-2+5/8
3. do… while loop: It is similar to while
=1+1+8-2+0
statement, except that it tests the condition at
=2+8-2+0
the end of the loop body.
=10-2+0
There are various control statements used for
=8+0
changing execution from its normal sequence. These
a=8
are as follows:
CONTROL STATEMENTS 1. break statement: It terminates the loop or
In C, programs are executed sequentially in the order switch and transfers the execution to the
of which they appear. This condition does not hold statement immediately following the loop
true always. Sometimes a situation may arise where or switch.
we need to execute a certain part of the program. Also 2. continue statement: It skips the remainder of
it may happen that we may want to execute the same the loop body and immediately begins
part more than once. Control statements enable us to execution from the top.
specify the order in which the various instructions in 3. goto statement: It transfers control to the
the program are to be executed. They define how the labelled statement.
control is transferred to other parts of the program. 4. return statement: It transfers control from the
function to the calling function.
Conditional Statement
1. If: When the condition is satisfied then the
statements inside the parenthesis {} will be Previous Year Questions
executed. 1. What is the difference between while and do
2. If-Else: If the condition is true then the while loop? [ICT Ministry-2014]
statements between if and else will be
executed. If it is false then the statement after 2. Explain in details the different forms of looping
else will be executed. In nested if, one or statement in C language. [Multi. Ministry-2017
more if-else block(s) lie within the parent if
statement. Rules for Switch Statement in C Language
3. Else-If: If the condition is true then the For switch only the integer /char type
statements between if and else if will be variables or expression evaluates to integral
executed. If it is false then the condition in allowed. You can also provide expressions,
else if is checked, and if it is true it will be
executed. but the result of the expression should not
4. Switch: It is also known as matching case return a float or decimal value. The Switch
statements. It is used to test for equality statement will not accept float, double string,
against a list of values. It matches the value in or other data types.
4
Cloud IT Online Batch Programming in C -04
switch(x==5) // this is valid. no break
statement. So
switch(x/3) // this is not valid. all cases are
executed.
You can't use two case labels with the same
value. Duplicate case values would throw an Examples 2: Output: Program
error. raises an error called
switch(x) main () “Duplicate case”
{ { while compiling
case b: int i = 10; because the
// statement switch (i) expression „8+2‟
case b: { evaluate to „10‟.
//statements case 10:
} // this kind of switch statement will throw you printf
a compile-time error. ("case 10");
You can't define ranges within a case break;
case 8 + 2:
statement, nor can you use a single case label printf
for more than one value. A case label can hold ("case 8+2");
only one value. break;
switch(x) default:
{ printf
case 1,10: ("default
// statements case");
case 2-5: }
// statements }
} // these 2 case statements will also throw a
compile time error
Absent of break after case statement leads
continuation execution of all case statement
followed by matching case block. Valid switch
Switch (a), switch (a> b), switch (d +e-3), switch (a>
Examples 1: Output: case b && b> c), switch (func (a, b))
main () 10 case 15 2
{ case 20 Invalid switch
int i=10; default case switch (f), switch (a + 4.5)
switch (i) Explanation: Valid Case 4 :, Case 'a' : Case 2+ 4: Case 'a'> 'b'
{ The break Invalid Case "second"; Case 2.3; Case a :, Case a>
case 10:printf("case statement at b: , Case a + 2: , Case 2, 4, 5
10"); the end of
case 15:printf("case each case Unary Operator Problem
15"); label is printf ("%d %d %d", a++, a++, ++a); , then which
case 20:printf("case optional. sequence it will print?
20"); However, the We know that printf() uses stack. Means your last
default:printf("default control will argument is treated first then 2nd last argument at
case"); sequentially second place and first argument is treated at last. Like,
} pass through
} all other case ++a
labels
without the a++
break
statement. a++
Here there is
5
Cloud IT Online Batch Programming in C -04
Then second thing to remember is postfix Function Declaration OR Function Prototype:
increment/decrement has higher priority than 1. It is also known as function prototype.
prefix. This simply means that postfix will assign its 2. It informs the computer about the three things
value first then increment and prefix will increment a) Name of the function
first then assign its value just before that statement is b) Number and type of arguments received by
completed. the function.
Now let me show you how that statement actually c) Type of value return by the function
executed. Syntax : return_type function_name (type1
int a = 5; arg1 , type2 arg2);
printf ("%d %d %d", a++, a++, ++a); OR
Step 1: last argument is treated first. ++a return_type function_name (type1 type2);
becomes 6 but that last is not assigned value 3. Calling function need information about called
of 6 yet. It‟s waiting for whole statement to function .If called function is place before calling
execute then assign value. Yet we get value of function then the declaration is not needed.
a as 6
Step 2: Now it‟s time to treat 2nd or I can say Function Definition:
2nd last argument. Told you post increment 1. It consists of code description and code of a
instantly assigns value then do increment function .
operation. So 2nd argument gets value It consists of two parts
assigned to 6. Increment is now done and a) Function header
value of a turns out to be 7. b) Function coding
Step 3: That 7 value is assigned to first Function definition tells what are the I/O function and
argument and it turns value of a to 8. Now what is going to do.
that all the operations are performed so it‟s Syntax: return_type function_name (type1 arg1 ,
time for pre-increment to do its left out type2 arg2)
work(assignment of value). So last argument {
gets value of 8. local variable;
So answer of your query is : 7 6 8 statements ;
Again, printf ("%d %d %d %d",a++, a++, a++, return (expression);
++a); // output: 8 7 6 9. See It graphically, }
2. Function definition can be placed anywhere in the
program but generally placed after the main
function
3. Local variable declared inside the function is local
to that function. It cannot be used anywhere in the
program and its existence is only within the
function.
4. Function definition cannot be nested.
5. Return type denote the type of value that function
will return and return type is optional if omitted it
is assumed to be integer by default.
6
Cloud IT Online Batch Programming in C -04
In this method the value of each of the actual Writing Recursive Functions
arguments in the calling function is copied into A recursive function has the following two parts:
corresponding formal arguments of the called 1. Base case: It is the non-recursive solution and a
function. With this method, the changes made to the stopping condition.
formal arguments in the called function have no effect 2. Recursive case: It is the recursive solution of the
on the values of actual arguments in the calling problem.
function
ẹ.g., int sum(int n)
void swap V (int x, int y); { if(n==0) /* base case or stopping condition */
void main (){ return n;
int a = 10, b = 20; else
swap V (a, b); return n + sum(n-1); /*self-call to function sum() */
printf (“\ a = %d, b = % d", a, b); }
}
void swap V (int x, int y) In this program, sum() function is called itself in else
{ condition. If n is equal to 0 then the function returns
int t; the value passing in the argument, but if n is not equal
t = x; to 0 then the function calls itself. Let n = 5 initially,
x=y; then next time 4 is passed to the function and the
y=t; value of the parameter is decreased by 1 until the
printf (“\n x =%d, y = %d", x, y); condition is satisfied. At the end, when n becomes 0,
} the value of n is returned, which is from 5 to 1.
Output sum(5)
x =20 y = 10 = 5 + sum(4)
a=10 b =20 = 5 + 4 + sum(3)
2. Call by Reference [Pally Sa.-2018] = 5 + 4 + 3 + sum(2)
In this method, the addresses of actual arguments in = 5 + 4 + 3 + 2 + sum(1)
the calling function are copied into the formal = 5 + 4 + 3 + 2 + 1 + sum(0)
arguments of the called function. This means hat, =5+4+3+2+1+0
using these addresses, we would have an access to the =5+4+3+2+1
actual arguments and hence, we would be able to =5+4+3+3
manipulate them. =5+4+6
e.g., = 5 + 10
void swapr (int*, int*) = 15
void main (){
int a = 10, b =20; How control flows in successive recursive calls?
swapr (& a, & b); Flow of control in successive recursive calls can be
printf (“\n a = % d b = % d", a, b); demonstrated in following example:
} Consider the following program which uses recursive
void swapr (int*x, int*y) function to compute the factorial of a number.
{ int t;
t=*x void main()
*x = *y; {
*y =t; int n,f;
} printf(“Enter a number”);
Output = a=20 b = 10 scanf(“%d”,&n);
f=fact(a);
Recursion [AP ICT ministry-2021] printf(“Factorial of %d is %d”,n,f);
When the function calls itself then it is called }
recursion. In C language, there is provision for the int fact(int m)
function to call itself. When using the recursion, it is {
necessary to have exit condition from the function; int a;
otherwise, the result will be infinite if (m==1)
7
Cloud IT Online Batch Programming in C -04
return (1); Previous Year Questions
else
a=m*fact(m-1); 1. What is recursion? Write a factorial program in
return (a); C using recursion. [MilkVita-23] [AP ICT ministry-2021]
} 2. Usually, recursion involves a function calling
itself until specified condition is met and it is
In the above program if the value entered by the user very useful to find out the factorial. Write a
is 1 i.e.n=1, then the value of n is copied into m. Since recursive algorithm to find the factorial of a
the value of m is 1 the condition „if(m==1)‟ is number.[Officer(SBL-JBL-IT)-2020]
satisfied and hence 1 is returned through return
statement i.e. factorial of 1 is 1. When the number
RECURSION VERSES ITERATION
entered is 2 i.e. n=2, the value of n is copied into m.
Every repetitive problem can be implemented
Then in function fact(), the condition „if(m==1)‟ fails
recursively or iteratively:
so we encounter the statement a=m*fact(m-1); and
Recursion should be used when the problem is
here we meet recursion. Since the value of m is 2 the
expression (m*fact(m-1)) is evaluated to (2*fact(1)) recursive in nature. Iteration should be used when
and the result is stored in a(factorial of a). Since value the problem is not inherently recursive.
returned by fact(1) is 1 so the above expression Recursive solutions incur more execution
reduced to (2*1) or simply 2. Thus the expression overhead than their iterative counterparts, but its
m*fact(m-1) is evaluated to 2 and stored in a and advantage is that recursive code is very simple.
returned to main(). Where it will print „Factorial of 2 Recursive version of a problem is slower than
is 2‟. In the above program if n=4 then main() will call
iterative version since it requires PUSH and POP
fact(4) and fact(4) will send back the computed value
i.e. f to main(). But before sending back to main() operations.
fact(4) will call fact(4-1) i.e. fact(3) and wait for a In both recursion and iteration, the same block of
value to be returned by fact(3). Similarly fact(3) will code is executed repeatedly, but in recursion
call fact(2) and so on. This series of calls continues repetition occurs when a function calls itself and
until m becomes 1 and fact(1) is called, which returns in iteration repetition occurs when the block of
a value which is so called as termination condition. So
code is finished or a continue statement is
we can now say what happened for n=4 is as follows
encountered.
fact(4) returns (4*fact(3) ) For complex problems iterative algorithms are
fact(3) returns (3*fact(2) ) difficult to implement but it is easier to solve
fact(2) returns (2*fact(1) )
recursively. Recursion can be removed by using
fact(1) returns (1)
iterative version.
STRING
String: Strings are defined as an array of characters.
So for n=4, the factorial of 4 is evaluated to
The difference between a character array and a string
4*3*2*1=24. For n=3, the control flow of the program
is the string is terminated with a special character
is as follows:
„\0‟.
Like: char name=”Cloud IT”
C L O U D I T \0
Declaration of strings: Declaring a string is as
simple as declaring a one-dimensional array.
Below is the basic syntax for declaring a string.
char str_name[size];
In the above syntax str_name is any name
given to the string variable and size is used to define
the length of the string, i.e the number of characters
strings will store. Please keep in mind that there is an
extra terminating character which is the Null
character („\0‟) used to indicate the termination of
8
Cloud IT Online Batch Programming in C -04
string which differentiates strings from normal *p: *p is a pointer to a variable, as shown below. It is
character arrays. also called single pointer. The single pointer has two
Or you can declare string like a pointer purposes: to create an array and to allow a function to
Char *p=”Cloud it book” change its contents (pass by reference).
‘\0’ character in C; [BCC-project-2021]
The null character '\0' (also null
terminator), is a control character with the value
zero. The character has much more significance in
C and it serves as a reserved character used to signify
the end of a string,often called a null-terminated
string **p: **p is a pointer to a pointer variable, also called
double pointer. It is a form of multiple indirection, or
SL.No. Function & Purpose a chain of pointers. When we define a pointer to a
1 strcpy(s1, s2); pointer, the first pointer contains the address of the
Copies string s2 into string s1. second pointer, which points to the location that
2 strcat(s1, s2); contains the actual value as shown below.
Concatenates string s2 onto the end of
string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less ***p: ***p is a pointer to a double pointer, rather a
than 0 if s1<s2; greater than 0 if s1>s2. pointer to a pointer to a pointer variable, as shown
5 strchr(s1, ch); below. It is mostly called triple pointer. It is an even
Returns a pointer to the first occurrence of higher level of multiple indirection or pointer
character ch in string s1. chaining. A triple pointer is used to traverse an array
6 strstr(s1, s2); of pointers.
Returns a pointer to the first occurrence of
string s2 in string s1. Example of Pointer demonstrating the use of &
and *
Pointer int main()
A pointer is a variable which stores the address of {
some other variables. The declaration of a pointer is /* Pointer of integer type, this can hold the
done as follows:
* address of a integer type variable.
Data type *variable_name;
*/
int *p;
See the following output:
#include <stdio.h>
int main() int var = 10;
{
int *ptr, q; /* Assigning the address of variable var to the
q = 50; pointer
/* address of q is assigned to * p. The p can hold the address of var because var is
ptr */ * an integer type variable.
ptr = &q;
*/
/* display q's value using ptr
variable */ p= &var;
printf("%d", *ptr); printf("Value of variable var is: %d", var);
return 0; printf("\nValue of variable var is: %d", *p);
} printf("\nAddress of variable var is: %p", &var);
Output: 50 printf("\nAddress of variable var is: %p", p);
*p vs **p vs ***p meaning: printf("\nAddress of pointer p is: %p", &p);
return 0;
9
Cloud IT Online Batch Programming in C -04
} int *ip; /* pointer variable
declaration */
ip = &var; /* store address of var
Output:
in pointer variable*/
Value of variable var is: 10 printf("Address of var variable:
Value of variable var is: 10 %x\n", &var );
Address of variable var is: 0x7fff5ed98c4c /* address stored in pointer
Address of variable var is: 0x7fff5ed98c4c variable */
Address of pointer p is: 0x7fff5ed98c50 printf("Address stored in ip
variable: %x\n", ip );
/* access the value using the
pointer */
printf("Value of *ip variable:
%d\n", *ip );
return 0;
}
Output: Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
Pointer to Pointer
We know, pointer is a variable that contains
See the following Example: address of another variable. Now this variable address
int main() might be stored in another pointer. Thus, we now have
{ a pointer that contains address of another pointer,
int var; known as pointer to pointer.
int *p,**pp,***ppp; Example 3:
var =100; main ()
p=&var; {
pp=&p; int i = 3, *p, **q;
p = &i;
ppp=&pp;
q=&p;
printf("value at var= printf("\n Address of i = %u", &i);
%d\n",var); printf("\n Address of i = %u", p);
printf("value available at *p= printf("\n Address of i = %u", *q);
%d\n",*p); printf("\n Address of p= %u", &p);
printf("value available at **p= printf("\n Address of p= %u", q);
%d\n",**pp); printf("\n Address of q = %u", &q);
printf("value available at ***p= printf("\n value of i= %d", i);
%d\n",***ppp); printf("\n value of i= %d", *(&i));
return 0; printf("\n value of i= %d", *p);
printf("\n value of i= %d", **q);
}
}
Output: If the memory map is **q=20555 , *p=20122 and
value at var= 100
i=2000
Then the output is:
value available at *p= 100 Address of i = 2000
Address of i = 2000
value available at **p= 100 Address of i = 2000
Address of p= 20122
value available at ***p= 100 Address of p = 20122
Understand Pointer how it works: Address of q = 20555
int main () {
Value of i = 3
int var = 20; /* actual variable
Value of i=3
declaration */
10
Cloud IT Online Batch Programming in C -04
Value of i=3
Value of i=3
Example 1:
void printxy(int x, int y)
{ int *ptr;
x=0;
ptr=&x;
y=*ptr;
*ptr=1;
printf("%d",%d",x,y);
}
NULL Pointers
It is always a good practice to assign a NULL value
to a pointer variable in case you do not have an exact
address to be assigned. This is done at the time of
variable declaration. A pointer that is assigned NULL
is called a null pointer.
The NULL pointer is a constant with a value of zero
Example2: defined in several standard libraries. Consider the
#include<stdio.h> following program −
void f(int *p, int*q) int main ()
{ {
p=q; int *ptr = NULL;
printf ("The value of ptr is :
*p=2;
%x\n", ptr);
} return 0;
}
int i=0, j=1; Output: The value of ptr is 0
int main() See the following example
{ int main()
f(&i, &j); {
printf("%d%d\n",i,j); int val[3] = { 5, 10, 20 };
return 0; int *ptr;
} ptr = val ; //assigning all
array value to ptr
printf("Elements of the array
are: ");
printf("%d %d %d ", ptr[0],
ptr[1], ptr[2]);
++*ptr; // increment the first
value of ptr
printf(" %d %d %d ", ptr[0],
ptr[1], ptr[2]);
printf(" %d",*(++ptr)); //
inctrement the index
return 0;
11
Cloud IT Online Batch Programming in C -04
} Creating a string
Output: 5 10 20 6 10 20 10 In the following example we are creating a
Here „val‟ array is assign to ptr. Then ptr string str using char character array of size 6.
point to the array. Print 5 10 20 . Now, ++*ptr
means increment the value of ptr *ptr is the first value
of array which is 5 ,So,++*ptr=++5=6. So, next output
is 6 10 20. And the final line ++ptr means increment
the index. Now ptr goes to index 1 which is 10. Print
10.
In most of the operating systems, programs
Creating a pointer for the string
are not permitted to access memory at address 0 The variable name of the string str holds the address
because that memory is reserved by the operating of the first element of the array i.e., it points at the
system. However, the memory address 0 has special starting memory address.
significance; it signals that the pointer is not intended So, we can create a character pointer ptr and store the
to point to an accessible memory location. But by address of the string str variable in it. This way, ptr
convention, if a pointer contains the null (zero) value, will point at the string str.
it is assumed to point to nothing.
char *ptr = str;
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
What is the correct output of the following
C program? [Com 6 bank AP-2021]
int array[] = {6,7,8,9,0,1,2,3,4,5,6};
*p=array+5;
printf(“%d\n”, p[1]);
a) 1 b) 2 c) 3 d) Compile Error Ans.: b
Pointer To String
We know that a string is a sequence of characters
which we save in an array. And in C programming
language the \0 null character marks the end of a
string.
12
Cloud IT Online Batch Programming in C -04
Example of String and array of character: operator * is used to access the value at an address.
int main(void) { In the statement „*ptr = 30‟, value at address ptr is
char name[] = "Harry Potter"; changed to 30. The address operator & is used to get
printf("%s", name); // Output: the address of a variable of any data type. In the
Harry Potter
printf("%s", name+1); // Output: function call statement „fun(&y)‟, address of y is
arry Potter passed so that y can be modified using its address.
printf("%c", *name); // Output: H #include <stdio.h>
printf("%c", *(name+7)); //
Output: o int main()
char *namePtr; {
namePtr = name; int *ptr;
printf("%c", *namePtr); // int x;
Output: H
printf("%c", *(namePtr+1)); // ptr = &x;
Output: a *ptr = 0;
printf("%c", *(namePtr+7)); //
Output: o printf(" x = %d\n", x);
printf(" *ptr = %d\n", *ptr);
Practices Problem: 1
char c[]="GATE2011'; *ptr += 5;
char *p=c; printf(" x = %d\n", x);
printf("%s",p+p[3]-p[1]); printf(" *ptr = %d\n", *ptr);
Ans:
(*ptr)++;
// p[3] is 'E' and p[1] is 'A'. printf(" x = %d\n", x);
// p[3] - p[1] = ASCII value of 'E' - ASCII value of printf(" *ptr = %d\n", *ptr);
'A' = 4
// So the expression p + p[3] - p[1] becomes p + 4 return 0;
which is }
// base address of string "2011"
Or let the address of p is 2000 so, 2000+E-
A=2000+4=2004= p[4]=2 Structures and Unions
Structures are used to represent a record (e.g. library).
Exercise A union is a special data type in C, which is used to
# include <stdio.h> store different data types in the same memory
void fun(int *ptr) location. comparison of the structures and union are as
{ follows:
*ptr = 30; Structure Union
} To define a structure, the To define union, the
`struct‟ keyword is used. `union‟ keyword is
int main() used
{ When a structure variable When a union variable
int y = 20; is created, the compiler is created, the
fun(&y); allocates memory for this compiler allocates
printf("%d", y); variable equal to the sum memory for that
of size of structure variable equal to the
return 0; elements maximum size of
} union element
Each structure element Individual members of
Explanation: The function fun() expects a pointer within a structure is the union share the
ptr to an integer (or an address of an integer). It assigned to unique memory allocated.
modifies the value at the address ptr. The dereference memory location.
13
Cloud IT Online Batch Programming in C -04
. More than one structure Only one member can
element can be initialized be initialized at a time
at once.
Individual members can Only one member can
be accessed at a time. be accessed at a time.
Storage Classes
A storage class defines the scope and visibility of
variables and functions in C program. The following
four types of storage classes are available:
1. Register 2. Auto 3. Static 4. Extern
5. 1+2+3+……….+100. [BPSC-SAE.-2021]
6. Write a program to reverse a string.[ICML(AP)-
2019]
14