PROGRAMMING IN C
& MATLAB
Strings & Functions
1
What is a String?
String is a set of characters
In ‘C’, there is no built in data type representing
strings
It is represented arrays of characters
Strings are accessed through pointers/array
names
2
String - examples
1. “DEPARTMENT OF TECHNICAL EDUCATION”
2. “State Board of Technical Education and Training”
3. “Polytechnic”
are all valid strings
3
Strings – storage in arrays
D E P A R T M E N T O F T E C H N I C A L E
D U C A T I O N A N D T R A I N I N G \0
4
Strings – storage in arrays
S T A T E B O A R D O F T E C H N I C A L
E D U C A T I O N A N D T R A I N I N G \0
5
Strings – NULL (0) character
Sequence of zero or more characters, terminated
by NULL (literally, the integer value 0)
NULL terminates a string, but is not part of it
The ASCII value of this is 0
6
6
NULL characters - example
The end of the string is marked with a
special character, the null character, which
is simply the character with the value 0 (or \
0 ).
For example:
char name[50] = “DAVE”;
7
String Literals
Evaluating ″dog″ results in memory allocated for
three characters ′d ′, ′ o ′, ′ g ′, plus terminating NUL
Note: If m is an array name, subtle difference:
char m[10] = ″dog″;
10 bytes are allocated for this array
This is not a string literal;
It’s an array initializer in disguise!
Equivalent to {′d′,′o′,′g′,
′\0′}
8
8
Strings - Declaration
In ‘C’ string is declared as
char name[24];
char district[30];
9
Strings – storage in arrays
P O L Y T E C H N I C \0
4002 4009
4004 4007
4000 4005 4010
4001 4006 4011
4003 4008
CONTIGUOUS MEMORY LOCATIONS HOLDING A STRING
10
C Strings (Character Arrays)
There is a difference between 'A' and "A"
'A' is the character A
"A" is the string A
Because strings are null terminated, "A" represents two
characters, 'A' and '\0‘
Similarly, "Hello" contains six characters, 'H', 'e', 'l', 'l',
'o', and '\0'
11
Strings – usage with arrays
For example a string denoting student
name of maximum 20 characters length
must be declared as
char student_name[21];
12
String initialization
A string can be initialized at declaration time as
char
string_name[length]={‘literal1’,’literal2’,’literal3’,
….,’literal(length-1),’\0’};
or
char string_name[length]=“literals of maximum
length (length-1)”
13
Declarations and Initializing strings
Array of char:
char str[5] = {'l', 'i', 'n', 'u', 'x'};
char str[6] = {'l', 'i', 'n', 'u', 'x', '\0'};
Declarations
14
String initialization - example
A string denoting name of a student can be
declared and initialized to SRINIVAS as
char
student_name[21]={‘S’,’R’,’I’,’N’,’I’,’V’,’A’,’S’,\0’};
Or
char student_name[21]=“SRINIVAS”;
Note that if a string is enclosed between double
quotes \0 is not necessary to be indicated.
However the compiler stores \0 at the end of the
string.
15
String Handling functions
C has no actual String type
Convention is to use null-terminated arrays of
chars
char str[] = “abc”;
‘a’, ‘b’, ‘c’, ‘\0’
String.h library of functions to manipulate
strlen(); strcmp(); strcpy(),…
16
String i/o functions
Strings can be handled
using two functions
scanf()
printf()
gets()
puts()
17
String Handling
scanf() function:
It is used to read a string from keyboard wordwise as
follows
ex:
char name[15];
scanf(“%s” ,name);
18
String Handling
printf() function
A string(word) can be printed using this
function as follows
printf(“%s”,name);
It does not print multi word string
19
String Handling
To handle multi word strings(lines ending
with newline characters) the functions used
are
gets()
puts()
20
String Handling functions
gets() :This function introduces NULL
character into the string upon encountering
a newline character
puts():This function outputs a string ending
with a newline character onto the standard
output device
21
String Handling functions
Ex:
char name[15];
gets(name);
puts(name);
These instructions read an entire line of
text from keyboard and print on to the
monitor
22
String i/o functions -program
23
String i/o functions -program
24
String i/o
Strings can also be read from keyboard or
written out to monitor using the functions
getchar()
putchar()
25
String I/O functions
getchar()
It appends NULL character upon
encountering a newline character
putchar()
It prints out an entire line of text ending
with a new line character
26
String functions
27
C-style strings
Comparing strings
#include <string.h>
if (s1 = = s2) { /* do s1 and s2 point to the same array?
(typically not what you want) */
}
if (strcmp(s1,s2) = = 0) { /* do s1 and s2 hold the same characters? */
}
Finding the lengths of a string
int lgt = strlen(s); /* note: goes through the string at run time
looking for the terminating 0 */
Copying strings
strcpy(s1,s2); /* copy characters from s2 into s1
be sure that s1 can hold that many characters */
28
28
String functions - program
29
String functions - program
30
String functions - program
31
String functions - program
32
String functions - program
33
Function techniques in C
Every C program contains at least one function that is
main() which is the first function to be executed by the
compiler
Functions are used for performing repeated tasks
Functions enable modular programming
34
Function definition
A self contained sub program that performs a
specific well defined task
35
Function Types
Library functions or Built-in functions
User defined functions
36
Library Functions
Already available in C language
User need not write programs
Can be used directly in the program
Examples:Finding square root, string
functions
37
User defined functions
Developed by user for performing a specific task
38
Advantages of user defined functions
Large task can be sub divided into several
smaller tasks
Smaller functions are easier to understand,
code, debug, and modify
Coded function can be placed in a library
for further use
39
Advantages of user defined functions
Contd..
Small functions are self documented and
are highly readable
Allows for the sharing of functions library
among programs
40
Features of functions
Function is defined when it is written
Function is defined once in a program and
can be used by any other function
Function receives many values but returns
only one value
41
Syntax of function
return-type function-name(datatype
arg1,datatype arg 2,…datatype arg n)
{
local variable declarations;
statement sequence;
return(expression);
}
42
Syntax of a function
contd….
Return type specifies the type of value the
function returns
If no type is specified the function is assumed
to return integer type
43
Syntax of a function
contd….
Rules applied for naming the variables will be
applied for function names also
With in parenthesis argument list is specified
with their type
Example:1
int big(int a, int b, int c)
{
------------
}
44
Syntax of a function
contd….
Function may be without arguments.
Example:2
int demo()
{
-----------
------------
}
45
Syntax of a function
contd….
If function returns nothing or takes no
arguments we use void
Example
void display(void)
{
------------
------------
}
46
Function Explanation
Function body consists of local variable
declarations
Local variables can be accessed by the
function in which it is defined
Statement sequence contains valid C
statements
47
Return statement
Syntax : return(expression); or
return();
Causes an immediate exit from the function
in which it occurs
Returns the value to the calling function
Returns nothing for a void function
48
Function parameters
Arguments in the function call are called
Actual parameters
Arguments appear in the function definition
are called Formal parameters
49
Calling a function
A function can be called by
- It’s name,
- Followed by list of arguments,
- Separated by commas and enclosed in
parenthesis
50
Calling a function
Contd..
There will be one actual parameter for each
formal parameter
Data type of actual and formal parameters
should be same
Names of actual and formal parameters can
be same or different
51
Calling a function
contd..
Examples
main()
{
int a,b,c;
--------
max(a,b,c);/* a,b,c are actual parameters*/
--------
}
52
Calling a function
contd..
Example:-1
int max(int x, int y, int z) /* x,y,z are formal
parameters*/
{
------
------
}
The values of actual parameters are copied into
formal parameters.
a,b,c values are given to x,y,z
53
Calling a function
contd..
When the compiler encounters a function call
control is transferred to the calling program
After the execution of the function program the
control is transferred back to the main program
using the return statement
54
Calling a function
contd..
Example:-2
#include<stdio.h>
main()
{
int product = mul(10,10);
printf(“The result is:%d”, product);
}
int mul(int i, int j)
{
return(i*j);
}
55
Function prototype
Tells the compiler the type of data returned by the
function
The number of arguments the function receives
Types of arguments
Order of the arguments
56
Function prototype
Syntax
Return_ type function_name(dt1,dt2..dtn);
Return_ type is the type of data returned by the
function
dt1,dt2..dtn are the types of data fed as arguments
57
Function prototype
Example:1
#include<stdio.h>
int big(int,int,int);/*function proto type*/
main()
{
int a,b,c;
scanf(“%d%d%d”,&a,&b,&c);
printf(“biggest is:%d”,big(a,b,c));
}
58
Function prototype
Contd..
int big(int x,int y,int z)
{
int max=x;
if(y>max)
max=y;
if(z>max)
max=z;
return(max);
}
59
Local variables
Variables which are defined within the body of
the function
Variables local to that function block
60
Local variables
Example Contd..
var(int i,int j)
{
int a,b;
---------
}
a, b are called local variables as they are
defined within the body of the function var()
61
Local variables
Contd..
Can only be used in the function in
which they are defined
Same variable names can be used in
different functions as they are local to
that particular function only
62
Global variables
Variables which are defined outside main()
function
Global variables are also known as External
variables
63
Global variables
Contd..
Global variables has the same name and
same data type throughout the program
It is useful to declare a variable as Global
when it has constant value throughout the
the program
64
Global variables
Contd..
Example
#include<stdio.h>
int a,b=6;
void fun();
main()
{
a=8;
fun();
}
65
Global variables
Contd..
void fun()
{
int area;
area = a*b;
printf(“%d”, area);
}
66
Global variables
Contd..
‘a’ and ‘b’ are global variables as they are
defined outside the main function
‘area’ is local variable as it is defined within
the function fun()
67
Differences between local and global variables
Local variables Global variables
1) Also known as Known as External
Automatic variables variables
2) Scope is within the Scope is entire
function program
3) Defined within the Defined outside
function main() function
68
Local variables Global variables
Contd..
4)Same variables can be Variables have constant
used in different values throughout the
programs program
5) Created upon Exists as long as
entry into its the program is
block and destro- executing
yed upon exit
69
Parameters can be passed to a function in two
ways
Call by value
Call by reference
70
Call by value
Actual arguments are copied into the
corresponding formal arguments
Changes done to the formal parameters have
no effect on the actual parameters because
actual parameters and formal parameters
have separate memory locations
71
Call by value
Write a program to compute the area, circumference of a circle with given radius
#include<stdio.h>
main()
{
float r,a,c;
void compute(float);
printf(“Enter the radius of the circle”);
compute(r);
}
void compute(float x)
{
float area,circum;
area=3.14*x*x;
circum=2*3.14*x;
printf(“area = %f ; circumference = %f \n”,area,circum);
}
72
Call by reference
Instead of values, only address of the actual
parameters is passed to the formal
parameters
Formal parameters are pointer variables and
they point to the same memory locations of
the corresponding actual parameters
So any changes done to the formal
parameters effect the actual parameters
73
Call by reference
Contd..
We use call by value mechanism if a single
value has to be returned
When more than one value is desired we use
call by reference mechanism to indirectly
transfer the resulting values back to the
calling function
74
Call By Reference
Write a program to calculate are and circumference of a circle for given
radius
#include<stdio.h>
main()
{
float r,a,c;
void compute(float,float *,float *);
printf(“Enter the radius of the circle”);
compute(r,&a,&c);
printf(“ \n area = %f circumference= %f \n”,a,c);
}
void compute(float x,float *y,float *z)
{
*y=3.14*x*x;
*z=2*3.14*x;
}
75
Call By Reference
Note that in the above example addresses
of variables a,c are passed to the function
The function modifies the contents of the
addresses a,c
Hence we can print the values of a,c (so
computed in ) in the main program itself
76
Call By Reference
Write a program to find the sum of a given series
#include<stdio.h>
main()
{
int n,a[10],sum,i;
void sum(int [],int,int *);
printf(“Enter the no.of elements in the list <10”);
scanf(“%d”,&n);
printf(“Enter the %d elements”,n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
sum(a,n,&sum);
printf(“\nThe sum of the series is: %d\n”,sum);
}
77
Call By Reference
void sum(int b[],int m ,int *s)
{
int i;
*s=0;
for(i=0;i<m;i++)
*s=*s+a[i];
}
78
Call By Reference
Write a program to that uses a function to sort an array of integers
/* Sorting of array elements */
#include<stdio.h>
main()
{
int I;
static int marks[5]={40,90,73,81,35};
printf(“marks before sorting\n”);
for(i=0;i<5;i++)
printf(“%d”,marks[i]);
printf(“\n\n”);
sort(5,marks);
printf(“marks after sorting”);
for(i=0;i<5;i++)
printf(“%4d”,marks[i]);
printf(“\n”);
}
79
Call By Reference
void sort(m,x)
int m,x[];
{
int I,j,t;
for(i=1;i<=m-1;i++)
for(j=1;j<=m-I;j++)
if(x[j-1]>=x[j])
{
t=x[j-1];x[j-1]=t;x[j]=t;
}
}
80
Call By Reference
Output
marks before sorting
40 90 73 81 35
Marks after sorting
35 40 73 81 90
81
Recursion
A function is recursive if a statement in the
body of the function calls itself
It is the process of defining something in
terms of itself
82
Advantage of recursion
Recursive function is
Clear
Short
Contains simple programs
83
Advantage of recursion
Contd..
Commonly used example of a recursive
procedure is finding the factorial of a number
Factorial of number N is defined as
N! = N*(N-1)*(N-2)*……..1
84
Advantage of recursion
Contd..
Recursive definition should have a stopping
condition i.e., 0! =1
Complete definition of factorial function is
N! = N*(N-1)! with 0! = 1
85
Program for factorial of a number
#include<stdio.h>
int fact(int);
main()
{
int n;
scanf(“%d”,&n);
printf(“factorial of number %d is %d\n”,n,fact(n));
}
86
Program for factorial of a number
int fact (int x) contd,..
{
int f =1;
if(x==1)
return(1);
else if(x>0)
f=x*fact(x-1);
return(f);
}
87
Program to find sum of digits of a number
#include<stdio.h>
int sumdigit(int);
main()
{
int n;
scanf(“%d”,&n);
printf(“sum of digits is %d:”,sumdigit(n));
}
88
Program to find sum of digits of a number
Contd..
int sumdigit(int x)
{
int sum =0;
if(x==0)
return(sum);
else
sum=(x%10 + sumdigit(x/10));
return(sum);
}
89