You are on page 1of 15

Birla Institute of Technology & Science, Pilani

Second Semester 2015-2016, Computer Programming [CS F111]


Week #7
Tutorial Sheet #1 Date:___/_____/________
Name: ______________ _____________ID: ______________________ Lec Sec/Lab
Sec:______/_____

Section 1 Functions:
A function is a block of statements, which is used to perform a specific task.
Suppose you are building an application in C language and in one of your program,
you need to perform a same task more than once. So in such scenario you have two
options
a)Use the same set of statements every time you want to perform the task
b)Create a function, which would do the task, and just call it every time you need to
perform the same task.
Using option (b) is a good practice and a good programmer always uses functions
while writing codes.
Benefits of Using Functions
1.
It provides modularity to the program.
2.
Easy code Reusability. You just have to call the function by its name to use it.
3.
In case of large programs with thousands of code lines, debugging and
editing becomes easier if you use functions.
General syntax of function declaration is,
return-type function-name (parameter-list);
Like variable and an array, a function must also be declared before its called. A
function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration consist of 4 parts.
return-type
function name
parameter list
terminating semicolon
General syntax of function definition is,
return-type function-name (parameter-list)
{
function-body ;
}
The first line return-type function-name(parameter) is known as function header and
the statement within curly braces is called function body.
return-type : return type specifies the type of value(int,float,char,double) that
function is expected to return to the program calling the function.
function-name : function name specifies the name of the function. The function
name is any valid C identifier and therefore must follow the same rule of formation
as other variables in C.
parameter-list : The parameter list declares the variables that will receive the
data sent by calling program. They often referred to as formal parameters. These
parameters are also used to send values to calling program.
function-body: The function body contains the declarations and the
statement(algorithm) necessary for performing the required task. The body is
enclosed within curly braces { } and consists of three parts.
local variable declaration.
function statement that performs the tasks of the function.
a return statement that return the value evaluated by the function.

Functions and Arguments


Arguments are the values specified during the function call, for which the formal
parameters are declared in the function.

Example 1: Write a function that returns the larger of two input numbers
along with the driver code.
#include<stdio.h>
int larger(int a,int b); // function declaration
int main()
/* main is called as driver code since
it is not performing any computation*/
{
int i,j,k;
printf(enter two numbers);
scanf(%d%d,&i,*j);
k=larger(i,j);
// function call
printf("%d",k);
return 0;
}
int larger(int a,int b){
// function declaration
if(a>b)
return a;
else
return b;
}
Lets try few more examples:
Exercise 1: Write a function to find if a given number is prime or not. Function
takes number as input argument. It returns 1 if number is prime else return 0. Based
on the return value, print the appropriate
message in main function.

Exercise 2: Write a program that takes the x-y coordinates of a point in the
Cartesian plane. Write a function which takes as input the x-y coordinates and
returns the quadrant in which it lies.

Section 2 Functions: Scope of data:


