A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

Similar documents
Strings and Library Functions

Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

A. Introduction to Function 1. Modular Programming input processing output functions library functions 2. Function 1. Benefit of Using Functions

Introduction to string

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

C mini reference. 5 Binary numbers 12

Course organization. Course introduction ( Week 1)

String Class in C++ When the above code is compiled and executed, it produces result something as follows: cin and strings

Chapter 8 C Characters and Strings

AIR FORCE SCHOOL,BAMRAULI COMPUTER SCIENCE (083) CLASS XI Split up Syllabus (Session ) Contents

Strings. Daily Puzzle

Multiple Choice Questions ( 1 mark)

Downloaded from

today cs3157-fall2002-sklar-lect05 1

Introduction. What is function? Multiple functions form a larger program Modular programming

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

C: How to Program. Week /May/28

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

Chapter 8 - Characters and Strings

C++ Programming Lecture 11 Functions Part I

Fundamentals of Computer Programming Using C

Chapter 10 Characters, Strings, and the string class

Chapter 10: Character Testing. From Program Character Case Conversion 8/23/2014. Character Testing. Character Case Conversion

Chapter 10: Characters, C- Strings, and More About the string Class

LESSON 4. The DATA TYPE char

Split up Syllabus (Session )

BITG 1113: Array (Part 2) LECTURE 9

System Design and Programming II

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

C PROGRAMMING. Characters and Strings File Processing Exercise

Chapter 10: Characters, C- Strings, and More About the string Class Character Testing

Fundamentals of Programming. Lecture 11: C Characters and Strings

Introduction to C++ Introduction and History. Characteristics of C++

Chapter 8: Character & String. In this chapter, you ll learn about;

case control statement (switch case)

UNIT-I Input/ Output functions and other library functions

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

ARRAYS(II Unit Part II)

C Libraries. Bart Childs Complementary to the text(s)

Chapter 8 Character Arrays and Strings

C Syntax Arrays and Loops Math Strings Structures Pointers File I/O. Final Review CS Prof. Jonathan Ventura. Prof. Jonathan Ventura Final Review

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Computer Language. It is a systematical code for communication between System and user. This is in two categories.

Computer Science XII Important Concepts for CBSE Examination Questions

String can be represented as a single-dimensional character type array. Declaration of strings

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

LAB7 : Characters and Strings

Computers Programming Course 11. Iulian Năstac

C Functions. 5.2 Program Modules in C

C Programs: Simple Statements and Expressions

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

Operators and Expression. Dr Muhamad Zaini Yunos JKBR, FKMP

C++ Quick Reference. switch Statements

C programming basics T3-1 -

ONE DIMENSIONAL ARRAYS

Functions: call by reference vs. call by value

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Characters and Strings

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Computer Programming

CCE1111 Programming for Engineers [C Programming Language]

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Arrays, Strings, & Pointers

SPLIT UP SYLLABUS SUBJECT : COMPUTER SCIENCE (083) SESSION: Class XI (Theory) C++ Duration: 3 hours Total Marks: 70

8. Characters, Strings and Files

C++ Overview. Chapter 1. Chapter 2

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

Chapter 2. Outline. Simple C++ Programs

Object Oriented Programming In C++

C Programming. Unit 9. Manipulating Strings File Processing.

KENDRIYA VIDYALAYA SANGATHAN BHUBANESWAR REGION SPLITUP SYLLABUS FOR COMPUTER SCIENCE CLASS XI

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

Scientific Programming in C V. Strings

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:

Functions. Systems Programming Concepts

ANSI C Programming Simple Programs

Chapter 9 Strings. With this array declaration: char s[10];

LECTURE 15. String I/O and cstring library

Copyright 2003 Pearson Education, Inc. Slide 1

Computer Science & Engineering 150A Problem Solving Using Computers

Appendix A Developing a C Program on the UNIX system

ECET 264 C Programming Language with Applications

