0% found this document useful (0 votes)
21 views14 pages

C program-Module 3

Uploaded by

preyasnayak19
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
21 views14 pages

C program-Module 3

Uploaded by

preyasnayak19
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

Functions & Strings

FUNCTIONS: “In c, we can divide a large program into the basic building blocks known
as function. The function contains the set of programming statements enclosed by {} that
performs a particular task/job”.

A function can be called multiple times to provide reusability and modularity to the C program.
In other words, we can say that the collection of functions creates a program. The function is also
known as procedure or subroutine in other programming languages.

Example: void hello( )

printf("hello nithin");

Need of Functions: Until now, in all the C programs that we have written, the program consists
of a main function and inside that we are writing the logic of the program.

The disadvantage of this method is, if the logic/code in the main function becomes huge or
complex, it will become difficult to debug the program or test the program or maintain the
program. So we’ll break down entire logic into different parts, this type of approach for solving
the given problems is known as Top Down approach.

Advantages of Functions: Functions have many advantages in programming. Almost all the
languages support the concept of functions in some way. Some of the advantages of
writing/using functions are:

 Functions support top-down modular programming.


 By using functions, the length of the source code decreases.
 Writing functions makes it easier to isolate and debug the errors.
 Functions allow us to reuse the code.
BASIC ELEMENTS OF USER DEFINED FUNCTION: For creating user defined
functions in C programs, we have to perform three steps. They are:

a) Function Declaration: Declaring the function (blue-print).

b) Function Definition: Defining the function (logic).

c) Function Calling: use of function in program (calling)

a) FUNCTION DECLARATION: The function declaration is the blue print of the function.
The function declaration can also be called as the function’s prototype.
The function declaration tells the compiler and the user about what is the function’s name,
inputs and output(s) of the function and the return type of the function.
Syntax: for declaring a function is shown below:
return_type function_name(parameters list);
Example:
int add(int m, int n);
In the above example, add is the name of the function, int is the return type of the function.
In our example, add function has two parameters. The parameters list is optional.

b) FUNCTION DEFINITION: The function definition specifies how the function will be
working i.e the logic of the function will be specified in this step.
Syntax: of function definition is shown below
return_type function_name(parameters list)
{
local variable declaration's;
---
return(expression);
}
Example:
int add(int a, int b)
{
int res;
res = a+b;
return res;
}
c) FUNCTION CALLING: After declaring and defining the functions, we can use the
functions in our program. For using the functions, we must call the function by its name.
Syntax: of function definition is shown below
function_name(parameters list);

Example: add(m,n);

Whenever the compiler comes across a function call, it takes the control of execution to the
first statement in the function’s definition. After the completion of function i.e., whenever the
compiler comes across the return statement or the closing brace of the function’s body, the
control will return back to the next statement after the function call.
PARAMETERS PASSING IN C FUNCTION: When a function gets executed in the
program, the execution control is transferred from calling-function to called function and
executes function definition, and finally comes back to the calling function.

When the execution control is transferred from calling-function to called-function it may carry
one or number of data values. These data values are called as parameters. In C, there are two
types of parameters and they are as follows:

1) Actual Parameters

2) Formal Parameters

There are two methods to pass parameters from calling function to called function and they are
as follows...

1) Pass by Value

2) Pass by Reference

In C, there are two types of parameters and they are as follows:


There are two methods to pass parameters from calling function to called function:

a) PASS BY VALUE: In call by value parameter passing method, the copy of actual parameter
values are copied to formal parameters and these formal parameters are used in called
function.
The changes made on the formal parameters does not effect the values of actual
parameters. That means, after the execution control comes back to the calling function, the
actual parameter values remains same.
Example: Program to swap two numbers using pass by value
#include<stdio.h>
void swap(int, int);
void main( )
{
int a,b;
printf(“Enter two numbers: ”);
scanf(“%d %d”, &a, &b);
swap(a,b);
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf(“A is %d\t B is %d”,a,b);
}

b) PASS BY REFERENCE/ Pass by address/ Call by Reference (Call by address) In Call


by Reference parameter passing method, the memory location address of the actual
parameters is copied to formal parameters. This address is used to access the memory
locations of the actual parameters in called function.
Whenever we use these formal parameters in called function, they directly access the
memory locations of actual parameters. So the changes made on the formal parameters
effects the values of actual parameters.
Example: Program to swap two numbers using pass by reference(pointer)
#include<stdio.h>
void swap(int *, int *);
void main( )
{
int a,b;
printf(“Enter two numbers: ”);
scanf(“%d %d”, &a, &b);
swap(&a,&b);
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
printf(“A is %d\t B is %d”,*a,*b);
}
Return statement

The return is a jump statement. When the return statement is executed in a function, then it
terminates the execution of the function and returns control to its caller function.

Syntax:

return (expression);

How does the return statement work?

When a function call to another function, then execution of the calling function is paused. The
control is transfer to the called function from the calling function. The return statement returns the
control to the calling function (terminates the execution of the called function) and now execution of
the calling function is resumed.example,

In the below program, when the main function calls addNumbers, then “main” is paused and
addNumbers starts.