A scope in any programming is a region of the program where a defined variable
can have its existence and beyond that variable it cannot be accessed. There are
three places where variables can be declared in C programming language
Inside a function or a block which is called local variables.
Outside of all functions which is called global variables.
In the definition of function parameters which are called formal parameters.
Let us understand what are local and global variables, and formal parameters.
int main () {
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
A program can have same name for local and global variables but the value of local
variable inside a function will take preference. Here is an example
#include <stdio.h>
/* global variable declaration */
int g = 20;
int main () {
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
return 0;
}
When the above code is compiled and executed, it produces the following result
value of g = 10
Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take
precedence over global variables. Following is an example
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main () {
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
/* function to add two integers */
int sum(int a, int b) {
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}

When the above code is compiled and executed, it produces the following result
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
Initializing Local and Global Variables
When a local variable is defined, it is not initialized by the system, you must
initialize it yourself. Global variables are initialized automatically by the system
when you define them as follows
Data Type Initial Default Value
int
0
char
'\0'
float
0
double
0
pointer
NULL
It is a good programming practice to initialize variables properly, otherwise your
program may produce unexpected results, because uninitialized variables will take
some garbage value already available at their memory location.
Example 3: Write a function that finds the minimum of three numbers. The function
then decrements this minimum number by one and increment other two numbers
(by one). Pass three integers as input arguments to the function and return the
decremented minimum number to main function. Print values of three integers from
within the function, before and after calling the function in main. Emphasize on
scope of variables and pass by value.

Exercise 43: Write a program for the following series. Divide the program into two
functions as follows:
(a) Write a power() function to compute 2a. This function takes variable 'a' as input
argument and
returns 2a.
(b) Write a function to compute sum of series. This function takes 'N' as input
argument and returns the
sum of the series. power() function will be called in this function. Call this function in
main().

Exercise 5: Calculate and print the value of 'i' using the following formula for
different values of x and y:
i = 2 + (y + 0.5x)
Write a program, which will produce a table of values of i, y and x, where y varies
from 1 to 6, and, for
each value of y, x varies from 5.5 to 12.5 in steps of 0.5. Write a function for
implementing the formula.
Pass value of x and y as an input argument. Function returns the value of i. Call this
function inside the
nested loops for different values of x and y.

Exercise 6: Write a function that takes a character indicating a color as an input


argument and displays the full color if it is present else prints the message that the
color is not present. Here function doesn't return anything. Emphasize on void
return type. Rainbow colors:
ROY G BIV = Red Orange Yellow Green Blue Indigo Voilet

Birla Institute of Technology & Science, Pilani


Second Semester 2015-2016, Computer Programming [CS F111]
Week #7
Tutorial Sheet #2 Date:___/_____/________
Name: ______________ _____________ID: ______________________ Lec Sec/Lab
Sec:______/_____

Section 1 Introduction to Pointers:


Pointers are variables that hold address of another variable of same data type.
Pointers are one of the most distinct and exciting features of C language. It provides
power and flexibility to the language. Although pointer may appear little confusing
and complicated in the beginning, but trust me its a powerful tool and handy to use
once its mastered.
Benefit of using pointers
Pointers are more efficient in handling Array and Structure.
Pointer allows references to function and thereby helps in passing of function as
arguments to other function.
It reduces length and the program execution time.
It allows C to support dynamic memory management.
Whenever a variable is declared, system will allocate a location to that variable in
the memory, to hold value. This location will have its own address number.
Let us assume that system has allocated memory location 80F (Hexa decimal
representation of memory address) for a variable a.
int a = 10 ;

We can access the value 10 by either using the variable name a or the address 80F.
Since the memory addresses are simply numbers they can be assigned to some
other variable. The variable that holds memory address are called pointer variables.
A pointer variable is therefore nothing but a variable that contains an address,
which is a location of another variable. Value of pointer variable will be stored in
another memory location.

Declaring and initializing a pointer variable:

datatype * identifier ;
int *a;
The meaning of the above statement is that a is a pointer variable that holds
address in which integer data is stored.
Note: a itself is not an integer
Example 1: declare a pointer variable that points to float data.
float *f;
Exercise 1: declare a pointer variable that points to character data.
Exercise 2: What is the size of memory for a, f and c pointer variables?
Unlike the variable the pointer variables also will have junk/garbage values. They
have to be initialized before using.
For example:
int a=10;
int *ptra;
ptra=&a; //This statement assigns the pointer address where a is
stored .
*ptra=20; // This statement assign 20 to the memory location pointed by
ptra
Note: & is the address operator also called as reference operator and * is
called as deference operator
Pointers and functions:
There are two ways of passing parameters to functions
1.pass by value
2.pass by reference
Example 2: Demonstrate the implementation of call by value and reference
for a program that swaps two input numbers.
pass by value
pass by reference
#include<stdio.h>
#include<stdio.h>
void swap(int num1, int num2);
void swap(int *num1, int
int main() {
*num2);
int x, y;
int main() {
printf("\nEnter two
int x, y;
numbers : ");
printf("\nEnter two
scanf("%d%d",&x,&y);
numbers : ");
printf("\nBefore Swaping x =
scanf("%d%d",&x,&y);
%d and y = %d", x, y);
printf("\nBefore Swaping x =
swap(x, y); // Function Call %d and y = %d", x, y);
- Pass By Reference
swap(&x, &y); // Function
printf("\nAfter Swaping x =
Call - Pass By Reference
%d and y = %d", x, y);
printf("\nAfter Swaping x =
return 0;
%d and y = %d", x, y);
}
return 0;
void swap(int num1, int num2) { }
int temp;
void swap(int *num1, int *num2)
temp = num1;
{
num1 = num2;
int temp;
num2 = temp;
temp = *num1;
}
*num1 = *num2;

Enter two numbers : 2 3


Before Swapping x = 2 and y = 3
After Swaping x = 2 and y = 3

*num2 = temp;
}
Enter two numbers : 2 3
Before Swapping x = 2 and y = 3
After Swaping x = 3 and y = 2

Conclusion from above example


1. When call by value is used a local copy of the variable is made in the function
and the scope those variables are within the function.
2. When call by reference is used the address of the variables in the main are sent
and the function has pointers refereeing to the sent address hence any change to
the content pointed by pointers are permanent.

Section 2 Pointer Arithmetic:


A pointer in c is an address, which is a numeric value. Therefore, you can perform
arithmetic operations on a pointer just as you can on a numeric value. There are
four arithmetic operators that can be used on pointers: ++, --, +, and
To understand pointer arithmetic, let us consider that ptr is an integer pointer which
points to the address 1000. Assuming 32-bit integers, let us perform the following
arithmetic operation on the pointer ptr++
After the above operation, the ptr will point to the location 1004 because each time
ptr is incremented, it will point to the next integer location which is 4 bytes next to
the current location. This operation will move the pointer to the next memory
location without impacting the actual value at the memory location.
The address computation is as follows when ptr++ is evaluated:
ptr = ptr + 1 * sizeof(int)
= 1000 + 1 * 4 = 1004
If ptr points to a character whose address is 1000, then the above operation will
point to the location 1001 because the next character will be available at 1001.
Example 3: Incrementing and decrementing a Pointer
int arr[] = {10, 100, 1000};
int *ptr1,*ptr2;
ptr1 = arr; /*here arr is an array and implicilty is a pointer
hence & is ignored in case of arrays */
ptr1++; /*assuming that the starting address of the array is 1000
this step results in 1004 hence ptr now points to 1004*/
ptr1--; /*since the pointer was pointing to 1004 this step results
in 1000 hence ptr now points to 1000*/
ptr2 = ptr1; //ptr2 will now point to 1000 memory location
if(ptr1==ptr2) //Comparing two pointers
printf(both pointers are pointing to the same location);

Section 3: Pointers and arrays


Arrays are closely related to pointers in C programming but the important difference
between them is that, a pointer variable can take different addresses as value
whereas, in case of array it is fixed. This is demonstrated by the following example:
Example 4:
#include <stdio.h>
int main(){
char c[4];
int i;
for(i=0;i<4;++i){
printf("Address of c[%d]=%x\n",i,&c[i]);

}
return 0;
}
Address of c[0]=28ff44
Address of c[1]=28ff45
Address of c[2]=28ff46
Address of c[3]=28ff47
Notice, that there is equal difference (difference of 1 byte) between any two
consecutive elements of array.
Note: You may get different address of an array.
Relation between Arrays and Pointers
Consider and array:
int arr[4];
Relation between arrays and pointers
In arrays of C programming, name of the array always points to the first element of
an array. Here, address of first element of an array is &arr[0]. Also, arr represents
the address of the pointer where it is pointing. Hence, &arr[0] is equivalent to arr.
Also, value inside the address &arr[0] and address arr are equal. Value in address
&arr[0] is arr[0] and value in address arr is *arr. Hence, arr[0] is equivalent to *arr.
Similarly,
&a[1] is equivalent
&a[2] is equivalent
&a[3] is equivalent
.
.
&a[i] is equivalent
In C, you can declare an

to (a+1)
to (a+2)
to (a+1)

AND, a[1] is equivalent to *(a+1).


AND, a[2] is equivalent to *(a+2).
AND, a[3] is equivalent to *(a+3).

to (a+i) AND, a[i] is equivalent to *(a+i).


array and can use pointer to alter the data of an array.

Example 5: Write a C program to find the sum of six numbers with arrays
and pointers
//Program to find the sum of six numbers with arrays and pointers.
#include <stdio.h>
int main(){
int i,class[6],sum=0;
printf("Enter 6 numbers:\n");
for(i=0;i<6;++i){
scanf("%d",(class+i)); // (class+i) is equivalent to &class[i]
sum += *(class+i); // *(class+i) is equivalent to class[i]
}
printf("Sum=%d",sum);
return 0;
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum=21

Example 6: What is the output of the statements shown?


#include<stdio.h>
int main()
{
int x[3][5]={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}},
*n=&x[0][0];
printf("%d\n",*(*x));
printf("%d\n",*(*(x+2)+1));
printf("%d\n",*(*x+2)+5);
printf("%d\n",(*(*(x+1))));
printf("%d\n",*(*(x+1)+3));
printf("%d\n",*(n+2));
printf("%d\n",(*(n+3)+1));
printf("%d\n",*(n+5)+1);
printf("%d\n",++*n);
}
*(*x) = x has the base address hence it is *(*(x+0)+0) = 1
*(*(x+2)+1)
= *(x+2) gets the address of the second row
+1
means having the second row go to the second element = 12
*(*x+2)+5)
= (*x+2) *x=base address of row 0 (*x+2*size) gives
address of 0th row 2 nd col , *(*x+2) gives values at that address
that is 3 *(*x+2)+5) = 3 + 5 = 8
(*(*(x+1))))
= *(x+1) = address of row 1 *(row1) = 6
*(*(x)+2)+1)
= *(x) = *(x+0) = *((1+2)+1) = 4
*(*(x+1)+3) = x[1] [3] = 9
*(n+2) = *(base address + 2 * size of int) = 3
*(n+5)+1 = *(base address + 2 * size of int) = 6 + 1=7
++ *n = *n=1 hence ++ gives 2
Exercise: Consider two arrays: x-coor[] and y-coor[]. The ith location of the two
arrays stores the x
and y coordinates of a point. For example, x-coor[4] and y-coor[4] stores the x and y
coordinates of forth
point.
a) Pass these two arrays to a function which prints the quadrant in which each point
lies. Emphasis is on passing array to a function.
b) Pass these two arrays to a function. The function stores the quadrant in which
each point lies in another array (which is also passed to the function). It then prints
the quadrant in main function. Emphasis is on returning array from a function.

Exercise: Modularize the following program into multiple functions. Consider a list
of prices of books represented as one dimensional array. Traverse the list and
modify the prices according to the following conditions:
(i) if price > 250, offer discount of 10%. Update the price with respect to discount.
(ii) if price > 500, offer discount of 25%. Update the price w.r.t discount.
Modularize it into following functions.
(i) readList(): Populate prices of the items.
(ii) printList(): Prints the price list.
(iii) modifyList(): Modify the prices in the list according to the conditions given
above.
Identify input arguments and return types for all the functions. Also write main
function where the functions are called.

Exercise: Implement insertion sort and bubble sort. First modularize the problem
into separate
functions by identifying arguments and return types. Now implement any one
sorting technique.

You might also like