CSCI 171 Chapter Outlines

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Assoc. Prof. Dr. Tansu FİLİK

Intermediate Programming, Spring 2017*

1 Pointer Concepts. 1.1 Pointer Examples

Strings in C++ Dr. Ferdin Joe John Joseph Kamnoetvidya Science Academy

CSE123. Program Design and Modular Programming Functions 1-1

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

Structured programming

Approximately a Test II CPSC 206

Introduction to C/C++ Lecture 5 - String & its Manipulation

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Transcription:

Chapter-12 FUNCTIONS Introduction A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called. Types of functions There are two types of functions: 1. Library functions 2. User-defined functions Library functions A standard library is a collection of pre-defined functions and other programming elements which are accessed through header files. Header files are the files containing standard functions that our programs may use. The header files should be written angled brackets and its functions are included into our programs by #include directive. User-defined functions We can create our own functions or sub-programs to solve our problem. Such functions are normally referred to as user defined functions. A user-defined function is a complete and independent program, which can be used (or invoked) by the main program, or by the other sub-programs. The user-defined functions are written to perform definite calculations, after performing their task they send back the result to the calling program or sub-program. Different header files iostream.h This header file contains C++ streams and i/o routines and are listed below. open, close, get, getline, read, write, put, seekg, seekp, tellg, tellp, eof etc. stdio.h This header file contains functions and macros to perform standard i/o operations. 1 P a g e

When we include the header file iostream.h, the header file stdio.h is automatically included into our program. The standard i/o functions of the header file stdio.h are listed below. fopen, fclose, printf, scanf, fprintf, fscanf, fread, fwrite etc. string.h This header file declares functions to manipulate strings and memory manipulation routines. The functions contained in the header file string.h are listed below in the table. Function Meaning strlen(s) It gives the no. of characters including spaces present in a string s. strcat(s1, s2) strcpy(s1, s2) strcmp((s1,s2)==0) strcmp((s1,s2)>0) strcmp((s1,s2)<0) strcmpi((s1,s2)==0) strcmpi((s1,s2)>0) strcmpi((s1,s2)<0) strrev(s) strupr(s) strlwr(s) It concatenates the string s2 onto the end of the string s1. The string s1 must have enough locations to hold s2. It copies character string s2 to string s1. The s1 must have enough storage locations to hold s2. It compares s1 and s2 and find out whether s1 equal s2, greater than s2 or s1 less than s2. It compares s1 and s2 ignoring case and find out whether s1 equal s2, greater than s2 or s1 less than s2. It converts a string into its reverse. It converts a string s into upper case. It converts a string into lower case. stdlib.h This header file is used to declare conversion routines, search/sort routines and other miscellaneous things. The functions are listed below. atoi, atol, atof, free, malloc, calloc, realloc etc. iomanip.h This header file contains functions and macros for I/O manipulators for creating parameterized manipulations. The functions are listed. endl, setw, setfile, setprecision, hex, oct etc. math.h This header file declares prototypes for the mathematical functions and error handlers. 2 P a g e

The functions that are used to perform mathematical calculations and conversions are listed below in the table. Function sqrt(x) pow(x, y) sin(x) cos(x) tan(x) asin(x) acos(x) exp(x) log(x) Meaning Square Root of X x raised to the power y Sine of an angle x (measured in radians) Cosine of an angle x (measured in radians) Tangent of an angle x (measured in radians) Sin -1 (x) where x (measured in radians) Cos -1 (x) where x (measured in radians) Exponential function of x (ex) Logarithm of x log 10(x) Logarithm of number x to base 10 abs(x) fabs(x) Absolute value of integer number x Absolute value of real number x Character functions A character is any single character enclosed within single quotes. Some functions accept a character as argument. The argument is processed as an int by using its ASCII code. To use these functions, the header file ctype.h should be included. Any character enclosed within single quotes is called as a single character constant or simply, a character constant. These functions will be of the form : int function-name(int character) Any character enclosed within single quotes is called as a single character constant or simply, a character constant. Some functions that perform operations on characters are given below. Function isalpha(c) isdigit(c) isalnum(c) islower(c) isupper(c) Meaning It returns True if C is an uppercase letter and false if c is lowercase. It returns True if c is a digit (0 to 9) otherwise false It returns True if c is digit from 0 through 9 or an alphabetic character (either uppercase or lowercase) otherwise false It returns True if c is a lowercase letter otherwise False It returns True if c is a uppercase letter otherwise False 3 P a g e