The addNumbers calculate the sum of the number from 1 to 100 and when control reaches to the
statement return sum; then terminate the execution of addNumbers and control is transferred back
to the main function.

#include <stdio.h>
//Add 1 to 100
int addNumbers(void)
{
int sum = 0;
int mumber = 0;
for(mumber = 1; mumber <= 100; ++mumber)
{
sum += mumber;
}
return sum;
}
//Main function
int main(int argc, char *argv[])
{
int sum =0;
//calling addNumbers
sum = addNumbers();
printf("%d\n", sum);
return 0;
}
STRINGS: A string is a sequence of characters terminated with a null character \0. A group of
characters enclosed in double quotes is known as a string constant.

 Some of the examples of string constants are:


1)“hai”

2) “hello world”

3) “My name is NITHIN”

In C programming, there is no predefined data type to declare and use strings. So, we use
character arrays to declare strings in C programs.
Example: char s[5];

a) String Declaration & Initialization: we should declare strings before using them in
the program. Strings are implemented as character arrays.
Syntax: char string_name[size];
Example: char student_name[26];
When the compiler assigns a character string to a character array, it appends a ‘\0’ to the end of
the array. So, the size of the character array should always be number of characters plus 1.
Character arrays can also be initialized when they are declared. Some of the examples for
initializing the string are as shown below:
1) char name[13] = {‘N’,’I’,’T’,’H’,’I’,’N’,’’,’K’,’U’,’M’,’A’,’R’,’\0’};
2) char name[13] = “NITHIN KUMAR”;
If less number of characters are provided than the size of the string, the rest of the characters are
initialized to ‘\0’.

b) Reading & Writing Strings: There are two ways read & write the strings
1) Formatted input/output – scanf & printf
2) Unformatted input/output – gets & puts

 Syntax for formatted input/output:


1) Read – char str[10];
scanf(“%s”, str);
2) Print – printf(“The string is %s”, str);

 Syntax for unformatted input/output:


1) Read – char str[10];
gets(str); //gets(string_name);
2) Print – printf(“The string is:”);
puts(str); //puts(string_name);

 Example C program to Read & Print Strings:


/*Using scanf & printf*/

#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
}
/*Using gets & puts*/

#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
gets(name);
printf("Name: ");
puts(name);
}

EXAMPLE PROGRAMS TO BE PREPARED FROM STRINGS:


 C program to find whether the given string is palindrome or not.
#include <stdio.h>
#include <string.h>
void main()
{
char str[100];
int i, len, flag;
flag = 0;
printf("Enter any String : ");
scanf(“%s”, str);
len = strlen(str);
for(i = 0; i < len; i++)
{
if(str[i] != str[len - i - 1])
{
flag = 1;
break;
}
}
if(flag == 0)
{
printf("String is a Palindrome String");
}
else
{
printf("String is Not a Palindrome String");
}
}
 C program to print String Length without Built-in function
#include<stdio.h>
#include<string.h>
int my_strlen(char[]);
void main()
{
int len;
char str[26]];
printf("Enter String:");
scanf("%s",str);
len=my_strlen(str);
printf("Length is %d",len);
}
int my_strlen(char str1[])
{
int i=0;
while(str1[i] != '\0')
{
i++;
}
return i;
}
 C program to Compare two String’s without Built-in function
#include<stdio.h>
#include<string.h>
int my_strcmp(char[],char[]);
void main()
{
int comp;
char str1[26], char str2[26];
printf("Enter Strings:");
scanf("%s %s",str1,str2);
comp=my_strcmp(str1,str2);
if(comp==0)
{
printf("Both are equal");
}
else if(comp>0)
{
printf(“String-1 is greater”);
}
else
{
printf(“String-2 is greater”);
}
int my_strcmp(char str1[],char str2[])
{
int i=0;
while(str1[i]==str2[i])
{
if(str1[i]=='\0')
{
break;
}
i++;
}
return str1[i]-str2[i];
}
C program to convert upper to lower case

#include<string.h>
void main()
{
char str[50];
int i;
printf("Enter any string which is to be converted to uppercase\n");
gets(str);
for(i=0; str[i]!=0;i++)
{
if(str[i]>='a' && str[i]<='z')
{
str[i]=str[i]_+ 32;
}
}
printf("\nThe string in UpperCase is\n");
printf("%s",str);
}

C program to convert upper to lower case

#include<string.h>
void main()
{
char str[50];
int i;
printf("Enter any string which is to be converted to uppercase\n");
gets(str);
for(i=0; str[i]!=0;i++)
{
if(str[i]>='a' && str[i]<='z')
{
str[i]=str[i]_- 32;
}
}
printf("\nThe string in UpperCase is\n");
printf("%s",str);
}
 C program to concate two String’s without Built-in function

#include <stdio.h>
int main()
{
char str1[100];
char str3[100];
char str2[100];
int i, k=0,j;

printf("Enter 1st string: ");


gets(str1);
printf("Enter 2nd string: ");
gets(str2);
/* Copy text1 to text2 character by character */
for(i=0; str1[i]!='\0'; i++)
{
str3[k] = str1[i];
k++;
}

for(j=0; str2[j]!='\0'; j++)


{
str3[k] = str2[j];
k++;
}
printf("value = %s\n", str3);

You might also like