0% found this document useful (0 votes)
3 views79 pages

AR23 REC IP Unit-IV

The document outlines the syllabus for an Introduction to Programming course at Raghu Engineering College, focusing on functions, recursion, strings, and command line arguments. It explains the concept of functions in C, including their types (library and user-defined), definitions, declarations, and calls, as well as the categories of functions based on arguments and return values. Additionally, it covers parameter passing methods, specifically call by value and call by reference.

Uploaded by

vgfacts07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views79 pages

AR23 REC IP Unit-IV

The document outlines the syllabus for an Introduction to Programming course at Raghu Engineering College, focusing on functions, recursion, strings, and command line arguments. It explains the concept of functions in C, including their types (library and user-defined), definitions, declarations, and calls, as well as the categories of functions based on arguments and return values. Additionally, it covers parameter passing methods, specifically call by value and call by reference.

Uploaded by

vgfacts07
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

RAGHU

ENGINEERING COLLEGE
(AUTONOMOUS | VISAKHAPATNAM)

AR23 I B.Tech I Semester


INTRODUCTION TO PROGRAMMING
UNIT-IV 1
Syllabus
Functions, Recursion, Strings, Command Line Arguments

Introduction to Function: Declaration, Function Definition,


Function Call, Categories of Functions, Passing Parameters to
Functions as call by value, call by reference, Arrays as Function
Arguments, Pointers as Function Arguments, Scope of Variables,
Variable Storage Classes, Recursion.
Strings: String Fundamentals, String Processing with and without
Library Functions, Pointers and Strings,
Command Line Arguments.
Function:
• A function is a self-contained block of code(subprogram)that is meant to do
some specific, well-defined task.
• A program consists of one or more functions. If a program has only one function
then it must be the main( ) function.
Advantages Of Using Functions:
1) Generally a difficult problem is divided into subproblems and then solved. This
divide and conquer technique is implemented in C through functions. A program
can be divided into functions, each of which performs some specific task.
2) When some specific code is to be used more than once and at different places in
the program the use of functions avoids repetition of that code(Reusability).
3) The program becomes easily understandable, modifiable and easy to debug and
test. It becomes simple to write the program and understand what work is done
by each part of the program
4) Functions can be stored in a library and reusability can be achieved.
Introduction to Programming Raghu Engineering College (A) 3
C programs have two types of functions-
i. Library functions
ii. User-defined functions
i) Library Functions:
• C has the facility to provide library functions for performing some operations.
These functions are present in the C library and they are predefined.
• For example sqrt( ) is a mathematical library function which is used for finding
out the square root of any number. The functions scanf( ) and printf( ) are input
output library functions. Similarly we have functions like strlen( ), strcmp( ) for
string manipulations.
• To use a library function we have to include corresponding header file using the
preprocessor directive #include.
• For example to use input output functions like printf( ), scanf( ) we have to include
stdio.h, for mathematical library functions we have to include math.h, for string
library string.h should be included for functions like strlen( ), strcmp( ) .
Introduction to Programming Raghu Engineering College (A) 4
Ex: Program to find the square root of any number.

#include<stdio.h>
#include<math.h>
int main()
{
double n, s;
printf("Enter a number ");
scanf("%lf", &n) ;
s=sqrt(n);
printf("The square root of %. 2lf is %.2lf\n", n, s );
}

Introduction to Programming Raghu Engineering College (A) 5


ii) User-Defined Functions:
Users can create their own functions for performing any specific task of
the program. These types of functions are called user-defined functions.
To create and use these functions, we should know about these three
things-
1) Function definition
2) Function declaration
3) Function call

Introduction to Programming Raghu Engineering College (A) 6


