C Programming: Functions and Pointers
C Programming: Functions and Pointers
INTRODUCTION TO FUNCTIONS
Structured programming is a programming technique in which a larger program is divided
into smaller subprograms. These subprograms are easy to understand, easy to implement. The
structured programming enables code reusability. Code reusability is a method of writing
code once and using it many times.
In C, the structured programming can be designed using functions concept. Using functions
concept, we can divide larger program into smaller subprograms and these subprograms are
implemented individually. Program is divided into multiple functions.
Programming in C CSE@AVCCE
UNIT III
Functions
A function is a block of statements that together perform a specific task.
Every C program has at least one function, which is main().
A function can also be referred as a method or a sub-routine or a procedure, etc.
Uses of C Functions
Using functions, larger program can be divided into smaller modules.
Modular programming is implemented using functions.
Main advantages of C functions are, re-usability, dividing a big task into small pieces to
achieve the functionality and to improve understandability.
It is easy to track when the program is divided into functions.
Once a function is created it can be used many times (code reusability).
Every function in C has the following.
i. Function Declaration (Function Prototype)
ii. Function Definition
iii. Function Call
Function Declaration
The function declaration informs the compiler about function name, datatype of the
return value and number of arguments.
The function declaration is also called as function prototype.
The function declaration is performed before main function or inside main function or
inside any other function.
Syntax:
returnType functionName(parameters);
returnType specifies the datatype of the value which is sent as a return value from the
function definiton.
functionName is a user defined name used to identify the function uniquely.
parametersList is the data values that are sent to the function definition.
Example:
//function name = display, receives a character as argument and returns nothing
void display(char);
//function name = sum, receives two integers as argument and returns an integer
int sum(int, int);
Programming in C CSE@AVCCE
UNIT III
Function Definition
The function definition provides the actual code of that function. The function
definition is also known as body of the function.
The actual instructions of a function are written inside the braces "{ }".
The function definition is performed before main function or after main function.
Syntax:
returnType functionName(parameters)
{
//Function body
}
Function body is the collection of statements.
Example:
int sum (int x, int y)
{
// Function body has 2 statements
int s = x+y;
return s;
}
Function Call
Function call statement calls the function by matching its name and arguments.
A function call can be made by using function name and providing the required
parameters.
Syntax:
functionName (parameters);
or
variable = functionName(parameters);
Example:
display(a);
or
s = sum(x,y);
Programming in C CSE@AVCCE
UNIT III
Programming in C CSE@AVCCE
UNIT III
In the concept of functions, the function call is known as "Calling Function" and the
function definition is known as "Called Function".
When we make a function call, the execution control jumps from calling function to called
function. After executing the called function, the execution control comes back to calling
function from called function.
The data values transferred from calling function to called function are called as Parameters
and the data value transferred from called function to calling function is called Return value.
Programming in C CSE@AVCCE
UNIT III
FUNCTION PROTOTYPES
Based on the data flow between the calling function and called function, the functions are
classified.
1. Functions with no arguments and no return value.
2. Functions with no arguments and with return value.
3. Functions with arguments and no return value.
4. Functions with arguments and with return value.
Classification of Functions
1. Functions with no arguments and no return value
In this type of functions there is no data transfer between calling function and called
function.
The execution control jumps from calling function to called function and executes
called function, and finally comes back to the calling function.
Programming in C CSE@AVCCE
UNIT III
Program
/* C program to explain functions with no arguments and no return value */
#include <stdio.h>
void main()
{
void addition(); // function declaration
addition(); // function call
}
void addition() // function definition
{
int num1, num2;
printf("Enter any two integer numbers : ");
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2);
}
Input:
Enter any two integer numbers: 20 30
Output:
Sum = 50
2. Functions with no arguments and with return value
In this type of functions there is no data transfer from calling function to called
function (parameters) but there is data transfer from called function to calling function
(return value).
The execution control jumps from calling function to called function and executes
called function, and finally comes back to the calling function along with a return
value.
Programming in C CSE@AVCCE
UNIT III
Programming in C CSE@AVCCE
UNIT III
The execution control jumps from calling function to called function along with the
parameters and executes called function, and finally comes back to the calling
function.
Programming in C CSE@AVCCE
UNIT III
The execution control jumps from calling function to called function along with
parameters and executes called function, and finally comes back to the calling
function along with a return value.
Programming in C CSE@AVCCE
UNIT III
Programming in C CSE@AVCCE
UNIT III
Programming in C CSE@AVCCE
UNIT III
#include<stdio.h>
void main()
{
int num1, num2;
void swap (int, int); // function declaration
num1 = 10;
num2 = 20;
printf("\nBefore swap: num1= %d, num2 = %d",num1, num2);
swap(num1, num2); // calling function
printf("\n After swap:num1 =%d \n num2 = %d",num1, num2);
}
void swap(int a, int b) // called function
{
int temp;
temp = a ;
a = b;
b = temp;
}
Output:
Before Swap: num1 = 10, num2 = 20
After Swap: num1 = 10, num2 = 20
Here, num1 and num2 are called actual parameters, a and b are called formal parameters.
num1 is copied to a and num2 is copied to b. Changes makes on a and b have no effect on
num1 and num2.
2. Call by Reference
In Call by Reference parameter passing method, the address of the memory location
address is copied to formal parameters. The address of the actual parameters is passed
to the called function and is received by the formal parameters (pointers).
Hence changes made on the formal parameters have effect on the actual parameters
also.
Programming in C CSE@AVCCE
UNIT III
Program
/* C program to swap two numbers using call by reference */
#include <stdio.h>
void main()
{
int num1, num2 ;
void swap (int*,int*); // function declaration
num1 10;
num2 = 20;
printf("\nBefore swap: num1=%d, num2 = %d", num1, num2
swap (&num1, &num2); // calling function
printf("\nAfter swap: num1= %d, num2 = %d", num1, num2);
}
void swap(int *a, int *b) // called function
{
int temp;
temp = *a ;
*a = *b;
*b = temp;
}
Output:
Before swap: num1 = 10, num2 = 20
After swap: num1 = 20, num2 = 10
Here, the addresses num1 and num2 are copied to a and b. Hence, changes made on the
pointer variables a and b have effect on the actual parameters too.
Nesting of Functions
A function calling another function is known as a nested function.
Programming in C CSE@AVCCE
UNIT III
Example
/* one Function calling another Function in a C program*/
void message(); //Function prototype
void say(); //Function prototype
void main()
{
message(); //Function call
}
void message() // Function Definition
{
say();
printf("Hello World");
}
void say()
{
printf("This will be executed first\n");
}
Output:
This will be executed first
Hello World
BUILT-IN FUNCTIONS
The standard library functions are built-in functions in C programming to handle tasks such
as mathematical computations, I/O processing, string handling etc. The various built-in
functions along with the header files are displayed in the following table.
Standard Functions
Table - Header files and standard functions
Header File Purpose Example
stdio.h Provides functions to perform
printf(), scanf()
standard I/O operations
conio.h Provides functions to perform console
clrscr(), getch()
I/O operations
string.h Provides functions to handle string
strlen(), strcpy()
data values
stdlib.h Provides functions to perform general
calloc(), malloc()
functions
math.h Provides functions to perform sqrt(), pow()
Programming in C CSE@AVCCE
UNIT III
mathematical operations
time.h Provides functions to perform
time(), localtime()
operations on time and date
graphics.h Provides functions to draw graphics circle(), rectangle()
Math Functions
"math.h" header file supports all the mathematical related functions in C language. All the
mathematical functions used in C language are given below
Table - Math Functions
Function Description Example Output
abs() Returns the positive absolute value of an abs(200) 200
integer. abs(-400) 400
floor() Returns the nearest integer. floor(5.1) 5
floor(5.9) 5
floor(-5.4) -6
round() Returns the nearest integer value round(5.4) 5
round(5.9) 6
round(-5.4) 5
ceil() Returns nearest integer value which is greater ceil(5.4) 6
than or equal to the value passed ceil(5.9) 6
sin() Returns sine value. sin(0.314) 0.3088
cos() Returns cosine value. cos(0.314) 0.9511
tan() Returns tangent value. tan(0.314) 0.3247
sinh() Returns hyperbolic sine value. sinh(0.25) 0.2526
cosh() Returns hyperbolic cosine value. cosh(0.25) 1.0314
tanh() Returns hyperbolic tangent value. tanh(0.25) 0.2449
exp() Returns the exponential "e" value exp(6.25) 518.01
log() Returns natural logarithm value. log(6.25) 1.8326
log10() Returns base 10 logarithm values. log10(6.25) 0.7959
sqrt() Returns the square root of a number. sqrt(16) 4
sqrt(2) 1.141
pow() Returns the power of a number. pow(2,4) 16
pow(5,3) 125
trunc() Truncates the decimal value from floating trunc(16.99) 16
point value and return integer value. trunc(20.1) 20
Programming in C CSE@AVCCE
UNIT III
String Functions
"string.h" header file supports all the string functions in C language. All the string functions
are given below.
Table - String Functions
Function Description Example Output
strcat() Concatenates s2 at the end of s1 = "World" World of C
sl s2 = "of C"
strcat (s1,s2)
printf("%s",s1)
strncat() Appends a portion of string to strncat (s1,s2,2) World of
another printf("%s",s1)
strcpy() Copies s2 into sl strcpy (s1,s2 ) of C
printf("%s",s1)
strncpy() Copies given number of strncpy (s1,s2, 2) of
printf("%s",s1)
strlen() Gives the length of s1 c = strlen(s1) 5
printf(“%d”, c)
strcmp() Returns 0 if s1 is same as s2. i= strcmp(s1,"World")
Returns <0 if s1<s2. printf("%d",i) 0
Returns >0 if s1>s2 i = strcmp(s1,s2)
printf("%d",i) 1
i = strcmp(s2,s1)
printf("%d",i) -1
strcmpi() Same as strcmp() function. But i= strcmp(s1,"WORLD") 0
this function negotiates case. printf("%d",i)
strchr() Returns pointer to first i=strchr(s1,'o') 1
occurrence of char in str1 printf("%d",i)
strrchr() Returns the last occurrence of s1="World of C” 6
given character in a string i = ,strchr(s1,'o')
printf("%d”, i)
strstr() Returns pointer to first s1="World of C” 2
occurrence of s2 in sl i = ,strchr(s1,'o')
printf("%d”, i)
strrstr() Returns pointer to last s1= "Test to Test you " 8
occurrence of s2 in sl i= strstr(s1,"Test")
printf("%d",i)
strdup() Duplicates the string s1 = "Hello"
s2 = strdup(s1)
printf("%s",s2)
strlwr() Converts string to lowercase s1 = "Hello" hello
printf("%s",strlwr(s1))
Programming in C CSE@AVCCE
UNIT III
The recursive functions should be used very carefully because; when a function called by
itself it enters into infinite loop. Define the condition to exit from the function call so that the
recursive function gets terminated.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.
Programming in C CSE@AVCCE
UNIT III
Program
/* C Program to find Factorial of a given number using
Recursion */
#include <stdio.h>
int fact(int i)
{
if(i <= 1)
{
return 1;
}
return i * fact(i-1);
}
void main()
{
int i = 5;
printf("Factorial = %d", fact(i));
}
Output:
Factorial = 120
Program
/* C Program to generate Fibonacci Series using Recursion */
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,...
#include <stdio.h>
int fibonacci(int i)
{
if(i == 0)
return 0;
if(i == 1)
return 1;
return fibonacci(i-1) + fibonacci(i-2);
}
void main()
{
int i;
for (i= 0; i<10; i++)
printf("%d\t", fibonacci(i));
}
Output:
0 1 1 2 3 5 8 13 21 34
Programming in C CSE@AVCCE
UNIT III
Programming in C CSE@AVCCE
UNIT III
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <stdlib.h>
void main()
{
int n, x1;
float acc, term, den, x, sinx=0, sinval;
clrscr();
printf("Enter the value of x (in degrees)\n");
scanf("%f",&x);
x1 = x;
/* Converting degrees to radians*/
x = x* (3.142/180.0);
sinval sin(x);
printf("Enter the accuary for the result\n");
scanf("%f", &acc);
term = X;
sinx = term;
n = 1;
do
{
den = 2*n* (2*n+1);
term = -term * x * x / den;
sinx sinx + term;
n = n + 1;
}
while (acc<= fabs (sinval - sinx));
printf("Sum of the sine series %f\n", sinx);
printf("Using Library function sin(%d)=%f\n",x1,sin(x));
getch();
}
Input:
Enter the value of x (in degrees)
45
Enter the accuary for the result
0.00001
Output:
Sum of the sine series =0.707178
Using Library function sin (45)= 0.707179
Programming in C CSE@AVCCE
UNIT III
Program
Scientific Calculator using Built-in functions.
/* C Program Scientific Calculator using Built-in functions */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main(void)
{
int choice, i, a, b;
float x, y, result;
clrscr();
do
{
printf("\nSelect your operation (0 to exit):\n");
printf("[Link] \n [Link] \n
[Link] \n 4. Division \n”);
printf("5. Square root\n 6. X ^ Y\n7. X^2 \n 8. X^3
\n”);
printf("Choice: ");
scanf("%d", &choice);
if(choice == 0)
exit(0);
switch (choice)
{
case 1:
printf("Enter X: ");
scanf("%f", &x);
printf("\nEnter Y: ");
scanf("%f", &y);
result = x + y;
printf("\nResult: %f", result);
break;
case 2:
printf("Enter X: ");
scanf("%f", &x);
printf("\nEnter Y: ");
scanf("%f", &y);
result = x - y;
printf("\nResult: %f", result);
break;
case 3:
printf("Enter X: ");
scanf("%f", &x);
printf("\nEnter Y: ");
Programming in C CSE@AVCCE
UNIT III
scanf("%f", &y);
result = x * y;
printf("\nResult: %f", result);
break;
case 4:
printf("Enter X: ");
scanf("%f", &x);
printf("\nEnter Y: ");
scanf("%f", &y);
result = x / y;
printf("\nResult: %f", result);
break;
case 5:
printf("Enter X: ");
scanf("%f", &x);
result = sqrt(x);
printf("\nResult: %f", result);
break;
case 6:
printf("Enter X: ");
scanf("%f", &x);
printf("\nEnter Y: ");
scanf("%f", &y);
result = pow (x, y);
printf("\nResult: %f", result);
break;
case 7:
printf("Enter X: ");
scanf("%f", &x);
result = pow (x, 2);
printf("\nResult: %f", result);
break;
case 8:
printf("Enter X: ");
scanf("%f", &x);
result = pow (x, 3);
printf("\nResult: %f", result);
break;
default:
printf("\nInvalid Choice!");
}
}while (choice);
getch();
}
Programming in C CSE@AVCCE
UNIT III
Input:
Select your operation (0 to exit):
1. Addition
2. Subtraction
3. Multiplication
4. Division
[Link] root
6.X^Y
7.X^2
8.X^3
Output:
Choice: 1
Enter X:5
Enter Y:4
Result:9
Program
Binary Search using Recursive functions.
Programming in C CSE@AVCCE
UNIT III
Programming in C CSE@AVCCE
UNIT III
POINTERS
Pointers are the powerful feature of C that differentiates it from other popular programming
languages like: Java and Python.
In C programming language, we use normal variables to store data values. When we declare a
variable, the compiler allocates required memory with specified name. We use a special type
of variable called pointer to store the address of another variable with same data type.
Pointer Operators
Pointer is a special type of variable used to store the memory location address of another
variable.
Programming in C CSE@AVCCE
UNIT III
Programming in C CSE@AVCCE
UNIT III
Program
/* C Program to explain Reference operator (&) and Dereference operator (*) */
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, *ptr ;
clrscr();
ptr = &a ;
printf("Address of variable a = %u\n", ptr);
printf("Value of variable a =%d\n",*ptr);
printf("Address of variáble ptr = %u\n", &ptr);
}
Output:
Address of variable a = 65524
Value of variable a = 10
Address of variable ptr = 65526
In the above example program, variable a is a normal variable and variable ptr is a pointer
variable. Address of variable a is stored in pointer variable ptr. Here ptr is used to access the
address of variable a and *ptr is used to access the value of variable a.
Programming in C CSE@AVCCE
UNIT III
Program
/* C program to explain handling of pointers */
#include <stdio.h>
void main()
{
int *pc;
int c;
c=22;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
pc=&c;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc: %d\n\n", *pc);
C=11;
printf("Address of pointer pc:%u\n",pc);
printf("Content of pointer pc: %d\n\n", *pc);
*pc=2;
printf("Address of c:%u\n",&c);
printf("Value of c:%d\n\n",c);
}
Output
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
Content of pointer pc: 22
Address of pointer pc: 2686784
Content of pointer pc: 11
Address of c: 2686784
Value of c: 2
Chain of Pointers
A pointer to a pointer is a form of multiple in-directions, or a chain of pointers. Normally, a
pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains
the actual value as shown below.
Programming in C CSE@AVCCE
UNIT III
Programming in C CSE@AVCCE
UNIT III
Pointer Arithmetic
Pointer variables are used to store address of variables. Address of any variable is an
unsigned integer value i.e., it is a numerical value. Arithmetic operations can be performed on
pointer values. But the result depends on the amount of memory required by the variable to
which the pointer is pointing.
The following arithmetic operations are performed on pointers.
1. Adding a number to pointer.
2. Subtracting a number form a pointer.
3. Incrementing a pointer.
4. Decrementing a pointer.
5. Subtracting two pointers.
Programming in C CSE@AVCCE
UNIT III
3. Incrementing a Pointer
"Incrementing a pointer increases its value by the number of bytes of its data type".
Let ptr be an integer pointer which points to the memory location 5000 and size of an integer
variable is 32-bit(4 bytes). Now, when we increment pointer ptr
ptr++;
will point to memory location 5004 because it will jump to the next integer location which is
4 bytes next to the current location. Incrementing a pointer is not same as incrementing an
integer value.
On incrementing, a pointer will point to the memory location after skipping N bytes, where N
is the size of the data type (in this case it is 4).A character (1 bytes) pointer is incremented by
1 bytes.
ptr + (sizeof(pointer_data_type))
4. Decrementing a Pointer
"Decrementing a pointer increases its value by the number of bytes of its data type"
ptr--;
ptr will point to 4996.
ptr - (sizeof(pointer_data_type))
5. Subtracting Pointers
The difference between two pointer returns indicates. It gives the total number of elements
between two pointers. If an integer pointer 'ptrl' points at memory location 10000 and
integer pointer 'ptr2' points at memory location 10008, the result of ptr2 - ptr1 is 2.
Scale Factor
We increment a pointer, its value is increased by the length of the data type that it points to.
This length is called the scale factor
The length of various data types are as follows:
character 1 byte
integers 2 byte
floats 4 bytes
long integers 4 bytes
doubles 8 bytes
Programming in C CSE@AVCCE
UNIT III
Program
/* program to explain Pointer Arithmetic Operations */
#include<stdio.h>
void main()
{
intint_var = 10, *int_ptr;
char char_var = 'A', *char_ptr;
float float_val = 4.65, *float_ptr;
/* Initialize pointers */
int_ptr = &int_var;
char_ptr = &char_var;
float_ptr = &float_val;
printf("Address of int_var = %u\n", int_ptr);
printf("Address of char_var = %u\n", char_ptr);
printf("Address of float_var = %u\n\n", float_ptr);
/* Incrementing pointers */
int_ptr++;
char_ptr++;
float_ptr++;
printf("Afterincrement address in int_ptr=%u\n",int_ptr);
printf("After increment address in char_ptr=%u\n",
char_ptr);
printf("After increment address in float_ptr= %u\n\n",
float_ptr);
/* Adding 2 to pointers */
int_ptr = int_ptr + 2;
char_ptr = char_ptr + 2;
float_ptr = float_ptr + 2;
printf("After addition address in int_ptr = %u\n",
int_ptr);
printf("After addition address in char_ptr = %u\n",
char_ptr);
printf("After addition address in float_ptr = %u\n\n",
float_ptr);
}
Output:
Address of int_var = 2293300
Address of char_var = 2293299
Address of float_var = 2293292
Programming in C CSE@AVCCE
UNIT III
Programming in C CSE@AVCCE
UNIT III
Program
/* Program to print the value and address of the element. */
#include < stdio. h >
void main ( )
{
int a[5] ={l0,20,30,40,50};
int b;
for (b=0;b<5;b++)
{
printf("The value of a[%d]=%d",b,a[b]);
printf("Address of a[%d]=%u",b,&a[b]);
}
}
Output:
The value of a[0] =10 Address of a[0]=4000
The value of a[1] =20 Address of a[1]=4002
The value of a[2] =30 Address of a[2]=4004
The value of a[3] =40 Address of a[3]=4006
The value of a[4] =50 Address of a[4]=4008
Program
#include < stdio. h >
void main()
{
int *p, sum, i;
static int x[5] = {10,20,30,40,50};
i = 0; p = x; sum = 0;
printf(“Element \t Value \t Address\n”);
while(i<5)
{
printf(“x[%d] \t %d \t %u”,i,*p,p);
sum = sum + *p;
i++;
p++;
}
printf(“\n Sum = %d\n”,sum);
printf(“\n &x[0] = %u \n”,&x[0]);
printf(“\n p = %u\n”,p);
}
Output
Element Value Address
x[0] 10 4000
x[1] 20 4002
Programming in C CSE@AVCCE
UNIT III
x[2] 30 4004
x[3] 40 4006
x[4] 50 4008
sum = 150
&x[0] = 4000
p = 4010
Program
/* Program to add the sum of number using pointer*/
#include <stdio.h>
void main ()
{
int b, total;
int a[5];
int *c ;
for(b=0;b<5;b++)
{
printf("Enter the number %d", b + 1);
scanf ("%d",&a[b]);
}
c = a;
for (b = 0;b<5; b++)
{
total = total + *c;
c = c + 1;
}
printf("\n total=%d", total);
}
Output
Enter the number 1 10
Enter the number 2 20
Enter the number 3 30
Enter the number 4 40
Enter the number 5 50
Total = 150
Program
/* Program to sort a given number using pointer*/
#include < stdio.b >
main ( )
{
int j,k;
int arr[5];
Programming in C CSE@AVCCE
UNIT III
int *a;
a = arr;
for (j=0;j<5;j+ +)
{
printf("Enter the number %d= “, j+ 1);
scanf ("%d", &arr[i]);
}
printf ("\n Before sorting");
for(j =0;j<5;j+ +)
printf("%d",arr[j]);
a=arr;
for (j=0;j<5;j++)
{
for (k=0;k< 5- j -l; k+ +)
{
if (*(arr+k) > *(arr+k+1))
swap(arr+k, arr+k+1);
}
}
printf("After sorting");
for (j=0; j<5; j+ +)
printf ("%d", arr[j]);;
}
swap (b,c)
{
int *b, *c;
int temp;
temp=*b;
*b=*c;
*c=temp;
}
Output
Enter the number=8
Enter the number=5
Enter the number=7
Enter the number=4
Enter the number=6
Before sorting
85746
After sorting
45678
Programming in C CSE@AVCCE
UNIT III
Where
Data-type - refers to the data type of the array.
Pointer-variable - is the name of the pointer variable.
Array - is the corresponding array name.
Expression 1, Expression 2 - are positive-integer expression that indicate the maximum
number of arrays elements associated with each subscript.
If 'a' is a two dimensional integer array having 10 rows and 20 columns.
'a' can be declared as
pointer int (*a)[20]; rather than
array int a[l0][20];
In first declaration 'a' is defined to be a group of contiguous, one dimensional, 20-elements
integer array, 'a' points to the first 20 element array which is actually first row (0th row) of
the original two-dimensional array. Similarly (2 +1) points to the second 20 elements array.
i.e., second row (1th row) and so on.
Pointers to two-dimensional arrays are denoted as follows:
Let us take p as a pointer variable ,
p → pointer to first row
p+i → pointer the ith row
*(p+i) → pointer to first element in the ith row
*(p+i)+j → pointer to jth element in the ith row
*(*(p+i)+j) → Value stored in the cell( i , j) (ith row and jth column);
For example, In the array x, the item in 2 row, 5 column can be accessed using the
expression. *(*(x+2)+5)
Programming in C CSE@AVCCE
UNIT III
Program
/* Program to print the values and address of the array
elements */
#include<stdio.h>
main()
{
int arr[4][2]={{5,100}, {10,200}, {15,300}, {20,400}};
int a,b;
for(a=0;a<4;a++)
{
printf("Address of %d array=%u" a, &arr[a]);
for(b=0; b<2; b++)
printf("value = %d",arr[a][b]);
}
}
Output
Address of 0 array = 4000
value= 5
value= l00
Address of 1 array = 4004
value=10 value =200
Address of 2 array = 4008 value =15
value =300
Address of 3 array = 4012 value =20
value =400
Programming in C CSE@AVCCE
UNIT III
C \0 C + + \0` J a v a \0
Fig. - Pointers and strings
Program
/* C program to explain Pointers and Strings */
#include <stdio.h>
void main()
{
int i;
char *lang[4]= {"C", "C++", "Java"};
for (i = 0; i < 3; i++)
Programming in C CSE@AVCCE
UNIT III
printf("%s\n", lang[i]);
}
Output:
C
C++
Java
In the above program, a pointer array of character data type is declared and strings like
"C","C++","Java" are initialized to the pointer array (*lang[]). Note that the size of the array
is not declared as it is of character pointer type.
Programming in C CSE@AVCCE
UNIT III
Array of Pointers
One important use of pointers is in handling of a table of strings. Consider the following
array of strings:
char lang[3][20] = {C,C++, Java}
It means that the lang is a array containing 3 names, each with a maximum length of 20
characters (including null character). The total space needed for the lang array is 60 bytes.
Instead of making each row a fixed number of characters, make it a pointer to a string of
varying length.
char *lang[3] = {C, C++, Java}
Declares lang to an array of 3 pointers.
This declaration needs only 11 bytes.
Programming in C CSE@AVCCE
UNIT III
Alteration to the value is not accepted inside the function in calling program but change is
locally available in the function.
Programming in C CSE@AVCCE
UNIT III
Programming in C CSE@AVCCE
UNIT III
ADDITIONAL PROGRAMS
Program
/* C Program to Compute the Sum of Digits of a given Integer*/
Sum of Digits in a Integer
435 = 4 + 3 + 5 = 12
#include <stdio.h>
void main()
{
int num, no, digit, sum = 0;
printf("Enter the number \n");
scanf("%d", &num);
no = num;
while (num> 0)
{
digit = num % 10;
sum = sum + digit;
num /= 10;
}
printf("Given number = %d\n", no);
printf("Sum of the digits of %d = %d\n", sum);
}
Input:
Enter the number
167
Output:
Programming in C CSE@AVCCE
UNIT III
Program
/* C Program to Check if a Given String is Palindrome */
Palindrome: A string is said to be palindrome if reverse are of the string is same as string.
Examples: "dad", "radar", "madam" etc.*/
#include <stdio.h>
#include <string.h>
void main()
{
char string1[20];
int i, length;
int flag = 0;
printf("Enter a string: \n");
scanf("%s", string1);
length = strlen(string1);
for(i=0; i < length ;i++)
{
if(string[i] != string1[length-i-1])
{
flag 1;
break;
}
}
if(flag)
printf("%s is not a palindrome\n", string1);
else
printf("%s is a palindrome\n", string1);
}
Input:
Enter a string: dad
Output:
dad is a palindrome
Program
/* C program for using recursion, find the sum of the series:
Programming in C CSE@AVCCE
UNIT III
#include <stdio.h>
int power(int,int);
int fact(int);
float sum (int,int);
void main()
{
int x,n;
float f;
printf("Enter the 'x' value: \n");
scanf("%d",&x);
printf("Enter the 'n' value: \n");
scanf("%d",&n);
f=sum(x, n) ;
printf("\n sum of the series: %f\n", f);
}
int power (intx,int i)
{
int p;
if (i==0)
p=1;
else
p=power(x,i-1)*x;
return p;
}
int fact(int x)
{
int f;
if(x==0)
f=1;
else
f=fact (x-1) *x;
return f;
}
float sum(intx,int n)
{
int i;
float s,s1=0, s2, s3;
for(i=0; i<n; i++)
{
Programming in C CSE@AVCCE
UNIT III
s2=power(x,i);
s3=fact(n);
s=s2/s3;
s1=s1+s;
}
return s1;
}
Input:
Enter the 'x' value: 2
Enter the 'n' value: 3
Output:
sum of the series: 1.166667
Program
/* C Program to perform sum = 1+ (1+2) + (1+2+3)+...+ (1+2...+n)*/
#include <stdio.h>
void main()
{
int n, sum, i, j;
printf("Please enter an integer, n =\n ");
scanf("%d", &n);
for(i=1;i<n;i++)
for(j=1;j<=i; j++)
sum = sum + n;
printf("sum = %d\n", sum);
}
Input:
Please enter an integer, n =2
Output:
sum = 4
Program
/* C Program to Compute the Sum of the series */
#include<stdio.h>
void main()
{
Programming in C CSE@AVCCE
UNIT III
int n,i;
int sum=0;
printf("Enter the n i.e. max values of series: \n");
scanf("%d",&n);
Programming in C CSE@AVCCE
UNIT III
Program
/* C Program to Compute the Sum of the series */
Sum of the series:1^2 +3^2 +5^2+…..+n^2.
#include<stdio.h>
void main()
{
int i,n, sum=0;
printf("1^2+3^2+5^2+.....+n^2");
printf("Enter value of n:\n");
scanf("%d",&n);
for(i=1;i<n; i+=2)
sum = sum + (i*i);
printf("Sum of the series : %d\n", sum);
}
Input:
Enter value of n: 2
Output:
Sum of the series : 5
Program
/* C Program to Compute the Sum of the series*/
Sum of the series: 1 + 3 + 5 +...n
#include <stdio.h>
void main()
{
int i,n, sum=0;
printf("1 + 3 + 5 ++ n");
printf("Enter value of n:\n");
scanf("%d",&n);
for(i=1;i<=n;i+=2)
Programming in C CSE@AVCCE
UNIT III
sum = sum + i;
printf("Sum of the series :%d\n", sum);
}
Input:
Enter value of n: 9
Output:
Sum of the series : 165
Program
/*C Program to find Factorial of a given number using Iteration */
#include <stdio.h>
void main()
{
int i,n;
printf(“Enter n Value:”);
scanf(“%d”, &n);
for (i =1; i < n; i++)
fact = fact * i
printf("Factorial Execution: = %d\n", fact);
}
Input:
Enter n Value: 5
Output:
Factorial = 120
Program
/* C Program to find largest and smallest element in an array using functions*/
#include <stdio.h>
void main()
{
int arr[30], size, largest,i;
printf("Enter the size of the array :\n ");
scanf("%d", &size);
printf("Enter the numbers:\n");
for(i=0; i<size; i++)
scanf("%d",&arr[i]);
largest = find_largest(arr, size);
printf("\nThe largest element is: %d\n", largest);
Programming in C CSE@AVCCE
UNIT III
Programming in C CSE@AVCCE