SlideShare une entreprise Scribd logo
1  sur  16
Library Functions in C++
string.h, ctype.h, math.h, stdlib.h
In built or Library Functions
In Built
Functions
Numeric
Mathematical
General
Purpose
Character String
standard
input/output
String Functions in C++
• C++ provides us with many functions to handle strings.
• string.h header file provides these functions.
Function Operation
strlen(str1); Finds the length of s string
strcpy(str1, str2); Copies string str2 to str1. Here str1 is the destination string and str2 is the source string.
strcat(str1, str2); Concatenates or joins str1 and str2. The concatenated string is stored in str1.
strcmp(str1, str2); Compares str1 and str2. It takes the case into consideration / For eg “Best” = “best”
If str1 and str2 are exactly equal, it returns 0
If str1> str2 , it returns -1 or negative number
If str1< str2 , it returns 1 or positive number
String Functions in C++……contd
Function Operation
strcmpi(str1, str2); Does the same as strcmp, but simply ignores the case of the characters. Ie
“Best”=“best”. The ‘i’ in the end signifies ‘ignore the case’.
strlwr(str1); Converts the entire string to lowercase
strupr(str1); Converts the entire string to uppercase
strrev(str1); Reverses the entire string
String functions……. examples
Function Example Output
strlen(S) char str[]=”Opera Winfrey”;
cout<<strlen(str);
13
strcat(S1, S2) char name[]=”Kiran Gupta”;
char title[]=”Miss”;
char str[25];
strcat(str, title);
strcat(str, name);
cout<<str;
Miss Kiran Gupta
strcpy(S1, S2) char a[20], b[20];
strcpy(a, “good”);
strcpy(b, “Morning”);
cout<<a<<”n”<<b;
// Now a will contain the string “good” and b will
contain “Morning”
good
Morning
String functions…..examples
strcmp(S1, S2)
strcmpi(S1, S2)
char str1[20]=” My Cookbook”;
if (strcmp(str1,”My Cookbook”)= =0)
cout<<”Found”;
else
cout<<”Not found”;
Found
char str1[20]=” MY CookbooK”;
if (strcmp(str1,”My Cookbook”)= =0)
cout<<”Found”;
else
cout<<”Not found”;
Not Found
This is because of letters in different cases
strrev(s) char ch[ ]=”ComPUterS”
strrev(ch);
cout<<ch;
SretUPmoC
strupr(s) char ch[ ]=”Palm oil”;
strupr(ch);
cout<<ch;
PALM OIL
strlwr(s) char ch[ ]=”pAlM Oil”;
strlwr(ch);
cout<<ch;
palm oil
Programs to check whether a string is a
palindrome.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
clrscr();
char str1[20],str2[20];
cout<<"|n Enter the string";
gets(str1); // input the string
strcpy(str2,str1); // store a copy of the original string
strrev(str1); // reverse the string
if(strcmp(str2,str1)==0) // compare the strings and display accordingly
{cout<<"n String is a palindrome";
else
cout<<"n Not a palindrome";
getch(); }
Program to search for a string in a list of
strings
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
clrscr();
char str[15][20], str1[20]; int n,flag=0;
cout<<“nHow many strings?”;
cin>>n;
cout<<“nEnter strings”;
for(int i=0; i<n;i++)
gets(str[i]);
cout<<"|n Enter the string to search";
gets(str1);
for(i=0;i<n;i++)
if(strcmp(str[i],str1)==0)
{cout<<"n String fouind at “<<i+1;
flag++;
}
If(flag==0 )
cout<<"n Not found";
getch();
}
Character functions
• C++ provides us with functions that work on single characters.
• These are contained in the header file ctype.h
function Purpose Domain Working
isalpha(char) Checks if the character in the brackets is an alphabet. a-z, A-Z Returns 1 if true else
returns 0
isalnum(char) Checks if the character is alphanumeric. a-z, A- Z, 0-9 “
isupper(char) Checks if the character is an upper case character A-Z “
islower (char) Checks if the character is a lower case character a-z “
isdigit(char) Checks if the character is a digit 0-9 “
toupper(char) Coverts a character to uppercase
tolower(char) Coverts a character to lowercase
Note : these functions work with a single character only
A sample program with explanation
#include<iostream.h>
#include<ctype.h>
{
char word[20]=”Welcome 2017”;
for(int i=0; word[i]!=’0’;i++)
if (isupper(word[i])
word[i]=tolower(word[i]);
else
if (islower(word[i])
word[i]= toupper(word[i]);
else
if(isdigit(word[i])
word[i]=word[i]+2;
else
word[i]=”@”;
cout<<word;}
Here each letter of the character array, word is evaluated and
modified accordingly. The diagram below shows how this works.
W e l c o m e 2 0 1 7 0
w E L C O M E @ 4 2 3 9 0
wELCOME@4239
Output
Program to demonstrate the use of character
functions
#include<iostream.h>
#include<ctype.h>
void main()
{
if(isalpha( ‘z’))
cout<<“nalphabet”;
else
cout<<“nnot an alphabet”;
if(isalnum( ‘#’))
cout<<“nalphanumeric”;
else
cout<<“nnot an alphanumeric”;
if(isdigit( ‘9’))
cout<<“na digit”;
else
cout<<“nnot a digit”;}
alphabet
not an alphanumeric
a digit
Output
Program to toggle the case of a sentence
#include<iostream.h>
#include<ctype.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char string[20];
cout<<”Input a string”;
gets(string);
for(int i=0;string[i[!=’0’; i++)
if (isupper(string[i])
string[i]=tolower(string[i]);
else
if(islower(string[i])
string[i]=toupper(string[i];
cout<<”n The string after toggle case is:n”<<string;
}
Input a string:
WelCome TO thE MAze
The string after toggle case is:
wELcOME to The maZE
Output
Mathematical functions
• C++ provides us with various mathematical functions
• These are contained in the header file math.h
function Purpose Example Output
sqrt(x) Finds the square root of x cout<<sqrt(81); 9
pow(x,y) Raises x to the power of y cout<<pow(4,2); 16
sin(x) Returns Sine of an angle x (measured in
radians)
cout<<sin(1.57); 1
cos(x) Returns Cosine of an angle x (measured in
radians)
cout<<cos(0); 1
sqrt(x) Returns square root of a number cout<<sqrt(36); 4
pow(x,y) Returns x raised to the power y cout<<pow(2,5); 32
fabs(x) Returns Absolute value of real number x Cout<<fabs(-80); 80
Mathematical functions : Usage
We can use the function call as a part of the expression or in a cout statement. Also the arguments or
parameters can either be (i)constants, (ii) variables or (iii)expression
(i) Using constants as arguments
int x;
x=sqrt(16);
cout<<x;
Answer : 4
(ii) Using variables as arguments
int a,b;
a=2, b=4;
cout<<pow(m,n)
Answer: 16
(iii) Using expressions
int p, q;
p=10, q=15;
int k=sqrt(p+q);
cout<<k;
Answer : 5
Generating random numbers
The stdlib.h file contains some library functions. We shall discuss the randomize () and the random() function
void randomize(void);
The randomize function initiates the random function. It is implemented as a macro that calls the time()
function. The function randomize has to be called before random() to initiate the random function.
The randomize function has no return value and no arguments.
int random(int x);
The function random is used to generate a random number. The function takes a single integer argument say n and
generates any number in the range 0 to n-1. So in order to obtain a number in the range 0- 31 we must write the
expression as:
int x= random(32); // x will have a no in the range 0-31
Program to generate random numbers between any
two values input by the user.
#include<iostream.h>
void main()
{
int x, y;
cout<<”n Enter the starting and ending values”;
cin>>x>>y;
randomize();
int random_no=random(y-x+1)+x;
cout<<random_no;
}

Contenu connexe

Tendances

Tendances (20)

Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
C functions
C functionsC functions
C functions
 
Strings in C
Strings in CStrings in C
Strings in C
 
File in c
File in cFile in c
File in c
 
Strings
StringsStrings
Strings
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Strings in C language
Strings in C languageStrings in C language
Strings in C language
 
Functions in c
Functions in cFunctions in c
Functions in c
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 
user defined function
user defined functionuser defined function
user defined function
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
C# basics
 C# basics C# basics
C# basics
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 

Similaire à Library functions in c++

2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
Warui Maina
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
Srikanth
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
gkgaur1987
 

Similaire à Library functions in c++ (20)

Unitii string
Unitii stringUnitii string
Unitii string
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Lecture 1 string functions
Lecture 1  string functionsLecture 1  string functions
Lecture 1 string functions
 
5 c control statements looping
5  c control statements looping5  c control statements looping
5 c control statements looping
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
Lecture 2. mte 407
Lecture 2. mte 407Lecture 2. mte 407
Lecture 2. mte 407
 
3. chapter ii
3. chapter ii3. chapter ii
3. chapter ii
 
String predefined functions in C programming
String predefined functions in C  programmingString predefined functions in C  programming
String predefined functions in C programming
 
Code optimization
Code optimization Code optimization
Code optimization
 
Code optimization
Code optimization Code optimization
Code optimization
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview Questions
 
String_C.pptx
String_C.pptxString_C.pptx
String_C.pptx
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Unit 5 Foc
Unit 5 FocUnit 5 Foc
Unit 5 Foc
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 

Plus de Neeru Mittal

Plus de Neeru Mittal (17)

Machine Learning
Machine LearningMachine Learning
Machine Learning
 
Introduction to AI and its domains.pptx
Introduction to AI and its domains.pptxIntroduction to AI and its domains.pptx
Introduction to AI and its domains.pptx
 
Brain Storming techniques in Python
Brain Storming techniques in PythonBrain Storming techniques in Python
Brain Storming techniques in Python
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
 
Python Tips and Tricks
Python Tips and TricksPython Tips and Tricks
Python Tips and Tricks
 
Python and CSV Connectivity
Python and CSV ConnectivityPython and CSV Connectivity
Python and CSV Connectivity
 
Working of while loop
Working of while loopWorking of while loop
Working of while loop
 
Increment and Decrement operators in C++
Increment and Decrement operators in C++Increment and Decrement operators in C++
Increment and Decrement operators in C++
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Arrays
ArraysArrays
Arrays
 
Nested loops
Nested loopsNested loops
Nested loops
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
 
Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
 
Getting started in c++
Getting started in c++Getting started in c++
Getting started in c++
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 

Dernier

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Dernier (20)

Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 

Library functions in c++

  • 1. Library Functions in C++ string.h, ctype.h, math.h, stdlib.h
  • 2. In built or Library Functions In Built Functions Numeric Mathematical General Purpose Character String standard input/output
  • 3. String Functions in C++ • C++ provides us with many functions to handle strings. • string.h header file provides these functions. Function Operation strlen(str1); Finds the length of s string strcpy(str1, str2); Copies string str2 to str1. Here str1 is the destination string and str2 is the source string. strcat(str1, str2); Concatenates or joins str1 and str2. The concatenated string is stored in str1. strcmp(str1, str2); Compares str1 and str2. It takes the case into consideration / For eg “Best” = “best” If str1 and str2 are exactly equal, it returns 0 If str1> str2 , it returns -1 or negative number If str1< str2 , it returns 1 or positive number
  • 4. String Functions in C++……contd Function Operation strcmpi(str1, str2); Does the same as strcmp, but simply ignores the case of the characters. Ie “Best”=“best”. The ‘i’ in the end signifies ‘ignore the case’. strlwr(str1); Converts the entire string to lowercase strupr(str1); Converts the entire string to uppercase strrev(str1); Reverses the entire string
  • 5. String functions……. examples Function Example Output strlen(S) char str[]=”Opera Winfrey”; cout<<strlen(str); 13 strcat(S1, S2) char name[]=”Kiran Gupta”; char title[]=”Miss”; char str[25]; strcat(str, title); strcat(str, name); cout<<str; Miss Kiran Gupta strcpy(S1, S2) char a[20], b[20]; strcpy(a, “good”); strcpy(b, “Morning”); cout<<a<<”n”<<b; // Now a will contain the string “good” and b will contain “Morning” good Morning
  • 6. String functions…..examples strcmp(S1, S2) strcmpi(S1, S2) char str1[20]=” My Cookbook”; if (strcmp(str1,”My Cookbook”)= =0) cout<<”Found”; else cout<<”Not found”; Found char str1[20]=” MY CookbooK”; if (strcmp(str1,”My Cookbook”)= =0) cout<<”Found”; else cout<<”Not found”; Not Found This is because of letters in different cases strrev(s) char ch[ ]=”ComPUterS” strrev(ch); cout<<ch; SretUPmoC strupr(s) char ch[ ]=”Palm oil”; strupr(ch); cout<<ch; PALM OIL strlwr(s) char ch[ ]=”pAlM Oil”; strlwr(ch); cout<<ch; palm oil
  • 7. Programs to check whether a string is a palindrome. #include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h> void main() { clrscr(); char str1[20],str2[20]; cout<<"|n Enter the string"; gets(str1); // input the string strcpy(str2,str1); // store a copy of the original string strrev(str1); // reverse the string if(strcmp(str2,str1)==0) // compare the strings and display accordingly {cout<<"n String is a palindrome"; else cout<<"n Not a palindrome"; getch(); }
  • 8. Program to search for a string in a list of strings #include<iostream.h> #include<conio.h> #include<stdio.h> #include<string.h> void main() { clrscr(); char str[15][20], str1[20]; int n,flag=0; cout<<“nHow many strings?”; cin>>n; cout<<“nEnter strings”; for(int i=0; i<n;i++) gets(str[i]); cout<<"|n Enter the string to search"; gets(str1); for(i=0;i<n;i++) if(strcmp(str[i],str1)==0) {cout<<"n String fouind at “<<i+1; flag++; } If(flag==0 ) cout<<"n Not found"; getch(); }
  • 9. Character functions • C++ provides us with functions that work on single characters. • These are contained in the header file ctype.h function Purpose Domain Working isalpha(char) Checks if the character in the brackets is an alphabet. a-z, A-Z Returns 1 if true else returns 0 isalnum(char) Checks if the character is alphanumeric. a-z, A- Z, 0-9 “ isupper(char) Checks if the character is an upper case character A-Z “ islower (char) Checks if the character is a lower case character a-z “ isdigit(char) Checks if the character is a digit 0-9 “ toupper(char) Coverts a character to uppercase tolower(char) Coverts a character to lowercase Note : these functions work with a single character only
  • 10. A sample program with explanation #include<iostream.h> #include<ctype.h> { char word[20]=”Welcome 2017”; for(int i=0; word[i]!=’0’;i++) if (isupper(word[i]) word[i]=tolower(word[i]); else if (islower(word[i]) word[i]= toupper(word[i]); else if(isdigit(word[i]) word[i]=word[i]+2; else word[i]=”@”; cout<<word;} Here each letter of the character array, word is evaluated and modified accordingly. The diagram below shows how this works. W e l c o m e 2 0 1 7 0 w E L C O M E @ 4 2 3 9 0 wELCOME@4239 Output
  • 11. Program to demonstrate the use of character functions #include<iostream.h> #include<ctype.h> void main() { if(isalpha( ‘z’)) cout<<“nalphabet”; else cout<<“nnot an alphabet”; if(isalnum( ‘#’)) cout<<“nalphanumeric”; else cout<<“nnot an alphanumeric”; if(isdigit( ‘9’)) cout<<“na digit”; else cout<<“nnot a digit”;} alphabet not an alphanumeric a digit Output
  • 12. Program to toggle the case of a sentence #include<iostream.h> #include<ctype.h> #include<stdio.h> #include<conio.h> void main() { char string[20]; cout<<”Input a string”; gets(string); for(int i=0;string[i[!=’0’; i++) if (isupper(string[i]) string[i]=tolower(string[i]); else if(islower(string[i]) string[i]=toupper(string[i]; cout<<”n The string after toggle case is:n”<<string; } Input a string: WelCome TO thE MAze The string after toggle case is: wELcOME to The maZE Output
  • 13. Mathematical functions • C++ provides us with various mathematical functions • These are contained in the header file math.h function Purpose Example Output sqrt(x) Finds the square root of x cout<<sqrt(81); 9 pow(x,y) Raises x to the power of y cout<<pow(4,2); 16 sin(x) Returns Sine of an angle x (measured in radians) cout<<sin(1.57); 1 cos(x) Returns Cosine of an angle x (measured in radians) cout<<cos(0); 1 sqrt(x) Returns square root of a number cout<<sqrt(36); 4 pow(x,y) Returns x raised to the power y cout<<pow(2,5); 32 fabs(x) Returns Absolute value of real number x Cout<<fabs(-80); 80
  • 14. Mathematical functions : Usage We can use the function call as a part of the expression or in a cout statement. Also the arguments or parameters can either be (i)constants, (ii) variables or (iii)expression (i) Using constants as arguments int x; x=sqrt(16); cout<<x; Answer : 4 (ii) Using variables as arguments int a,b; a=2, b=4; cout<<pow(m,n) Answer: 16 (iii) Using expressions int p, q; p=10, q=15; int k=sqrt(p+q); cout<<k; Answer : 5
  • 15. Generating random numbers The stdlib.h file contains some library functions. We shall discuss the randomize () and the random() function void randomize(void); The randomize function initiates the random function. It is implemented as a macro that calls the time() function. The function randomize has to be called before random() to initiate the random function. The randomize function has no return value and no arguments. int random(int x); The function random is used to generate a random number. The function takes a single integer argument say n and generates any number in the range 0 to n-1. So in order to obtain a number in the range 0- 31 we must write the expression as: int x= random(32); // x will have a no in the range 0-31
  • 16. Program to generate random numbers between any two values input by the user. #include<iostream.h> void main() { int x, y; cout<<”n Enter the starting and ending values”; cin>>x>>y; randomize(); int random_no=random(y-x+1)+x; cout<<random_no; }