0% found this document useful (0 votes)
8 views19 pages

Ppsch3 Word

The document provides an overview of strings in C, explaining their representation as character arrays and the importance of the null character for termination. It covers string declaration, initialization methods, built-in string functions, and the differences between call by value and call by reference in function parameters. Additionally, it discusses function pointers and their usage in C programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views19 pages

Ppsch3 Word

The document provides an overview of strings in C, explaining their representation as character arrays and the importance of the null character for termination. It covers string declaration, initialization methods, built-in string functions, and the differences between call by value and call by reference in function parameters. Additionally, it discusses function pointers and their usage in C programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

String Basics:

Strings in C are represented by arrays of characters.

String is a one-dimensional array of char type, with the last character in


the array being a "null character" represented by '\0'.

String is a sequence/collection of characters terminated with a null


character \0.

Purpose: Strings are used for storing text/characters.

String Basics - String Declaration and Initialization:

String Declaration Syntax: char string_name[size_of_string];

Ex: char str[6];

String Basics - String Declaration and Initialization:

String Initialization: 4 different ways:

Assigning a string literal without size char str[ ] = "SRMIST";

Assigning character by character with size

char str[7] = { 'S','R','M','I','S','T','\0'};

Assigning a String Literal with a Predefined Size

String literals can be assigned with a predefined size.


char str[50] = "SRMIST";

Assigning Character by Character without Size

We can assign character by character without size with the NULL


character at the end. The size of the string is determined by the compiler
automatically.

char str[ ] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

STRING BASICS:

Strings in C are represented by arrays of characters.

String is nothing but the collection of the individual array elements or


characters stored at contiguous memory locations

i) Character array -- 'P','P','S'

ii) Double quotes - "PPS" is a example of String.

-- If string contains the double quote as part of string then we can use
escape character to keep double quote as a part of string.

Null Character:

The end of the string is marked with a special character, the null
character, which is a character all of whose bits are zero i.e., a NULL.

String always Terminated with NULL Character ('\0′)

*char name[10] = {'P','P','S','\0'}*

NULL Character is having ASCII value 0


ASCII Value of '\0' = 0

As String is nothing but an array , so it is Possible to Access Individual


Character

*name[10] = "PPS";*

− It is possible to access individual character

*name[0] = 'P';*

*name[1] = 'P';*

*name[2] = 'S';*

*name[3] = '\0';*

MEMORY:

Each Character Occupy 1 byte of Memory Size of "PPS" = Size of 'P' + Size
of 'P' + Size of 'S' ;

Size of "PPS" is 3 BYTES

Each Character is stored in consecutive memory location. Address of 'P' =


2000

Address of 'P' = 2001

Address of 'S' = 2002

String Functions:

gets()

puts()

getchar()
putchar()

Printf()

String Input/Output Functions:

gets( ) - Reads a string from the keyboard (input) -- scanf( )

puts( ) - Writes a string to the screen (output) -- printf( )

Reading string using gets():

The gets() and puts() are declared in the header file stdio.h.

Both the functions are involved in the input/output operations of the


strings.

Reading string using gets():

#include<stdio.h>

void main ()

char s[30];

printf("Enter the string? ");

gets(s);

printf("You entered %s",s);

getchar( ) - Read a single character using the getchar() function


putchar( ) - Writes a character to the screen.

Built-in String Functions:

atoi

strlen

strcat

strcmp

Built-in String Functions:

strlen( ) - The strlen( ) function returns the length of the given string. It
doesn't count null character '\0'.

strcpy( ) - strcpy(s2, s1) : copy one string to another.

The strcpy(destination-s2, source-s1) function copies source string into


destination string.

strcat( ) - strcat(first_string, second_string)

strstr( ) - Find a substring in the string.

const char str[20] = "Hello, how are you?";

const char searchString[10] = "you";

char *result;
result = strstr(str, searchString);

printf("The substring is : %s", result);

strcmp( )

The strcmp() compares two strings character by character. If the strings


are equal, the function returns 0.

Return Value from strcmp()

Return Value Remarks

0 if strings are equal

> 0 if the first non-matching character in str1 is greater (in ASCII) than
that of str2.

< 0 if the first non-matching character in str1 is lower (in ASCII) than that
of str2.

#include <stdio.h>

#include <string.h>

int main()

char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";

int result;

result = strcmp(str1, str2);

printf("strcmp(str1, str2) = %d\n", result);

result = strcmp(str1, str3);

printf("strcmp(str1, str3) = %d\n", result);


return 0;

strcmp(str1, str2) = 32

strcmp(str1, str3) = 0

strings str1 and str2 are not equal. Hence, the result is a non-zero integer.

strings str1 and str3 are equal. Hence, the result is 0.

strrev( )

#include<stdio.h>

#include <string.h>

int main(){

char str[20];

printf("Enter string: ");

gets(str);//reads string from console

printf("String is: %s",str);

printf("\nReverse String is: %s", strrev(str));

return 0;

Built-in String Functions

atoi

The atoi() function converts a character string to an integer value. The


input string is a sequence of characters that can be interpreted as a
numeric value of the specified return type. The function stops reading the
input string at the first character that it cannot recognize as part of a
number.

Syntax:

int atoi(const char *str)

Where

str- String passed to the function

Return value:

If str is a valid input, the function returns the integer number equal to the
passed string number. If str has no valid input, the functions return zero
value.

#include <stdio.h>

#include <string.h>

int main ()

char string[55] ="This is a test string";

char *p;

p = strstr (string, "test");

if(p)

printf("string found\n");

else

printf("string not found\n" );

return 0;

Output: string found

sscanf() Function in C:
The full form of sscanf is String Scan Formatted.

scanf and sscanf are both C standard library functions used for formatted
input, but they differ in their source of input.

scanf: This function reads formatted input from the standard input stream
(stdin), which is typically the keyboard or a redirected file.

sscanf: This function reads formatted input from a character string (a char
array) provided as an argument.

Functions declaration and definition

Define Function

Describe Modular Programming

Function Types

Function declaration

Function Definition

Function Calling

Types of Arguments /Parameters

Types of function definition

Defining a Function
A function is an independent part of the program, and can perform a
specific tasks.

A function is a block of code that performs a specific task.

We can divide a large program into the basic building blocks known as
function. The function contains the set of programming statements
enclosed by { }.

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.

Function Types:

Two types of functions are as follow:

Library Functions: are the functions which are declared in the C header
files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.

User-defined functions: are the functions which are created by the C


programmer, so that he/she can use it many times. It reduces the
complexity of a big program and optimizes the code.

Example: User-defined function

Here is an example to add two integers.

To perform this task, we have created an user-defined addNumbers().

Function Prototype Declaration:


A function prototype is simply the declaration of a function that specifies
function's name, parameters and return type. It doesn't contain function
body.

A function prototype gives information to the compiler that the function


may later be used in the program.

Syntax of Function Prototype:

returnType functionName(type1 argument1, type2 argument2, ...);

Example: int addNumbers(int a, int b);

Any function (library or user-defined) has 3 things:

Function declaration

Function calling

Function definition

Function Calling: Function can be called from anywhere in the program.

Syntax: function_name(param_list);

a. Formal Parameters:

Parameter Written in Function Declaration or Function Definition.

b. Actual Parameters:

Parameter Written in Function Call.


Function Declaration:

Syntax:

return data_type function_name(argument list);

Function Definition:

Syntax:

return data_type function_name(argument list) // Function Header

body; // Function Body

Return Value

A C function may or may not return a value from the function. If you don't
have to return any value from the function, use void for the return type.

Example without return value:

void hello()

printf("hello c");

Different aspects of function calling

A function may or may not accept any argument. It may or may not return
any value. Based on these facts, There are four different aspects of
function calls.

function without arguments and without return value


function without arguments and with return value

function with arguments and without return value

function with arguments and with return value

Functions with no arguments and no return value

Functions with no arguments and a return value:

Functions with arguments and no return value

Functions with arguments and a return value

Program 2: program to calculate the average of five numbers.

#include<stdio.h>

void average(int, int, int, int, int);

void main( )

int a,b,c,d,e;

printf("\nGoing to calculate the average of five numbers:");

printf("\nEnter five numbers:");

scanf("%d %d %d %d %d", &a,&b,&c,&d,&e);

average(a,b,c,d,e);

void average(int a, int b, int c, int d, int e)

{
int avg;

avg = (a+b+c+d+e)/5;

printf("The average of given five numbers : %d", avg);

Pass arrays to a function in C: Pass Individual Array Elements

#include <stdio.h>

void display(int age1, int age2)

printf("%d\n", age1);

printf("%d\n", age2);

int main( ) {

int ageArray[] = {2, 8, 4, 12};

display(ageArray[1], ageArray[2]); // pass second and third elements to


display( )

return 0;

Difference Between Call by Value and Call by Reference:

Functions can be invoked (call) in two ways:

Call by Value or Call by Reference

These two ways are generally differentiated by the type of values passed
to them as parameters.

The parameters passed to the function are called actual parameters


whereas
the parameters received by the function are called formal parameters.

Call By Value:

In call by value method of parameter passing,

the values of actual parameters are copied to the function's formal


parameters.

// C program to illustrate call by value:

#include <stdio.h>

// Function Prototype

void swapx(int x, int y);

int main()

int a = 10, b = 20;

// Pass by Values

swapx(a, b); // Actual Parameters

printf("In the Caller:\n a = %d b = %d\n", a, b);

return 0;

// Swap functions that swaps two values

void swapx(int x, int y) // Formal Parameters

int t;
t = x;

x = y;

y = t;

printf("Inside Function:\nx = %d y = %d\n", x, y);

Thus actual values of a and b remain unchanged even after exchanging


the values of x and y in the function.

Output:

Inside Function:

x = 20 y = 10

In the Caller: a = 10 b = 20

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.

#include <stdio.h>

// Function Prototype

void swapx(int*, int*);

int main()

int a = 10, b = 20;

// Pass reference

swapx(&a, &b); // Actual Parameters

printf("Inside the Caller:\na = %d b = %d\n", a, b);


return 0;

// Function to swap two variables by references

void swapx(int* x, int* y) // Formal Parameters

int t;

t = *x;

*x = *y;

*y = t;

printf("Inside the Function:\nx = %d y = %d\n", *x, *y);

Output:

Inside the Function:

x = 20 y = 10

Inside the Caller:

a = 20 b = 10

Function Pointer:

We can create a pointer of any data type such as int, char, float, we can
also create a pointer pointing to a function. The code of a function always
resides in memory, which means that the function has some address. We
can get the address of memory by using the function pointer.

#include <stdio.h>

int main( )

printf("Address of main() function is %p", main);


return 0;

Declaration of a function pointer

Syntax of function pointer

return type (ptr_name)(type1, type2...);*

For example:

int (ip) (int);*

In the above declaration, ip is a pointer that points to a function which


returns an int value and accepts an integer value as an argument.

float (fp) (float);

In the above declaration, *fp is a pointer that points to a function that


returns a float value and accepts a float value as an argument.

float (fp) (int , int);* // Declaration of a function pointer.

float func( int , int ); // Declaration of function.

fp = func; // Assigning address of func to the fp pointer.

In the above declaration, 'fp' pointer contains the address of the 'func'
function.

Passing Function Pointer as an argument

#include<stdio.h>

void fun1(void(*test)())

int a=20;

test(a);

void test(int a)

{
printf("a=%d\n",a);

void main()

fun1(&test);

THANK YOU

You might also like