toupper(c) tolower(c) It converts c to uppercase letter It converts c to lowercase letter. Inputting single character We can input a character using the function get ( ). 4 P a g e The general form is char ch; or char ch; cin =get(ch); Outputting single character put ( ) function is used to display single character. The general form is cout.put (ch); Example: char ch; ch=cin.get( ); cout.put (ch); Sample Program 1: To determine the type of character. ch=cin.get(ch); #include<ctype.h> void main ( ) char ch; clrscr( ); cout<< Type-in a character: ; ch=cin.get(); if((ch>= A &&ch<= Z ) (ch>= a &&ch<= z )) cout<< It is an albhabet <<endl; else if(ch>= 0 &&ch<= 9 ) cout<< It is a digit <<endl; else cout<< It is a special character <<endl; getch( ); Sample Program 2: To convert a character from upper-case to lower case and vice versa. #include<ctype.h> void main( )

char ch; clrscr( ); cout<< Type-in a character: ; ch=cin.get(); if( isupper (ch) ) ch= tolower (ch); cout<< The lower-case letter is <<ch<<endl; else if( islower (ch) ) ch= toupper (ch); cout<< The upper-case letter is <<ch<<endl; else cout<< It is not an alphabet <<endl; String functions: 5 P a g e A string is sequence of characters enclosed within double quotes. String are manipulated as one-dimensional array of characters and terminated by null ( \0 ) character. C++ provides many functions to manipulate strings. To use these functions, the header file string.h should be included. Declaring a string variable The general form to declare a string is: char string _name[size]; String_ name is the name of the string variable Size is the number of characters in the string. The size helps the compiler to allocate required number of memory locations to store the string. Example: char st[50]; This declaration reserves 50-bytes to store the characters of the string variable st. Initializing a string Like other variables, strings can also be initialized when they are declared. Example: char s[10]= Karnataka ;

6 P a g e There are only 9 characters in the string. The null character ( \0 ) is automatically appended to the end of the string. Example: char s[ ]= Bangalore ; The string st is initialized without specifying its size. The size is determined automatically which is 9 in the above example. Example: char st[]= E, m, p, r, e, s, s, \0 ; The string is initialized character wise. In this case, we must specify the null character. Example: char st[10]= Book ; The string is initialized with only 4-characters and the null characters and the null characters are appended to the end f the string. If an entire string is initialized to a string-variable then the null character is automatically appended to end-of-string. If string is initialized by giving the characters, then we must explicitly specify the string terminator. i.e., null character. Inputting a string C++ provides the function getline ( ) to read a string. The general form is: cin.getline (string, size); Example :- cin.getline (st, 25); getline( ) the function terminates reading characters on reading a newline character or when number of characters read is equal to size. The newline character is read, but replaced by null character. Outputting a string C++ provides the function write ( ) to output a string. The general form is: cout.write (string, size); Example:- cout.write (st, 25); write ( ) function displays the specified number of characters. This function does not stop displaying the characters when encountering the null character. As a result, if the size specified is greater than the length of the string, it displays beyond the bounds of the line. Sample Program 3: To read a string and print the string.

#include<string.h> void main( ) char s[50]; int l; clrscr( ); cout<< enter the string: ; cin.getline(s,50); l=strlen(s); cout<< the given string is ; cout.write(s,l); Some string manipulation functions are given below: strlen( ) function void main() 7 P a g e This function returns the length of the string.i.e., the number of characters present in the string, excluding the null character. The general form is variable=strlen(string); A string of length 0 is called a null string. Example:- l = strlen ( empress ); returns 7 Sample Program 4: To find the length of the string using the library function. #include<string.h> void main() char st[100]; int l; clrscr( ); cout<< enter the string: ; cin.getline (st,100) l=strlen (st); cout<< length= <<l<<endl; Sample Program 5:- To find the length of the string without using the library function. #include<string.h>

8 P a g e char st[100]; int i; clrscr(); cout<< enter the string: ; cin.getline(st,100); for (i=0; st[i]!= \0 ; i++) cout<< length= <<i<<endl; strcat( ) function //for loop terminated This function is used to concatenate 2 strings. The process of combining 2 strings to form a string is called as concatenation. The general form is strcat(string1, string2); Example:- char str1[ ]= win ; str1 becomes windows8. strcpy( ) function char str2[ ]= dows8 ; strcat(str1,str2); A string cannot be copied to another string by using assignment statement. The function strcpy() is used to copy a string into another string. The general form is strcpy (string1, string2); It copies all the characters to string2 to string1. Example:- char str1[ ]= computer ; str1 becomes science strcmp( ) function char str2[ ]= science ; strcpy (str1,str2); This function is used to alphabetically compare a string with another string. This function is case-sensitive. i.e., it treats the uppercase letters and lowercase letters as different. The general form is strcmp (string1, string2); It compares all the characters of str2 with str1. The function returns a positive value if string1>string2, a negative vale if string 1<string2 or it string1 is same as string2. Example:- char str1[ ]= There ; char str2[ ]= there ;

strcmpi ( ) function 9 P a g e strcmp (str2,str1); //gives a positive value But, strcmp (str1,str2); //gives a negative value This function is used to alphabetically compare a string with another string. This function is not case-sensitive. i.e., it treats the uppercase letter and lowercase letter as same. The general form is strcmpi (string1,string2); It compares all the characters of str2 with str1. This function returns a positive value if string1>string2, a negative value if string1<string2 or 0 it string1 is same as string2. Example:- char str1[ ]= There ; char str2[ ]= there ; strcmpi (str2,str1); //gives 0 Practical Program 25: To determine whether the string is a palindrome. #include<string.h> void main( ) char s[100], r[100]; //s is the string and r is the reserved string clrscr(); cout<< Enter the String: ; cin.getline(s,100); strcpy (r, s); // Copy the characters of the string s to r strrev (r); // Reverse the characters of the string r if(strcmpi(s, r) == 0) cout<< It is palindrome <<endl; else cout<< It is not palindrome <<endl; Practical Program 26: To count the number of vowels and consonants in a string. #include<string.h> #include<ctype.h> void main( ) char s[100]; int l, i, cons=0, vow=0; clrscr( ); cout<< enter the string: ;

cin.getline(s,100); l=strlen(s); for(i=0;i<1;i++) if( isalpha (s[i]) ) switch (toupper (s[i]) ) case A : case E : case I : case O : case U : vow++; break; default: cons++; cout<< Number of Vowels: <<vow<<endl; cout<< Number of Consonants: <<cons<<endl; Other functions C++ provides some useful functions under the library stdlib.h. Some functions are rand( ), srand( ), random( ) and randomized( ). These functions are used to generate pseudo-random numbers. i.e.,numbers that are uniformly distributed within a given interval and for which there is no particular pattern. Computer will generate a number by itself!! Randomly, using this randomized ( ). Function randomize() random(n) atoi(s) itoa(n) Meaning It initialize/seeds the random number generator with a random number. It generates a random number between 0 to n-1. It converts string s into a numerical representation. It converts a number to a string. CHAPTER 12 FUNCTIONS BLUE PRINT VSA (1 marks) SA (2 marks) LA (3 Marks) Essay (5 Marks) Total - 01 Question - - 02 Marks ************** 10 P a g e