This document provides an overview of string handling functions in C programming. It discusses how to declare strings, compare strings, concatenate strings, copy strings, and manipulate strings using pre-defined functions from the string.h header file. Examples are given for common string functions like strlen(), strcmp(), strcpy(), strcat(), etc. to illustrate how each function works and what it returns.
String handling functions in C allow programmers to manipulate string data more easily. Some key string handling functions include strlen() to return the length of a string, strcpy() to copy one string to another, strcmp() to compare two strings, strcat() to concatenate strings, and strrev() to reverse a string. These functions take string arguments and perform operations like copying, comparing, concatenating, and reversing to manipulate string data. Examples are provided to demonstrate how each function works.
1) A string is a one-dimensional array of characters terminated by a null character. Strings are declared using char arrays or string literals.
2) There are two ways to declare and initialize strings in C: using a char array and specifying the size, or using a string literal which automatically inserts a null terminator.
3) Common string functions include strlen() to return the length, strcpy() to copy one string to another, strcat() to concatenate strings, and strcmp() to compare two strings.
The document provides information on strings in C programming language. It discusses that strings are arrays of characters terminated by a null character. It shows examples of declaring and initializing strings, reading strings from users, and printing strings. It also provides examples of using standard string functions like strcpy(), strcat(), strlen() etc. Further examples demonstrate finding frequency of characters in a string, counting vowels, consonants, digits and whitespaces, and removing non-alphabet characters from a string.
This document discusses C strings and functions for manipulating strings. It explains that in C, a string is an array of characters terminated with a null character. It describes different ways to declare and initialize strings. Functions like strcpy(), strcat(), strlen() from the string.h library are used to copy, concatenate and find the length of strings. The document also demonstrates how to read strings from the user using scanf() and fgets(), and how to traverse strings using a loop until the null character is reached.
This document discusses C string functions. It defines a string as an array of characters terminated with a null character. It notes that the standard library contains many built-in string handling functions in the string.h header file to manipulate strings. Some functions discussed include strlen() to return the length of a string, strrev() to reverse a string, strdup() to duplicate a string, strlwr() to convert a string to lowercase, and strupr() to convert a string to uppercase. Code examples are provided to demonstrate the use of these functions.
The document discusses various topics related to arrays, strings, and string handling functions in C programming language. It explains that arrays are collections of variables of the same type that can be accessed using indexes. One-dimensional and multi-dimensional arrays are declared along with examples. Common string functions like strlen(), strcpy(), strcat() etc. are described with examples to manipulate strings in C. Pointers and their usage with arrays and strings are also covered briefly.
This document provides an introduction to strings in C programming, including defining strings as character arrays, initializing strings, inputting and outputting strings, and pointers and strings. It also covers common string library functions like strlen(), strcpy(), strcat(), strcmp(), and strrev(). Finally, it includes examples of basic string programs demonstrating the use of these functions.
The document discusses strings in C programming language. It provides details about:
- Strings are arrays of characters terminated by a null character '\0'.
- Common functions to declare, initialize, print and manipulate strings like strlen(), strcpy(), strcat(), strcmp() etc.
- Important points about receiving and processing multi-word strings using scanf(), gets() and puts().
- Implementation of some string handling functions like xstrlen(), xstrcpy() to demonstrate their working.
This document provides information about strings in C++. It defines a string as a collection of characters within double quotes. Strings are stored as character arrays terminated by a null character. The document discusses declaring and initializing strings, inputting strings from the user, and functions for manipulating strings like strcat(), strcmp(), and memcpy(). It also covers arrays of strings and comparing, concatenating, copying and other operations on strings.
The document discusses strings in C programming. It defines strings as sequences of characters stored as character arrays that are terminated with a null character. It covers string literals, declaring and initializing string variables, reading and writing strings, and common string manipulation functions like strlen(), strcpy(), strcmp(), and strcat(). These functions allow operations on strings like getting the length, copying strings, comparing strings, and concatenating strings.
This document discusses C strings and string functions. It defines a C string as a sequence of characters terminated with a null character. Strings are stored as character arrays. It provides examples of declaring, initializing, reading, and passing strings. It also describes common string functions like strcpy(), strcat(), strcmp(), strlen() for copying, concatenating, comparing, and getting the length of strings.
This document provides an overview of standard C library functions for handling strings and characters. It discusses functions for string input/output, conversion, manipulation, comparison, searching, and memory operations. Examples are given to demonstrate the use of functions like strcpy(), strcmp(), strtok(), memmove(), and strerror(). The document is intended to introduce common string and memory handling techniques used in applications like word processors, layout software, and typesetting programs.
Unit III discusses strings in C programming. Strings are represented as arrays of characters that are stored in contiguous memory locations. Common string functions like gets(), puts(), printf() are explained. gets() accepts a string from the user and puts() displays a string. printf() can display strings with format specifiers. The atoi() function converts a string to an integer.
This document contains information about strings in C programming language. It defines strings as arrays of characters terminated by a null character. It discusses different ways to declare and initialize string variables including using character arrays and pointers. It also covers common string handling functions like strcat(), strcpy(), strlen(), strcmp(), strcmpi() which are used for string manipulation. Examples are given to demonstrate the use of these functions. The document also discusses pointers in C and provides examples of pointer declaration, initialization, dereferencing and using pointers to access structure members.
This document discusses strings in C programming. It defines strings as arrays of characters that end with a null terminator (\0). It explains how to initialize and print strings. Common string functions like strlen(), strcpy(), strcat(), and strcmp() are described. The document contrasts strings and character pointers, noting strings cannot be reassigned while pointers can. Finally, it lists and briefly explains other standard string library functions.
02 of 03 parts
Get Part 1 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-1
Get Part 3 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-3
C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to PLCs and embedded system.
This document discusses strings in C programming. It defines strings as arrays of characters terminated with a null character. It describes four methods of initializing strings: assigning a string literal with or without size, assigning characters individually with size, and assigning characters individually without size. It also covers string functions like strlen(), strcpy(), strcat(), and strcmp() to get the length, copy, concatenate, and compare strings. Finally, it discusses string arrays as two-dimensional character arrays where each string is terminated with a null character. An example program is provided to print an array of strings.
This document contains information about strings in C programming including how they are represented in memory, standard string functions like strlen(), strcpy(), strcmp(), etc. It also provides examples of using these string functions. The document discusses arrays of pointers as an alternative to 2D character arrays for storing strings to avoid memory wastage. It includes questions and answers related to strings and structures.
An array is a collection of similar data types stored in contiguous memory locations. Arrays in C can store primitive data types like int, char, float, etc. Elements of an array are accessed using indexes and they are stored sequentially in memory. Strings in C are arrays of characters terminated by a null character. Common functions to manipulate strings include strlen(), strcpy(), strcat(), strcmp(), strrev(), strlwr(), and strupr().
This document discusses C string functions. It defines a string as an array of characters terminated with a null character. It notes that the standard library contains many built-in string handling functions in the string.h header file to manipulate strings. Some functions discussed include strlen() to return the length of a string, strrev() to reverse a string, strdup() to duplicate a string, strlwr() to convert a string to lowercase, and strupr() to convert a string to uppercase. Code examples are provided to demonstrate the use of these functions.
The document discusses various topics related to arrays, strings, and string handling functions in C programming language. It explains that arrays are collections of variables of the same type that can be accessed using indexes. One-dimensional and multi-dimensional arrays are declared along with examples. Common string functions like strlen(), strcpy(), strcat() etc. are described with examples to manipulate strings in C. Pointers and their usage with arrays and strings are also covered briefly.
This document provides an introduction to strings in C programming, including defining strings as character arrays, initializing strings, inputting and outputting strings, and pointers and strings. It also covers common string library functions like strlen(), strcpy(), strcat(), strcmp(), and strrev(). Finally, it includes examples of basic string programs demonstrating the use of these functions.
The document discusses strings in C programming language. It provides details about:
- Strings are arrays of characters terminated by a null character '\0'.
- Common functions to declare, initialize, print and manipulate strings like strlen(), strcpy(), strcat(), strcmp() etc.
- Important points about receiving and processing multi-word strings using scanf(), gets() and puts().
- Implementation of some string handling functions like xstrlen(), xstrcpy() to demonstrate their working.
This document provides information about strings in C++. It defines a string as a collection of characters within double quotes. Strings are stored as character arrays terminated by a null character. The document discusses declaring and initializing strings, inputting strings from the user, and functions for manipulating strings like strcat(), strcmp(), and memcpy(). It also covers arrays of strings and comparing, concatenating, copying and other operations on strings.
The document discusses strings in C programming. It defines strings as sequences of characters stored as character arrays that are terminated with a null character. It covers string literals, declaring and initializing string variables, reading and writing strings, and common string manipulation functions like strlen(), strcpy(), strcmp(), and strcat(). These functions allow operations on strings like getting the length, copying strings, comparing strings, and concatenating strings.
This document discusses C strings and string functions. It defines a C string as a sequence of characters terminated with a null character. Strings are stored as character arrays. It provides examples of declaring, initializing, reading, and passing strings. It also describes common string functions like strcpy(), strcat(), strcmp(), strlen() for copying, concatenating, comparing, and getting the length of strings.
This document provides an overview of standard C library functions for handling strings and characters. It discusses functions for string input/output, conversion, manipulation, comparison, searching, and memory operations. Examples are given to demonstrate the use of functions like strcpy(), strcmp(), strtok(), memmove(), and strerror(). The document is intended to introduce common string and memory handling techniques used in applications like word processors, layout software, and typesetting programs.
Unit III discusses strings in C programming. Strings are represented as arrays of characters that are stored in contiguous memory locations. Common string functions like gets(), puts(), printf() are explained. gets() accepts a string from the user and puts() displays a string. printf() can display strings with format specifiers. The atoi() function converts a string to an integer.
This document contains information about strings in C programming language. It defines strings as arrays of characters terminated by a null character. It discusses different ways to declare and initialize string variables including using character arrays and pointers. It also covers common string handling functions like strcat(), strcpy(), strlen(), strcmp(), strcmpi() which are used for string manipulation. Examples are given to demonstrate the use of these functions. The document also discusses pointers in C and provides examples of pointer declaration, initialization, dereferencing and using pointers to access structure members.
This document discusses strings in C programming. It defines strings as arrays of characters that end with a null terminator (\0). It explains how to initialize and print strings. Common string functions like strlen(), strcpy(), strcat(), and strcmp() are described. The document contrasts strings and character pointers, noting strings cannot be reassigned while pointers can. Finally, it lists and briefly explains other standard string library functions.
02 of 03 parts
Get Part 1 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-1
Get Part 3 from /ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-3
C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to PLCs and embedded system.
This document discusses strings in C programming. It defines strings as arrays of characters terminated with a null character. It describes four methods of initializing strings: assigning a string literal with or without size, assigning characters individually with size, and assigning characters individually without size. It also covers string functions like strlen(), strcpy(), strcat(), and strcmp() to get the length, copy, concatenate, and compare strings. Finally, it discusses string arrays as two-dimensional character arrays where each string is terminated with a null character. An example program is provided to print an array of strings.
This document contains information about strings in C programming including how they are represented in memory, standard string functions like strlen(), strcpy(), strcmp(), etc. It also provides examples of using these string functions. The document discusses arrays of pointers as an alternative to 2D character arrays for storing strings to avoid memory wastage. It includes questions and answers related to strings and structures.
An array is a collection of similar data types stored in contiguous memory locations. Arrays in C can store primitive data types like int, char, float, etc. Elements of an array are accessed using indexes and they are stored sequentially in memory. Strings in C are arrays of characters terminated by a null character. Common functions to manipulate strings include strlen(), strcpy(), strcat(), strcmp(), strrev(), strlwr(), and strupr().
PROJECT REPORT ON PASTA MACHINE - KP AUTOMATIONS - PASTA MAKING MACHINE PROJE...yadavchandan322
油
All the materials and content contained in Project report is for educational purpose and reflect the views of the industry which are drawn from various research on pasta machine. PM FME- Detailed Project Report of Multigrain Pasta Making Unit. 3. 1. PROJECT ... A pasta extruder is a machine that makes pasta dough through dies to.The process is quite simple and requires not much skilled labour. The machine itself is high technology and provides the manufacturers to produce noodles with. In this article, you will be able to get all the detail about a pasta-making business unit in India and the financial status of this business as well.ENGINEERS INDIA RESEARCH INSTITUTE - Service Provider of Project Report on PASTA PRODUCTION PLANT (SHORT PASTA) [CODE NO. 1632] based in Delhi, India.
Macaroni Machines are used to produce pasta from the raw material. With ... The views expressed in this Project Report are advisory in nature. SAMADHAN.
Distributed System Models and Enabling Technologies: Scalable Computing Over the
Internet, Technologies for Network Based Systems, System Models for Distributed and
Cloud Computing, Software Environments for Distributed Systems and Clouds,
Performance, Security and Energy Efficiency.
Shaping Skylines- The Evolution of Real Estate Development and the Vision of ...josephmigliorini1
油
Real estate development has long been a cornerstone of economic growth, community formation, and urban transformation. At its best, it fuses design, functionality, and vision to bring vibrant spaces to life. As cities expand and populations shift, the role of a real estate developer evolves from simply constructing buildings to reimagining how people live, work, and connect. Among those leading this evolution is Joe Migliorini, a seasoned developer whose work embodies both innovation and integrity.
Virtual Power plants-Cleantech-RevolutionAshoka Saket
油
VPPs are virtual aggregations of distributed energy resources, such as energy storage, solar panels, and wind turbines, that can be controlled and optimized in real-time to provide grid services.
power system protection and why to protect the systemDivyangBhatt6
油
Power system protection is a crucial aspect of electrical engineering that ensures the safety and reliability of power networks. It involves detecting faults, isolating faulty sections, and minimizing damage using relays, circuit breakers, and protective devices. Proper protection prevents equipment failures, enhances system stability, and ensures continuous power supply.
Reinventando el CD_ Unificando Aplicaciones e Infraestructura con Crossplane-...Alberto Lorenzo
油
En esta charla, exploraremos c坦mo Crossplane puede transformar la forma en que gestionamos despliegues, yendo m叩s all叩 de un simple IaC para convertirse en una potente herramienta de Continuous Deployment (CD).
Aprenderemos que es Crossplane
Como usar Crossplane como IaC pero sobretodo Deployment as Code de manera eficiente
Unificar la gesti坦n de aplicaciones e infraestructura de forma nativa en Kubernetes
Industry 4.0: Transforming Modern Manufacturing and BeyondGtxDriver
油
This document explores the fundamental concepts, technologies, and applications of Industry 4.0. Topics include automation, IoT (Internet of Things), smart factories, cyber-physical systems, and the integration of AI and big data analytics in industrial processes. It serves as a comprehensive resource for students, professionals, and enthusiasts eager to delve into the fourth industrial revolution.
Industry 4.0: Transforming Modern Manufacturing and BeyondGtxDriver
油
Principals of Programming in CModule -5.pdfModule-4.pdf
1. Module 4
Strings
Strings are defined as an array of characters. The difference
between a character array and a string is the string is terminated
with a special character 0.
2. Declaration of strings: Declaring a string is as simple as declaring a
one-dimensional array. Below is the basic syntax for declaring a string.
char str_name[size];
In the above syntax str_name is any name given to the string variable
and size is used to define the length of the string, i.e the number of
characters strings will store. Please keep in mind that there is an extra
terminating character which is the Null character (0) used to indicate
the termination of string which differs strings from normal character
arrays.
3. Initializing a String:
// C program to illustrate strings
#include<stdio.h>
int main()
{
// declare and initialize string
char str[] = "cmrit";
// print string
printf("%s",str);
return 0;
}
4. // C program to see how scanf() stops reading input after whitespaces
#include <stdio.h>
int main()
{
char str[20];
printf("enter somethingn");
scanf("%s", str);
printf("you entered: %sn", str);
return 0;
}
Here the input will be provided by the user and output will be as
follows:
Input: Computer science
Output: Computer
5. gets()
It is used to read input from the standard input(keyboard).
It is used to read the input until it encounters newline or End Of File(EOF).
// C program to show how gets() takes whitespace as a string.
#include <stdio.h>
int main()
{
char str[20];
printf("enter somethingn");
gets(str);
printf("you entered : %sn", str);
return 0;
}
Here input will be provided by user as follows
Input: Computer science
Output: Computer science
6. C program to show how to read entire string using scanf()
#include <stdio.h>
int main()
{
char str[20];
printf("Enter somethingn");
// Here n indicates that take the input
// until newline is encountered
scanf("%[^n]s", str);
printf("%s", str);
return 0;
}
The above code reads the string until it encounters newline.
Examples:
Input: Computer science
Output: Computer science
10. // C program to illustrate how to pass string to functions
#include<stdio.h>
void printStr(char str[])
{
printf("String is : %s",str);
}
int main()
{
// declare and initialize string
char str[] = "cmrit bangalore";
// print string by passing string
// to a different function
printStr(str);
return 0;
}
11. String Handling Functions
in C
These String functions are:
1. strlen().
2. strupr().
3. strlwr().
4. strcmp().
5. strcat().
6. strcpy().
7. strrev().
12. strlen()
size_t strlen(const char *str);
The function takes a single argument, i.e, the string variable whose
length is to be found, and returns the length of the string passed.
The strlen() function is defined in <string.h> header file
13. #include <stdio.h>
strlen()
#include <string.h>
int main()
{
char a*20+=Program
char b*20+=,P,r,o,g,r,a,m,0-;
char c[20];
printf(Enter string: );
gets(c);
printf(Length of string a = %d n, strlen(a));
printf(Length of string b = %d n, strlen(b));
printf(Length of string c = %d n, strlen(c));
return 0;}
14. strupr()
strupr() function convertsa given string into uppercase. Syntax
for strupr( ) functionis given below.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "Modify This String To Upper";
printf("%sn",strupr(str));
return 0;
}
Output: MODIFY THIS STRING TO UPPER
15. strlwr()
strlwr( ) function converts a given string into lowercase. Syntax for
strlwr( ) function is given below.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "MODIFY This String To LOwer";
printf("%sn",strlwr (str));
return 0;
}
OUTPUT: modify this string to lower
16. strcmp()
strcmp( ) function in C compares two given strings and returns zero if
they are same.
#include <stdio.h>
#include <string.h>
int main( )
{char str1[ ] = "fresh" ;
char str2[ ] = "refresh" ;
int i, j, k ;
i = strcmp ( str1, "fresh" ) ;
j = strcmp ( str1, str2 ) ;
k = strcmp ( str1, "f" ) ;
printf ( "n%d %d %d", i, j, k ) ;return 0;}
17. strcat()
strcat( ) function in C language concatenates two given strings. It
concatenates source string at the end of destinationstring.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = " fresh2refresh" ;
char target[ ]= " C tutorial" ;
printf ( "nSource string = %s", source ) ;
printf ( "nTarget string = %s", target ) ;
strcat ( target, source ) ;
printf ( "nTarget string after strcat( ) = %s", target ) ;}
18. strcpy()
strcpy( ) function copies contents of one string into another string
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
printf ( "nsource string = %s", source ) ;
printf ( "ntarget string = %s", target ) ;
strcpy ( target, source ) ;
printf ( "ntarget string after strcpy( ) = %s", target ) ;
return 0;
}
19. strrev()
strrev( ) function reverses a given string in C language
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = "Hello";
printf("String before strrev( ) : %sn",name);
printf("String after strrev( ) : %s",strrev(name));
return 0;
}
20. Arrays of strings
A string is a 1-D array of characters, so an array of strings is a 2-D
array of characters.
Just like we can create a 2-D array of int, float etc; we canalso
create a 2-D array of character or array of strings.
Here is how we can declare a 2-D array of characters.
char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '0'},
{'t', 'o', 'm','0'},
{'j', 'e', 'r', 'r', 'y','0'}
};
21. It is important to end each 1-D array by the null character
otherwise, it's just an array of characters. We can't use them as
strings.
Declaring an array of string this way is a tedious and error-prone
process that's why C provides a more compact way to it. This above
initialization is equivalentto:
char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};
22. The following program demonstrates how to print an array
of strings.
#include<stdio.h>
int main()
{
int i;
char ch_arr[3][10] = {"spike","tom","jerry"};
printf("1st way nn");
for(i = 0; i < 3; i++)
{
printf("string = %s t address = %un", ch_arr + i, ch_arr + i);
}
signal to operating system program ran fine return 0;
}
24. C String function strlen
Syntax:
size_t strlen(const char *str)
size_t represents unsigned short
It returns the length of the string without including end character (terminating
char 0).
Example of strlen:
#include <stdio.h>
#include <string.h> int
main()
{
char str1[20] = "be happy";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Output:
Length of string str1: 8
25. strlen vs sizeof
strlen returns you the length of the string stored in array, however sizeof returns
the total allocated size assigned to the array. So if I consider the above example
again then the following statements would return the below values.
strlen(str1) returned value 13.
sizeof(str1) would return value 20 as the array size is 20
26. C String function strcmp
int strcmp(const char *str1, const char *str2)
It compares the two strings and returns an integer value. If both the
strings are same (equal) then this function would return 0 otherwise it
may return a negative or positive value based on the comparison.
If string1 < string2 OR string1 is a substring of string2 then it would
result in a negative value. If string1 > string2 then it would return
positive value.
If string1 == string2 then you would get 0(zero) when you use this
function for compare strings.
27. Example of strcmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "bangalore";
char s2[20] = "hyderabad";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
string 1 and 2 are different
28. C String function strcat
char *strcat(char *str1, char *str2)
It concatenates two strings and returns the concatenated string.
Example of strcat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:
Output string after concatenation: HelloWorld
29. C String function strcpy
char *strcpy( char *str1, char *str2)
It copies the string str2 into string str1, including the end character (terminator
char 0).
Example of strcpy:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : Im gonna copied into s1";
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:
String s1 is: string 2: Im gonna copied into s1
30. Passing string to Function
C program to pass a string to a function
#include <stdio.h>
void Strfun(char *ptr)
{
printf("The String is : %s",ptr);
}
// main function
int main()
{
// Declare a buffer of type "char"
char buff[20]="Hello Function";
// Passing string to Function
Strfun(buff);
return 0;
}
31. Passing string to Function
C program to pass a string to a function
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
32. String Manipulation without using built-in function
(Using user defined function)
Calculate string length
#include <stdio.h>
/*function to return length of the string*/
int stringLength(char*);
int main()
{
char str[100]={0};
int length;
printf("Enter any string: ");
scanf("%s",str);
/*call the function*/
length=stringLength(str);
printf("String length is : %dn",length);
/*function definition...*/
int stringLength(char* txt)
{
int i=0,count=0;
while(txt[i++]!='0'){
count+=1;
}
return count;
}
return 0;
}
33. program to copy one string to another (implementation of strcpy) in C
#include <stdio.h>
void stringCpy(char* s1,char* s2);
int main()
{
char str1[100],str2[100];
printf("Enter string 1: ");
scanf("%[^n]s",str1);//read string with spaces
stringCpy(str2,str1);
printf("String 1: %s nString 2: %sn",str1,str2);
return 0;
}
/*** function definition **/
void stringCpy(char* s1,char* s2)
{
int i=0;
while(s2[i]!='0')
{
s1[i]=s2[i];
i++;
}
s1[i]='0'; /*string terminates by
NULL*/
}
34. C program to concatenate two strings without using library function
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
void stringCat (char *s1,char *s2);
int main()
{
char str1[MAX_SIZE],str2[MAX_SIZE];
printf("Enter string 1 : ");
scanf("%[^n]s",str1);//read string with spaces
getchar();//read enter after entering first string
printf("Enter string 2 : ");
scanf("%[^n]s",str2);//read string with spaces
stringCat(str1,str2);
printf("nAfter concatenate strings are :n");
printf("String 1: %s nString 2: %s",str1,str2);
printf("n");
return 0;
}
/*** function definition **/
void stringCat (char *s1,char *s2)
{
int len,i;
len=strlen(s1)+strlen(s2);
if(len>MAX_SIZE)
{
printf("nCan not Concatenate !!!");
return;
}
len=strlen(s1);
for(i=0;i< strlen(s2); i++)
{
s1[len+i]=s2[i];
}
s1[len+i]='0'; /* terminates by NULL*/
}
35. String comparison without using strcmp() function
#include <stdio.h>
int compare(char[],char[]);
int main()
{
char str1[20]; // declaration of char array
char str2[20]; // declaration of char array
printf("Enter the first string : ");
scanf("%s",str1);
printf("Enter the second string : ");
scanf("%s",str2);
int c= compare(str1,str2); // calling compare() function
if(c==0)
printf("strings are same");
else
printf("strings are not same");
return 0;
}
36. // Comparing both the strings.
int compare(char a[],char b[])
{
int flag=0,i=0; // integer variables declaration
while(a[i]!='0' &&b[i]!='0') // while loop
{
if(a[i]!=b[i])
{
flag=1;
break;
}
i++;
}
if(flag==0)
return 0;
else
return 1;
}
37. Given a string and we have to count digits, spaces, special characters and alphabets using
C program.
#include <stdio.h>
int main()
{
char str[100];
int countDigits, countAlphabet, countSpecialChar, countSpaces;
int counter;
//assign all counters to zero
countDigits = countAlphabet = countSpecialChar = countSpaces = 0;
printf("Enter a string: ");
gets(str);
39. Reverse a string without using library function
/*copy characters from last index of str and
#include <stdio.h>
#include <string.h>
int main()
{
store it from starting in revStr*/
j=0;
for(i=(strlen(str)-1); i>=0;i--)
revStr[j++]=str[i];
char str[100],revStr[100];
int i,j;
printf("Enter a string: ");
scanf("%[^n]s",str);//read string with
spaces
//assign NULL in the revStr
revStr[j]='0';
printf("nOriginal String is: %s",str);
printf("nReversed String is: %s",revStr);
return 0;
}
40. Pointer
A pointer is a variable whose value is the address of another
variable, i.e., direct address of the memory location. Like any
variable or constant, you must declare a pointer before using it to
store any variable address. The general form of a pointer variable
declaration is
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type
andvar-nameis the nameof the pointer variable.
41. Pointer
The asterisk * used to declare a pointer is the same
asterisk used for multiplication. However, in this
statement the asterisk is being used to designate a
variable as a pointer. Take a look at some of the valid
pointer declarations
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
42. Pointer
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x", ip );
/* access the value using the pointer */
printf("Value of var variable: %d", *ip );
return 0;
}
Output:
Address of var variable: bffd8b3c
Value of var variable: 20
43. NULL Pointers
It is always a good practice to assign a NULL value to a pointer
variable in case you do not have an exact address to be assigned.
This is done at the time of variable declaration. A pointer that is
assignedNULL iscaled anull pointer.
The NULL pointer is a constant with a value of zero defined in
several standard libraries. Consider the following program
#include <stdio.h>
int main () {
int *ptr ;
ptr=NULL;
printf("The value of ptr is : %xn", ptr );
return 0;
}
44. C dereference pointer
As we already know that "what is a pointer", a pointer is a variable
that stores the address of another variable. The dereference
operator is also known as an indirection operator, which is
represented by (*). When indirection operator (*) is used with the
pointer variable, then it is known as dereferencing a pointer.
When we dereference a pointer, then the value of the variable
pointed by this pointer will be returned.
Dereference apointer is used becauseof the following reasons:
It can be used to access or manipulate the data stored at the memory
location, which is pointed by the pointer.
Any operation applied to the dereferenced pointer will directly affect the
value of the variable that it points to.
45. Using Pointer concept Swap2 values( without usingthird Variable)
#include<stdio.h>
int main()
{
int a=10;
int b=20;
int *p, *q;
p=&a;
q=&b;
*p=*p+*q;
*q=*p-*q;
*p=*p-*q;
printf(after swapping
values of a=%d, b=%d, *p,
*q);
return 0;
}
46. Pointer Arithmetic in C with Examples
Pointers variables are also known as address data types because
they are used to store the address of another variable. The address
is the memory location that is assigned to the variable. It doesnt
store any value.
Hence, there are only a few operations that are allowed to perform
on Pointers in C language. The operations are slightly different from
the ones that we general y use for mathematical calculations. The
operations are:
Increment/Decrement of aPointer
Addition of integer to apointer
Subtractionof integer to apointer
Subtractingtwo pointers of the sametype
47. Increment/Decrement of aPointer
Increment: It is a condition that also comes under addition. When a
pointer is incremented, it actually increments by the number equal
to the size of the data type for which it is apointer.
For Example:
If an integer pointer that stores address 1000 is incremented, then it
will increment by 2(size of an int) and the new address it will points
to 1002. While if a float type pointer is incremented then it will
increment by 4(size of afloat) andthe new address will be 1004.
Samefor decrement of apointer
48. // C program to illustrate pointer increment/decrement
#include <stdio.h>
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Incrementing pointer ptr1;
ptr1++;
printf("Pointer ptr1 after"
" Increment: ");
printf("%p nn", ptr1);
// Pointer to an integer
int *ptr1, *ptr2;
printf("Pointer ptr1 before"
" Decrement: ");
// Pointer stores
// the address of N
ptr1 = &N;
ptr2 = &N;
printf("%p n", ptr1);
// Decrementing pointer ptr1;
ptr1--;
Output:
printf("Pointer ptr1 "
"before Increment: ");
printf("%p n", ptr1);
}
printf("Pointer ptr1 after"
" Decrement: ");
printf("%p nn", ptr1);
return 0;
Pointer ptr1 before Increment: 0x7ffcb19385e4
Pointer ptr1 after Increment: 0x7ffcb19385e8
Pointer ptr1 before Decrement: 0x7ffcb19385e8
Pointer ptr1 after Decrement: 0x7ffcb19385e4
49. When a pointer is added with a value, the value is first multiplied by the size of data type and
then added to the pointer.
// C program to illustrate pointer Addition
#include <stdio.h>
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Addition of 3 to ptr2
ptr2 = ptr2 + 3;
printf("Pointer ptr2 after
Addition: ");
printf("%p n", ptr2);
return 0;
}
Output:
// Pointer stores the address of N
ptr1 = &N;
ptr2 = &N;
Pointer ptr2 before Addition:
0x7fffffdcd984
Pointer ptr2 after Addition:
0x7fffffdcd990
printf("Pointer ptr2 before Addition: ");
printf("%p n", ptr2);
50. When a pointer is subtracted with a value, the value is first multiplied by the size of the
data type and then subtracted from the pointer.
// C program to illustrate pointer Subtraction
#include <stdio.h>
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Subtraction of 3 to ptr2
ptr2 = ptr2 - 3;
printf("Pointer ptr2 after Subtraction: ");
printf("%p n", ptr2);
return 0;
}
Output:
Pointer ptr2 before Subtraction: 0x7ffcf1221b24
// Pointer stores the address of N
ptr1 = &N;
ptr2 = &N;
Pointer ptr2 after Subtraction: 0x7ffcf1221b18
printf("Pointer ptr2 before Subtraction: ");
printf("%p n", ptr2);
51. Subtraction of Two Pointers
The subtraction of two pointers is possible only when they have the same data
type. The result is generated by calculating the difference between the
addresses of the two pointers and calculating how many bits of data it is
according to the pointer data type. The subtraction of two pointers gives the
increments between the two pointers.
For Example:
Two integer pointers say ptr1(address:1000) and ptr2(address:1016) are
subtracted. The difference between address is 16 bytes. Since the size of int is
2 bytes, therefore the increment between ptr1 and ptr2 is given by (16/2) = 8.
Below is the implementation to illustrate the Subtraction of Two Pointers:
52. C program to illustrate Subtraction of two
pointers
#include <stdio.h>
// Driver Code
int main()
{
int x;
// Integer variable
int N = 4;
// Subtraction of ptr2 and ptr1
x = ptr2 - ptr1;
// Print x to get the Increment
// between ptr1 and ptr2
printf("Subtraction of ptr1 "
"& ptr2 is %dn", x);
// Pointer to an integer
int *ptr1, *ptr2;
return 0;
}
// Pointer stores the address of N
ptr1 = &N;
ptr2 = &N;
Output:
Subtraction of ptr1 & ptr2 is 3
// Incrementing ptr2 by 3
ptr2 = ptr2 + 3;
53. Pointers as function arguments
Pointer preliminaries:
Pointer Definition:
A pointer is a variable whose value is the address of another variable,
i.e., direct address of the memory location. Like any variable or
constant, you must declare a pointer before using it to store any
variableaddress.
Function basics:
A function is a group of statements that together perform a task.
Every C program has at least one function, which is main(), and all the
most trivial programs can define additionalfunctions.
A function declaration tells the compiler about a function's name,
return type, and parameters. A function definition provides theactual
body of the function.
55. Call by value
This method copies the actual value of an argument
parameter of the function.
into the formal
In this case, changes made to the parameter inside the function
have no effect on the argument.
Syntax:
Datatype function_name(datatype variable_name);
56. #include <stdio.h>
void swap(int i, int j)
{
int t; t=i; i=j; j=t;
}
void main()
{
int a,b;
a=5; b=10;
printf("%d %dn", a, b);
swap(a,b);
printf("%d %dn", a, b);
}
57. Call by reference:
This method copies the address of an
parameter.
argument into the formal
Inside the function, the address is used to
argument used in the call.
access the actual
This means that changes made to the parameter affect the
argument.
Syntax:
datatype function_name(datatype *variable_name);
58. Call by reference Example
#include <stdio.h> void swap(int
*i, int *j)
{
int t; t = *i;
*i = *j;
*j = t;
}
void main()
{
int a,b; a=5; b=10;
printf("%d %dn",a,b);
swap(&a,&b); printf("%d
%dn",a,b);
}
59. When we pass a pointer as an argument instead of a variable then
the address of the variable is passed instead of thevalue.
So any change made by the function using the pointer is
permanently made at the address of passed variable.
60. #include <stdio.h>
void salaryhike(int *var, int b)
{
*var = *var+b;
}
int main()
{
int salary=0, bonus=0;
printf("Enter the employee current salary:");
scanf("%d", &salary);
printf("Enter bonus:");
scanf("%d", &bonus);
salaryhike(&salary, bonus);
printf("Final salary: %d", salary);
return 0;
}
61. Example for passing pointers as function argument
#include<stdio.h>
#include<conio.h>
void getDoubleValue(int *F){
*F = *F + 2;
printf("F(Formal Parameter) = %dn", *F);
}
int main(){
int A;
printf("Enter a numbersn");
scanf("%d", &A);
getDoubleValue(&A);
printf("A(ActualParameter) = %dn", A);
getch();
}
62. Another Example on passing pointer to function
#include <stdio.h> int* larger(int*, int*); void main()
{
Int a = 15; int b = 92; int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
int* larger(int *x, int *y)
{
if(*x > *y)
return x;
else
returny;
}
OUTPUT:
92 is larger
63. Functions of returning pointers
It is also possible for functions to return a function pointer as a
value.
This ability increases the flexibility of programs.
In this case you must be careful, because local variables of function
doesn't live outside the function. They have scope only inside the
function.
Hence if you return a pointer connected to a local variable, that
pointer will be pointing to nothing when the function ends
64. Pointer to functions
Exampleof function pointers as returnedvalues
#include <stdio.h>
int* larger(int*, int*);
voidmain()
{
int a = 15; int b = 92; int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
}
int* larger(int *x, int *y)
{
if(*x > *y) return x;
else
return y;
}