1) Function definition:
• The function definition consists of the whole description and code of a
function. It tells what the function is doing and what are its inputs and
outputs. A function definition consists of two parts - a function header
and a function body.
• The general syntax of a function definition is
`
return_type func_name (typel argl, type2 arg2, ….) Function Header
{
local variables declarations;
statement;
……. Function Body
return(expression) ;
}

Introduction to Programming Raghu Engineering College (A) 7


• The first line in the function definition is known as the function header
and after this, the body of the function is written enclosed in curly
braces.
• The return_type denotes the type of the value that will be returned by the
function. The return_type is optional and if omitted, it is assumed to be
int by default. A function can return either one value or no value. If a
function does not return any value then void should be written in place of
return_type.
• func_name specifies the name of the function and it can be any valid C
identifier. After function name the argument declarations are given in
parentheses, which mention the type and name of the arguments. These
are known as formal arguments and used to accept values. A function can
take any number of arguments or even no argument at all. If there are no
arguments then either the parentheses can be left empty or void can be
written inside the parentheses.

Introduction to Programming Raghu Engineering College (A) 8


• The body of the function is a compound statement (or a block), which consists
of declarations of variables and C statements followed by an optional return
statement.
• The variables declared inside the function are known as local variables since
they are local to that function only, i.e. they exist only in the function in which
they are declared, they can not be used anywhere else in the program.
• There can be any number of valid C statements inside a function body.
• The return statement is optional. It may be absent if the function does not
return any value. The return statement is used in a function to return a value to
the calling function. It may also be used for immediate exit from the called
function to the calling function without returning a value. This statement can
appear anywhere inside the body of the function. There are two ways in which
it can be used-
1. return;
2. return ( expression );
Introduction to Programming Raghu Engineering College (A) 9
• The function definition can be placed anywhere in the program. But
generally all definitions are placed after the main( ) function. Note that
a function definition cannot be placed inside another function
definition.

For example:
int sum (int x, int y) /*Function definition*/
{
int s;
s=x+y;
return s;
}

Introduction to Programming Raghu Engineering College (A) 10


2) Function Call:
• The function definition describes what a function can do, but to actually use it in
the program the function should be called somewhere. A function is called by
simply writing its name followed by the argument list inside the parentheses.
func_name(arg1, arg2, arg3 ...)
• These arguments arg1, arg2,....are called actual arguments.
• Here func_name is known as the called function while the function in which this
function call is placed is known as the calling function.
When a function is called, the control Calling Function Called Function 1
passes to the called function, which is
executed and after this, the control is
transferred to the statement following
the function call in the calling function. Called Function 2
This figure shows the transfer of control
when two functions funcl() and func2()
are called from main().

Introduction to Programming Raghu Engineering College (A) 11


For example:
#include<stdio.h>
int sum(int x, int y); /*Function declaration*/
int main() /*Calling Function*/ int sum (int x, int y) /*Function definition*/
{ { /*Called Function*/
int a,b, s; int s;
printf ("Enter values for a and b:"); s=x+y;
scanf ("%d %d", &a, &b) ; return s;
s=sum (a, b); /*Function call*/ }
printf ("Sum of %d and %d is %d \n", a, b, s) ;
}

• In the above program, main() is the calling function, sum() is the called function, “a, b” are actual
arguments, and “x, y” are formal arguments. The function call is written on the right-hand side of the
assignment operator as, s = sum(a, b);

Introduction to Programming Raghu Engineering College (A) 12


3) Function Declaration:
• The function declaration is also known as the function prototype, and it
informs the compiler about the following three things-
1. Name of the function.
2. Number and type of arguments received by the function.
3. Type of value returned by the function.
• Function declaration tells the compiler that a function with these features
will be defined and used later in the program. The general syntax of a
function declaration is-
return_type func_name(type1 arg1, type2 arg2, .. , .....);
• The calling function needs information about the called function. If the
definition of the called function is placed before the calling function, then
declaration is not needed.
Introduction to Programming Raghu Engineering College (A) 13
#include<stdio.h>
#include<stdio.h>
int sum(int x, int y); /*Function declaration*/
int sum (int x, int y) /*Function definition*/
int main() /*Calling Function*/
{ /*Called Function*/
{
int s;
int a,b, s;
s=x+y;
printf ("Enter values for a and b:");
return s;
scanf ("%d %d", &a, &b) ;
}
s=sum (a, b); /*Function call*/
int main() /*Calling Function*/
printf ("Sum of %d and %d is %d \n", a, b, s);
{
}
int a,b, s;
int sum (int x, int y) /*Function definition*/
printf ("Enter values for a and b:");
{ /*Called Function*/
scanf ("%d %d", &a, &b) ;
int s;
s=sum (a, b); /*Function call*/
s=x+y;
printf ("Sum of %d and %d is %d \n", a, b, s) ;
return s;
}
}
Introduction to Programming Raghu Engineering College (A) 14
Function Arguments
The calling function sends some values to the called function for communication; these
values are called arguments or parameters,
a) Actual arguments: The arguments which are mentioned in the function call are known
as actual arguments, since these are the values which are actually sent to the called function.
• For example-
sum (a, b) // a and b are actual arguments
b) Formal arguments: The name of the arguments, which are mentioned in the function
definition are called formal or dummy arguments since they are used just to hold the values
that are sent by the calling function.
• For example-
int sum( int x, int y) // x and y are formal arguments
{
int s;
s = x + y;
return s;
}
Introduction to Programming Raghu Engineering College (A) 15
Example:
#include<stdio.h>
int sum(int x, int y);
int main()
{
int a,b, s;
printf ("Enter values for a and b:");
scanf ("%d %d", &a, &b) ;
s=sum (a, b); // a and b are actual arguments
printf ("Sum of %d and %d is %d \n", a, b, s);
}
int sum (int x, int y) // x and y are formal arguments
{
int s;
s=x+y;
return s;
}
Introduction to Programming Raghu Engineering College (A) 16
Categories of Functions:

• The functions can be classified into four categories based on the


arguments and return value.
1) Functions with no arguments and no return value.
2) Functions with no arguments and a return value.
3) Functions with arguments and no return value.
4) Functions with arguments and a return value.

Introduction to Programming Raghu Engineering College (A) 17


1) Functions with no arguments and no return value:
Functions that have no arguments and no return value are written as-
#include<stdio.h>
void sum();
The function sum() has no arguments, Calling
int main()
main() can not send any data to sum() Function
{
and since it has no return statement, sum ();
hence function sum() can not return }
any value to main(). There is no void sum ()
communication between the calling Called
{ Function
and the called function. int a, b, s;
printf ("Enter values for a and b:");
scanf ("%d %d", &a, &b) ;
s = a + b;
printf("Sum is %d", s);
}

Introduction to Programming Raghu Engineering College (A) 18


2) Functions with no arguments and a return value:
Functions that have no arguments and no return value are written as-
#include<stdio.h>
int sum();
int main() Calling
Function
{
The function sum() has no int s;
arguments, main() can not send any s = sum ();
data to sum() and it has a return printf("Sum is %d", s);
statement, hence function sum() can }
Called
return any value to main(). int sum ()
Function
{
int a, b, s;
printf ("Enter values for a and b:");
scanf ("%d %d", &a, &b) ;
s = a + b;
return s;
}
Introduction to Programming Raghu Engineering College (A) 19
3) Functions with arguments and no return value:
• These types of functions have arguments, hence the calling function can
send data to the called function but the called function does not return any
value, These functions can be written as-
#include<stdio.h>
void sum(int, int); Calling
The function sum() has arguments, int main() Function
main() can send data to sum() and since {
it has no return statement, hence int a,b, s;
function sum() can not return any value printf ("Enter values for a and b:");
to main(). Here a and b are actual scanf ("%d %d", &a, &b) ;
sum (a, b);
arguments that are used for sending the
}
value, and x and y are the formal Called
void sum (int x, int y)
arguments, which accept values from the Function
{
actual arguments. int s;
s = x + y;
printf("Sum is %d", s);
}
Introduction to Programming Raghu Engineering College (A)
4) Functions with arguments and a return value:
• These types of functions have arguments, so the calling function can send
data to the called function, it can also return any value to the calling
function using the return statement. This function can be written as-
#include<stdio.h>
int sum(int, int);
int main() Calling
{ Function
int a,b, s;
The function sum() has arguments, main() printf ("Enter values for a and b:");
scanf ("%d %d", &a, &b) ;
can send data to sum() and it has a return
s = sum (a, b);
statement, hence function sum() can return printf("Sum is %d", s);
any value to main(). }
Called
int sum (int x, int y)
Function
{
int s;
s = x + y;
return s;
}
Introduction to Programming Raghu Engineering College (A) 21
Passing Parameters to Functions
• Functions can be invoked in two ways:
1. Call by Value
2. Call by Reference.
• These two ways are generally differentiated by the type of values
passed to them as parameters.
• We already know that, the parameters passed to the function are called
actual parameters whereas the parameters received by the function are
called formal parameters.

Introduction to Programming Raghu Engineering College (A) 22


1) Call By Value:
• In call by value method of parameter passing, the values of actual
parameters are copied to the function‟s formal parameters.
There are two copies of parameters stored in different memory
locations.
One is the original copy and the other is the function copy.
Any changes made inside functions are not reflected in the actual
parameters of the caller

Introduction to Programming Raghu Engineering College (A) 23


For Example:
#include <stdio.h>
void swap(int, int);
int main()
{
int a, b;
printf("Enter a and b values:\n");
scanf("%d%d", &a, &b);
printf("Before Swapping:\na = %d b = %d\n", a, b);
swap(a, b); // a and b are Actual Parameters
printf("After Swapping:\na = %d b = %d\n", a, b);
return 0;
}
void swap(int x, int y) // x and y are Formal Parameters
{
int t;
t = x;
x = y;
y = t;
}
Introduction to Programming Raghu Engineering College (A) 24
2) Call By Reference:
• In call by reference method of parameter passing, the address of the
actual parameters is passed to the function as the formal parameters.
Both the actual and formal parameters refer to the same locations.
Any changes made inside the function are actually reflected in the
actual parameters of the caller.

Introduction to Programming Raghu Engineering College (A) 25


For Example:
#include <stdio.h>
void swap(int*, int*);
int main()
{
int a, b;
printf("Enter a and b values:\n");
scanf("%d%d", &a, &b);
printf("Before Swapping:\na = %d b = %d\n", a, b);
swap(&a, &b); // a and b are Actual Parameters
printf("After Swapping:\na = %d b = %d\n", a, b);
return 0;
}
void swap(int *x, int *y) // x and y are Formal Parameters
{
int t;
t = *x;
*x = *y;
*y = t;
}
Introduction to Programming Raghu Engineering College (A) 26
Difference between call by value and call by reference
CALL BY VALUE CALL BY REFERENCE
In call by value, Variable values are passed as arguments In call by reference, Variable addresses(references)are
in function call passed as arguments in function call

In function definition (called function),variables declared In function definition (called function),variables declared
as formal arguments are normal variables. as formal arguments are pointer variables.

Changes made in function copy are not reflected in Changes made in function copy are reflected in original
original copy of function copy of function

Introduction to Programming Raghu Engineering College (A) 27


Arrays as Function Arguments
Passing a 1-D Array to a Function:
• We can pass whole array as an actual argument to a function. The corresponding
formal argument should be declared as an array variable of the same data type.
• For ex: void totalsum1d(int a[6])
#include<stdio.h> {
int sum=0,i;
void totalsum1d(int[6]); // we can also write this // we can also write it as
proto type as for(i=0;i<6;i++)
int main() { void totalsum(int a[])
{ void totalsum(int a[]);
sum+=a[i]; void totalsum(int *a)
int i, arr [6] = {1, 2, 3,4, 5, 6} ; }
printf ("Contents of array are :"); printf("\nThe sum of elements = %d", sum);
for(i=0; i<6; i++) }
printf("%d ", arr[i]);
totalsum1d(arr);
}

Introduction to Programming Raghu Engineering College (A) 28


• It is optional to specify the size of the array in the formal argument.
• We have studied that changes made in formal arguments do not affect the
actual arguments, but this is not the case while passing an array to a
function.
• When an array is passed as an actual argument, the called function actually
gets access to the original array and works on it, so any changes made
inside the function affect the original array.

Introduction to Programming Raghu Engineering College (A) 29


Passing a 2-D Array to a Function:
• For ex:
#include<stdio.h> // we can also write this proto void totalsum2d(int a[3][4])// we can also write it as
void totalsum2d(int a[3][4]); type as { void totalsum(int a[][4]) or
int main() void totalsum2d (int a[][4]); int sum=0, i, j; void totalsum(int (*a)[4])
{ void totalsum2d (int (*a)[4]); for(i=0;i<3;i++)
int i,j,arr[3][4]={{11,12,13,14},{15,16,17,18},{19,20,21,22}}; for(j=0;j<4;j++)
printf ("Contents of 2D array are : \n"); sum += a[i][j];
for(i=0;i<3;i++) printf("\nThe sum of elements = %d", sum);
{ }
for(j=0;j<4;j++)
printf("%d ",arr[i][j]);
printf("\n");
}
totalsum2d(arr);
}

Introduction to Programming Raghu Engineering College (A) 30


Class Exercises:
1. Write a function that accepts a character in lower case and returns its upper case
equivalent.
2. Write a function 'check' to verify whether a given character is alphabet or digit.
3. Write a function to print the below kind of pattern for the given argument 'n'
1
22
333
4444

Introduction to Programming Raghu Engineering College (A) 31


Pointers as Function Arguments
• Passing the pointers to the function means the memory location of the
variables is passed to the parameters in the function, and then the operations
are performed. The function definition accepts these addresses using pointers,
addresses are stored using pointers.
• For example: #include <stdio.h>
void addOne(int*);
#include <stdio.h>
void addOne(int**);
int main() int main()
{ {
int* p, i = 10; int* p, i = 10;
p = &i; p = &i;
addOne(p); addOne(&p);
printf("%d", *p); // 11 printf("%d", *p); // 11
return 0; return 0;
} }
void addOne(int* ptr) { void addOne(int **ptr) {
(*ptr)++; // adding 1 to *ptr (**ptr)++; // adding 1 to **ptr
} }
Here we passed address of variable a Here we passed address of pointer p
Introduction to Programming Raghu Engineering College (A) 32
Scope of Variables
• The scope of a variable in C is the block or the region in the program
where a variable is declared, defined, and used. Outside this region,
we cannot access the variable and it is treated as an undeclared
identifier.
• For example: #include <stdio.h>
int main()
// Scope of this variable var is
within main() function only.
{
int var = 34;
printf("%d", var); Here function func() try to
return 0; access the var defined in
} main(), gives an error
void func()
{
printf("%d", var);
}

Introduction to Programming Raghu Engineering College (A) 33


Local, Global And Static Variables
Local Variables:
• The variables that are defined within the body of a function or a block, are local to
that function block only and are called local variables.
Global Variables:
• The variables that are defined outside any function are called global variables. All
functions in the program can access and modify global variables. It is useful to
declare a variable global if it is to be used by many functions in the program.
Global variables are automatically initialized to 0 at the time of declaration.
Static Variables:
• Static variables are declared by writing keyword static in front of the declaration.
static type var_name;.
• A static variable is initialized only once and the value of a static variable is
retained between function calls. If a static variable is not initialized then it is
automatically initialized to 0.
Introduction to Programming Raghu Engineering College (A) 34
For example: #include<stdio.h>
void func();
#include <stdio.h>
int main()
void mul(int, int);
{
int a = 10; // a is global variable
func();
int main()
func();
{
func();
int b = 20, c=30; // b and c are local variables
}
printf("Sum = %d", a+b);
void func()
mul(b, c);
{
return 0;
int a=10;
}
static int b=20;
void mul(int x, int y) // x and y are local variables
printf("a = %d b = %d\n", a, b);
{
a++;
printf(“Product = %d", x * y);
b++;
}
}
Example for Local and Global Variables Example for Static Variables
Introduction to Programming Raghu Engineering College (A) 35
Variable Storage Classes
• C Storage Classes are used to describe the features of a
variable/function. These features basically include the scope, visibility,
and lifetime which help us to trace the existence of a particular
variable during the runtime of a program.
• C language uses 4 storage classes, namely:
1. auto
2. extern
3. static
4. register

Introduction to Programming Raghu Engineering College (A) 36


1) auto:
• It is also known as the automatic storage class, and it acts as the default
storage class for all the variables that are local in nature. We use the
keyword auto to define the automatic variables, but its optional.
• Features of automatic variables:
The scope of an automatic variable is limited to that block in which we
are defining them.
The visibility of these variables is also limited to that block in which we
are defining them.
The initialization of these variables is, by default, a garbage value.
The memory that is assigned to an automatic variable gets free when it
exits from a block.

Introduction to Programming Raghu Engineering College (A) 37


2) extern:

• The extern or external storage class is used to give a reference of a


global variable that is visible to ALL the program files. When you use
'extern', the variable cannot be initialized however, it points the
variable name at a storage location that has been previously defined.
• The extern modifier is most commonly used when there are two or
more files sharing the same global variables or functions.
• An external integral type‟s default initial value is going to be 0, or else
it is null.

Introduction to Programming Raghu Engineering College (A) 38


3) static:
• This type of storage class gives an instruction to a compiler to keep the given
local variable around during the program‟s lifetime- instead of creating it and
then destroying it every time it comes into a scope and goes out of it. Thus,
when we make a local variable static, it allows the variable to maintain the
values that are available between various function calls.
• Features of static variables:
Those variables that we define as static specifiers are capable of holding
their assigned value that exists between various function calls.
The static local variables are only visible to the block or the function in
which we have defined them.
The initial value of a static variable, by default, is 0.
The visibility of any static global variable stays limited to that file in
which we have declared it.
Introduction to Programming Raghu Engineering College (A) 39
4) register:
• We use the register storage class for defining the local variables that must be
stored in any register, and not in a RAM. It means that the maximum size of this
variable is equal to that of the register size (it is usually one word). Also, we
cannot apply the „&‟ unary operator to it because it has no memory location.
• We must only use the register in the case of those variables which require quick
access.
• Features of register variables:
Its access time is comparatively much faster than that of the automatic
variables.
One cannot dereference a register variable. In other words, one cannot make
use of the „&‟ operator in the case of a register variable.
The default initial value of any given register local value will always be
garbage.
Introduction to Programming Raghu Engineering College (A) 40
Introduction to Programming Raghu Engineering College (A) 41
#include <stdio.h>
For example: void display();
extern int a;
int main()
{
auto int b;
register int c;
printf("auto variable b = %d\n", b);
printf("gloabal variable a = %d\n", a);
printf("register variable c = %d\n\n", c);
display();
display();
display();
}
int a;
void display()
{
static int d;
printf("Static variable d = %d\n", d);
d++;
}

Introduction to Programming Raghu Engineering College (A) 42


Recursion
• The function that calls itself (inside function body) repeatedly again and again until
some condition is specified is known as recursión and that function is known as
recursive function. In recursion the calling function and the called function are same.
• Before writing a recursive function for a problem we should consider these points-
We should be able to define the solution of the problem in terms of a similar type of
smaller problem. At each step we get closer to' the final' solution of our original
problem.
There should be a terminating condition to stop recursion.
• For example, factorial of a positive integer n can be found out by multiplying all integers
from 1 to n.
n! = 1 * 2 * 3 * ......* (n-l) * n
We know that 6! = 6*5*4*3*2*1
We can write it as- 6! = 6*5!
Similarly we can write 5! = 5*4!
So intogeneral
Introduction we can write n!
Programming = nEngineering
Raghu * (n-l)! College (A) 43
The best example to understand recursive function is computing factorial of
a number
If we want find n factorial ,mathematically it can be represented as
n! = n × (n - 1)!
To find factorial(3) we write factorial(3) is 3 * factorial(2)
similarly factorial(2) is 2 * factorial(1)
similarly factorial(1) is 1 * factorial(0)
we know factorial(0) is 1 this,acts as terminating condition for recursion
Recursion calls are stored in stack memory as given below

Introduction to Programming Raghu Engineering College (A) 44


For example:

#include<stdio.h> int fact(int n)


int fact(int n); {
int main() if(n==0)
{ return 1;
int num; else
printf ("Enter a number ") ; return(n*fact(n-1));
scanf("%d",&num); }
printf("Factorial of %d is %d\n", num, fact (num));
}
This is recursive call

Introduction to Programming Raghu Engineering College (A) 45


• Suppose, we want to find out the factorial of 5.

• When factorial( ) is called with n=0 then the condition inside the if statement
becomes true, so now the recursion stops and control returns to factorial(l)
• Now every called function will return the value to the previous function. These
values are returned in the reverse order of function calls.
• Recursive functions work in two phases. First one is the winding phase and the
next one is unwinding phase. In winding phase the function keeps on calling
itself. The winding phase stops when the terminating condition arrives in a call,
now the unwinding phase starts and the called functions return values in reverse
order.
Introduction to Programming Raghu Engineering College (A) 46
Example: Program to print the Fibonacci series
• Now we'll write a recursive definition for finding Fibonacci numbers

This figure shows the


recursive calls of
function fib( ) when it is
called with argument 5.

Introduction to Programming Raghu Engineering College (A) 47


#include<stdio.h>
int fib(int);
int main()
{
int nterms, i;
printf ("Enter number of terms ") ;
scanf ("%d", &nterms);
for(i=0; i<nterms; i++)
printf("%d ",fib(i));
}
int fib(int n) /* recursive function that returns
{ nth term of fibonacci series */
if (n==0 || n==1)
return 1;
else
return (fib(n-1)+fib(n-2));
}
Introduction to Programming Raghu Engineering College (A) 48
Class Exercises:
1. Write a C program to print number in words using recursion. For example if
we have a number 31246, then the program should print "Three one Two
four Six”
2. Write a C program to find the sum of digits in a given number using
recursion
3. Write a C program to reverse a number using recursion

Introduction to Programming Raghu Engineering College (A) 49


Strings:
• A String is a sequence of characters terminated with a null character i.e. '\0'.
• There is no separate data type for strings in C. They are treated as array of type
char. A character array is a string if it ends with a null character ('\0'). This null
character is an escape sequence with ASCII value 0.
String Constant or String Literal:
• A string constant is a sequence of characters enclosed in double quotes. It is
sometimes called as literal.
• The double quotes are not a part of the string. Some examples of string constants
are-
1. "Taj Mahal"
2. "V"
3. "2345"
4. "Subhash Chandra Bose was a great leader"
5. "" (Null string, contains only '\0')
Introduction to Programming Raghu Engineering College (A) 50
• Whenever a string constant is written anywhere in a program, it is
stored somewhere in memory as an array of characters terminated by a
null character ('\0‟). The string constant itself becomes a pointer to the
first character in the array. For example the string "Taj Mahal" will be
stored in memory as-

• Each character occupies one byte and compiler automatically inserts the
null character at the end. The string constant "Taj Mahal" is actually a
pointer to the character 'T'. So whenever a string constant. used in the
program it is replaced by a pointer pointing to the string.
• If we have a pointer variable of type char *, then we can assign the
address of this string constant to it as-
char *p = "Taj Mahal";
Introduction to Programming Raghu Engineering College (A) 51
String Variables:
• To create a string variable we need to declare a character array with
sufficient size to hold all the characters of the string including null
character.
char str[ ] = {'N' , 'e' , 'w' , ' ', 'Y' , 'o' , 'r' , 'k' , '\0‟};
• We may also initialize it as
char str[ ] = "New York";
• This initialization is same as the previous one and in this case the
compiler automatically inserts the null character at the end. The array
str will be stored in memory as-

Introduction to Programming Raghu Engineering College (A) 52


Example program to print characters of a string and
address of each character:
#include<stdio.h>
int main()
{
char arr[]="India";
int i;
for(i=0; arr[i]!='\0'; i++)
{
printf ("Character = %c \t" , arr[i]);
printf("Address = %u \n",&arr[i]);
}
}

Introduction to Programming Raghu Engineering College (A) 53


Example program to print the address and characters of
the string using pointer:
#include<stdio.h>
int main()
{
char arr[]="India";
char *p;
Here 'p' is pointer variable which holds the
p=arr; base address of array arr[ ]. Incrementing this
while(*p != '\0') pointer by 1 gives the address of next element of
{ character array arr[ ], so on incrementing and
printf ("Character = %c \t" , *p); dereferencing this pointer we can print all the
elements of the string. Here the loop terminates
printf("Address = %u \n", p);
when the character '\0' is encountered which means
p++; end of the string.
}
}Introduction to Programming Raghu Engineering College (A) 54
Printing and Scanning strings:
• There is a shortcut way for entering and printing strings, using %s
specification in the control string of printf() and scanf().
Example program to input and output a string variable using scanf ( ) and printf ( ):
#include<stdio.h>
int main()
{
char name [20] ;
printf("Enter your college name:");
scanf("%s", name);
printf ("%s", "My college name is "); The printf( ) takes the base address of string and continues to
display the characters until it encounters the character '\0‟. We
printf("%s", name); haven't used & sign in the scanf( ) since the name of the array is
} itself address of the array. In the 2nd run when we entered a string
with space we could not get the required result. This is because
scanf( ) stops reading as soon as it encounters a whitespace.

Introduction to Programming Raghu Engineering College (A) 55


• For entering strings with whitespaces(blank spaces) we can use the
function gets().
• It stops reading only when it encounters a newline and replaces this
newline by the null character.
• We have another function puts() which can output a string and replaces
the null character by a newline.
Example program to input and output a string variable using gets() and puts( ):
#include<stdio.h>
int main()
{
char name[20];
printf("Enter name : ");
gets(name);
printf("Entered name is : ") ;
puts(name);
}Introduction to Programming Raghu Engineering College (A) 56
String Processing with and without Library Functions:
• There are several library functions used to manipulate strings(known as string
handling functions or string manipulation functions). The prototypes for
these functions are in header file string.h.
1) strlen( ):
• This function returns the length of the string i.e. the number of characters in the
string excluding the terminating null character. It accepts a single argument, i.e.
string.
Syntax: strlen (string name);

Introduction to Programming Raghu Engineering College (A) 57


For example: Find the length of the string with the Library function.
#include <stdio.h>
#include <string.h>
int main() Output:
{ Length of string Raghu is 5
int len;
char s[]="Raghu";
len = strlen(s);
printf("Length of string %s is %d", s, len);
}

For example: Find the length of the string without Library function.
#include <stdio.h>
int main()
Output:
{
Length of string Raghu is 5
char s[]="Raghu";
int i, len=0;
for(i=0; s[i] != '\0'; i++)
len++;
printf("Length of string %s is %d", s, len);
}

Introduction to Programming Raghu Engineering College (A) 58


2) strcmp( ):
• This function is used for the comparison of two strings. If the two strings match,
strcmp( ) returns a value 0, otherwise, it returns a non-zero value.
• This function compares the strings character by character. The comparison stops
when either the end of the string is reached or the corresponding characters in the
two strings are not the same.
• The non-zero value returned on mismatch is the difference between the ASCII
value of the non-matching characters of the two strings-
Syntax: int strcmp(string1, string2);

strcmp(s1, s2) returns a value-


< 0 when s1 < s2
= 0 when s1 == s2
> 0 when sl > s2

Introduction to Programming Raghu Engineering College (A) 59


For example: Compare two strings with the Library function.
Output:
Comparing s1 and s2
#include <stdio.h> output is 1
#include <string.h> Comparing s3 and s4
int main() output is -1
{ strcmp compares 2 strings,if they are
char s1[]="abcd", s2[]="Abcd"; same,outputs 0 value,otherwise compares each
char s3[]="PQRS", s2[]="pqrs"; character of 2 strings one by one by its ASCII
printf(“Comparing s1 and s2\n”); Values ,for example here first character of string
printf(“output is %d\n", strcmp(s1, s2)); s1 is a(its ASCII Value is 97) and first character
of string s2 is A(a(its ASCII Value is 65),so
printf(“Comparing s3 and s4\n”); strings1(character a) has highest ASCII so
printf(" output is %d\n ", strcmp(s3, s4)); returns Difference(97-65=32) of these as output
return 0; of positive value(1),otherwise returns negative
} value(-1) as output , if first characters are
same,then checks 2nd character and so on

Introduction to Programming Raghu Engineering College (A) 60


For example: Compare two strings without Library function.
#include <stdio.h>
#include <string.h>
int main()
Output:
{
32
char s1[]="abcd", s2[]="Abcd";
int i, flag=0, diff;
for(i=0; s1[i] != '\0' && s2[i] != '\0'; i++)
{
if(s1[i] != s2[i]) {
flag = 1;
diff = s1[i] - s2[i];
break;
}
}
if(s1[i] == '\0' && s2[i] == '\0' && flag == 0)
printf("0");
else
printf("%d", diff);
}
Introduction to Programming Raghu Engineering College (A) 61
3) strncmp():
• This function is used for comparing the first „n‟ characters of two
strings.
Syntax:
strncmp ( string1, string2, n)
For example:
#include <stdio.h>
#include <string.h> Output:
int main() 0
{
char s1[]="There", s2[]="These";
printf("%d", strncmp (s1, s2, 3));
}

Introduction to Programming Raghu Engineering College (A) 62


4) strcpy():
• This function is used for copying one string to another string. strcpy(sl,s2)
copies s2 to s1. Here s2 is the source string and s1 is the destination string.
• If s2 = "Raghu" this function copies "Raghu" into s1.
Syntax:
strcpy (Destination_string, Source_string);
For example: Copy one string to another string with the Library function.
#include <stdio.h>
Output:
#include <string.h>
int main() String s2 = hello
{
char s1[]="hello", s2[10];
strcpy(s2,s1);
printf("String s2 = %s", s2);
}

Introduction to Programming Raghu Engineering College (A) 63


For example: Copy one string to another string without the Library
function.

#include <stdio.h> Output:


#include <string.h> String s2 = hello
int main()
{
char s1[]="hello", s2[10];
int i;
for(i=0; s1[i] != '\0'; i++)
s2[i] = s1[i];
s2[i] = '\0';
printf("String s2 = %s", s2);
}

Introduction to Programming Raghu Engineering College (A) 64


5) strncpy():
• It copies the 'n' characters of the source string into the destination string.
Syntax:
strncpy(Destination_string, Source_string, n);
For example:
#include <stdio.h>
#include <string.h>
Output:
int main()
String s2 = hel
{
char s1[]="hello", s2[10];
strncpy(s2, s1, 3);
printf(“String s2 = %s", s2);
}

Introduction to Programming Raghu Engineering College (A) 65


6) strcat( ):
• This function is used for concatenation of two strings.
Syntax:
strcat(Destination_string, Source_string);
For example: The concatenation of one string with another string with the library
function

#include <stdio.h>
#include <string.h>
int main()
{
char s1[]="Raghu ", s2[]="Engg College";
printf ("Before concatenation \n\tfirst string is %s \n\tSecond string is %s\n", s1, s2) ;
strcat(s1,s2);
printf ("After concatenation \n\tfirst string is %s \n\tSecond string is %s\n", s1, s2) ;
}

Introduction to Programming Raghu Engineering College (A) 66


For example: The concatenation of one string with another string
without the library function

#include <stdio.h>
#include <string.h>
int main()
{
char s1[30]="Raghu ", s2[]="Engg College";
int len=0, i, j;
printf ("Before concatenation \n\tfirst string is %s \n\tSecond string is %s\n", s1, s2) ;
for(i=0; s1[i] != '\0'; i++)
len++;
for(j=0; s2[j] != '\0'; j++)
s1[len++] = s2[j];
s1[len]='\0';
printf ("After concatenation \n\tfirst string is %s \n\tSecond string is %s\n", s1, s2) ;
}

Introduction to Programming Raghu Engineering College (A) 67


7) strncat( ):
• This is used for combining or concatenating n characters of one string into another.
Syntax:
strncat(Destination_string, Source_string, n);
For example:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[]="Raghu ", s2[]="Engg College";
printf("First string is %s Second string is %s\n", s1, s2);
printf ("Before concatenation \n\tfirst string is %s \n\tSecond string is %s\n", s1, s2) ;
strncat(s1,s2,4);
printf ("After concatenation \n\tfirst string is %s \n\tSecond string is %s\n", s1, s2) ;
}
In the above program strcat() function concatenates s2 at the end of sl.
Introduction to Programming Raghu Engineering College (A) 68
8) strrev():
• The function is used for reversing a string.
• The reversed string will be stored in the same string.
Syntax:
strrev(string)
For example: Reverse the given string with the Library function.
#include <stdio.h>
#include <string.h>
int main() Output:
{ Reversed string = elloH
char s[]="Hello";
strrev(s);
printf(“Reversed string = %s", s);
}

Introduction to Programming Raghu Engineering College (A) 69


For example: Reverse the given string without the Library function.
#include <stdio.h>
#include <string.h>
int main() Output:
{ Reversed string = elloH
char s[]="Hello", t;
int i, j, len=0;
for(j=0; s[j]!= '\0'; j++)
len++;
for(i=0, j=len-1; i<j; i++, j--)
{
t = s[i];
s[i] = s[j];
s[j] = t;
}
printf("Reversed string = %s", s);
}
Introduction to Programming Raghu Engineering College (A) 70
9) strstr():
• It is used to search whether a substring is present in the main string or not.
• It returns a pointer to the first occurrence of s2 in s1.
Syntax:
char* strstr(main_string, sub_string);
For example:
#include <stdio.h>
Output:
#include <string.h>
Engg is found in Raghu Engg College in 6 position
int main()
{
char main[]="Raghu Engg College", sub[]="Engg", *found;
found=strstr(main, sub);
if(found)
printf("%s is found in %s in %d position",sub,main,found-main);
else
printf("since the string is not found");
}

Introduction to Programming Raghu Engineering College (A) 71


Class Exercises:
1. Write a C program to check whether a string is palindrome or not.
2. Write a C program to count total number of vowels and consonants in a
string.

Introduction to Programming Raghu Engineering College (A) 72


Pointers and Strings:
• The string itself acts as a pointer.
• The string name is a pointer to the first character in the string.
• Now we'll compare the strings defined as arrays and strings defined as
pointers.
char str[] = "Mumbai";
char *ptr = "Chennai";
• These two forms may look similar but there are some differences in them.
The initialization itself has different meanings in both forms.
• Now let us see how they are represented in memory.

Introduction to Programming Raghu Engineering College (A) 73


• In the first case, str is an array of characters and 7 bytes are reserved for it.
Since str is the name of an array hence it is a constant pointer that will
always point to the first element of an array. The elements of an array are
initialized with the characters of the string.
• In the second case, the string constant "Chennai" is stored somewhere in
memory with 8 consecutive bytes reserved for it. The string constant returns
the address of the first character of the string that is assigned to the pointer
variable ptr. So in this case total of 10 bytes are reserved, 2 bytes for the
pointer variable and 8 bytes for the string.

Introduction to Programming Raghu Engineering College (A) 74


For example: Let's print each character of a string using pointer notation

#include<stdio.h> Output:
Hello
int main()
{
char str[6] = "Hello";
int i;

for(i = 0; str[i]; i++)


printf("%c ",*(str+i)); //str[i] == *(str+i)

return 0;
}

Introduction to Programming Raghu Engineering College (A) 75


Ex:
#include<stdio.h> Output:
int main() str1=HAPPY
{ str2=HELLO
char str1[]="HAPLY"; str3=HELLO
char str2[]="HELKO";
char *str3=str2;

str1[3]='P';
str3[3]='L';

printf("str1=%s\n", str1);
printf("str2=%s\n", str2);
printf("str3=%s\n", str3);
}

Introduction to Programming Raghu Engineering College (A) 76


Command-line arguments:
• Command-line arguments are the values given after the name of the
program in the command-line shell of Operating Systems. Command-
line arguments are handled by the main() function of a C program.
• To pass command-line arguments, we typically define main() with two
arguments: the first argument is the number of command-line
arguments and the second is a list of command-line arguments.
• Syntax:

int main(int argc, char *argv[]) int main(int argc, char **argv)
{ {
/* ... */ or /* ... */
} }

Introduction to Programming Raghu Engineering College (A) 77


Here,
• argc (ARGument Count) is an integer variable that stores the number
of command-line arguments passed by the user including the name of
the program. So if we pass a value to a program, the value of argc would
be 2 (one for argument and one for program name)
• The value of argc should be non-negative.
• argv (ARGument Vector) is an array of character pointers listing all
the arguments.
• If argc is greater than zero, the array elements from argv[0] to argv[argc-
1] will contain pointers to strings.
• argv[0] is the name of the program , After that till argv[argc-1] every
element is command -line arguments.

Introduction to Programming Raghu Engineering College (A) 78


Example program to demonstrate Command Line Arguments:
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("You have entered %d arguments:\n", argc);
for (int i = 0; i < argc; i++) {
if (i==0)
printf("Program name is %s\n", argv[i]);
else
printf("%s\n", argv[i]);
}
return 0;
}

Introduction to Programming Raghu Engineering College (A) 79

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy