Vidyalankar. F.E. Sem. II Structured Programming Approach Prelim Question Paper Solution

Similar documents
Chapter 8 Character Arrays and Strings

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

ONE DIMENSIONAL ARRAYS

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

Multiple Choice Questions ( 1 mark)

Computers Programming Course 5. Iulian Năstac

Operators and Expressions:

Introduction to string

Chapter 8 C Characters and Strings

Strings and Library Functions

C-LANGUAGE CURRICULAM

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Model Viva Questions for Programming in C lab

Chapter 8 - Characters and Strings

C Programming Multiple. Choice

UNIT 3 OPERATORS. [Marks- 12]

Basics of Programming

Fundamentals of Programming. Lecture 11: C Characters and Strings

today cs3157-fall2002-sklar-lect05 1

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Computers Programming Course 6. Iulian Năstac

Fundamental of Programming (C)

Q 1. Attempt any TEN of the following:

Contents. Preface. Introduction. Introduction to C Programming

Important Questions for Viva CPU

PERIYAR CENTENARY POLYTECHNIC COLLEGE Periyar Nagar- Vallam Thanjavur

UNIT-I Input/ Output functions and other library functions

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Fundamentals of Programming

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

C: How to Program. Week /Mar/05

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

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

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

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

C: How to Program. Week /May/28

UNIT- 3 Introduction to C++

Data Types. Data Types. Integer Types. Signed Integers

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath


Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

LESSON 4. The DATA TYPE char

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

Object Oriented Pragramming (22316)

'C' Programming Language


Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

UNIT- I INTRODUCTION TO PROBLEM SOLVING TECHNIQUES

Chapter 7. Basic Types

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C

Department of Computer Applications

Characters and Strings

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

A Fast Review of C Essentials Part I

Chapter 2 - Introduction to C Programming

Programming and Data Structures

Lecture 02 C FUNDAMENTALS

Chapter 3: Operators, Expressions and Type Conversion

Language Reference Manual simplicity

printf( Please enter another number: ); scanf( %d, &num2);

Programming. Elementary Concepts

THE FUNDAMENTAL DATA TYPES

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

SECTION II: LANGUAGE BASICS

Arithmetic Operators. Portability: Printing Numbers

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Lecture 3. More About C

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

C Language Programming

Questions Bank. 14) State any four advantages of using flow-chart

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU


DEPARTMENT OF MATHS, MJ COLLEGE

SWEN-250 Personal SE. Introduction to C

Lexical Considerations

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Write a C program using arrays and structure

M1-R4: Programing and Problem Solving using C (JULY 2018)

System Design and Programming II

Procedural programming with C

C mini reference. 5 Binary numbers 12

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

1 Lexical Considerations

Fundamentals of Computer Programming Using C

File Handling in C. EECS 2031 Fall October 27, 2014

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

بسم اهلل الرمحن الرحيم

KARMAYOGI ENGINEERING COLLEGE, Shelve Pandharpur

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

ARRAYS(II Unit Part II)

PESIT Bangalore South Campus Hosur Road (1km before Electronic City), Bengaluru Department of Basic Science and Humanities

Computer Programming Unit 3

CMPT 125: Lecture 3 Data and Expressions

Computers Programming Course 7. Iulian Năstac

CSCI 171 Chapter Outlines

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }

Transcription:

1. (a) 1. (b) 1. (c) F.E. Sem. II Structured Programming Approach C provides a variety of stroage class specifiers that can be used to declare explicitly the scope and lifetime of variables. The concepts of scope and lifetime are important only in multifunction and multiple file programs and therefore the storage classes are considered in detail later when functions are discussed. For now, remember that there are four storage class specifiers (auto, register, static, and extern) whose meanings are given in Table. The storage class is another qualifier (like long or unsigned) that can be added to a variable declaration as shon below: auto int count; register char ch; static int x; extern long total; Static and external (extern) variables are automatically initialized to zero, Automatic (auto) variables contain undefined values (known as garbage ) unless they are initialized explicitly. Table : Storage Classes and Their Meaning Storage class Meaning auto Local variable known only to the function in which it is declared. default is auto. static Local variable which exists and retains its value even after the control is transferred to the calling function. Extern Global variable known to all functions in the file. register Local variable which is stored in the register. (i) Y = Garbage Value, z = Garbage value, x = Garbage value (ii) 4040404040 Step1:- start Step2:- print Enter the length of 3 sides of a Triangle Step3:- Input A, B, C Step4:- If A+B>C and B+C>A and A+C>b Then print Triangle can be drawn Else Print Triangle cannot be drawn : Go to 8 Step5:- If A=B and B=C Then Print Equilateral Triangle : Go to 8 36

Step6:- If A= B or B=C or C= A then Print Isosceles Triangle : Go to 8 Step7:- Print Scalene triangle Step8:- Stop 2. (a) RECURSION When a called function in turn calls another function a process of chaining occurs. Recursion is a special case of this process, where a function calls itself. A very simple example of recursion is presented below: main( ) printf( This is an example of recursion\n ) main( ); When executed, this program will produce an output something like this : This is an example of recursion This is an example of recursion This is an example of recursion This is an ex Execution is terminated abruptly; otherwise the execution will continue indefinitely. Another useful example of recursion is the evaluation of factorials of a given number, Then factorial of a number n is expressed as a series of repetitive multiplications as shown below: factorial of n = n(n 1)(n 2).1. For example, factorial of 4 = 4 3 2 1 = 24 A function to evaluate factorial of n is as follows: factorial (int n) int fact; if (n= =1) return(1); else fact = n*factorial (n 1); return (fact); Let us see how the recursion works. Assume n = 3. Since the value of n is not 1, the statement fact = n * factorial (n 1); will be executed with n = 3. That is, fact = 3 * factorial (2); will be evaluated. The expression on the right hand side includes a call to factorial with n = 2. This call will return the following value: 2 * factorial(1) 37

: F.E. SPA 2. (b) Once again, factorial is called with n = 1. This time, the function returns 1. The sequence of operations can be summarized as follows: fact = 3 * factorial(2) = 3 * 2 * factorial(1) = 3 * 2 * 1 = 6 Recursive functions can be effectively used to solve problem where solution is expressed in terms of successively applying the same solution to subsets of the problem. When we write recursive functions, we must have an if statement somewhere to force the funcion to return withut the recursive call being executed. Otherwise, the function will never return. Typecasting is a way to convert a variable from one data type to another data type. For example if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another explicitly using the cast operator as follows: (type_name) expression Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating-point operation: #include <stdio.h> main() int sum = 17, count = 5; double mean; mean = (double) sum / count; printf("value of mean : %f\n", mean ); When the above code is compiled and executed, it produces the following result: Value of mean : 3.400000 It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value. Type conversions can be implicit which is performed by the compiler automatically, or it can be specified explicitly through the use of the cast operator. It is considered good programming practice to use the cast operator whenever type conversions are necessary. Integer Promotion Integer promotion is the process by which values of integer type "smaller" than int or unsigned int are converted either to int or unsigned int. Consider an example of adding a character in an int: #include <stdio.h> main() 38

int i = 17; char c = 'c'; /* ascii value is 99 */ int sum; sum = i + c; printf("value of sum : %d\n", sum ); When the above code is compiled and executed, it produces the following result: Value of sum : 116 Here value of sum is coming as 116 because compiler is doing integer promotion and converting the value of 'c' to ascii before performing actual addition operation. Usual Arithmetic Conversion The usual arithmetic conversions are implicitly performed to cast their values in a common type. Compiler first performs integer promotion, if operands still have different types then they are converted to the type that appears highest in the following hierarchy: The usual arithmetic conversions are not performed for the assignment operators, nor for the logical operators && and. Let us take following example to understand the concept: #include <stdio.h> main() int i = 17; char c = 'c'; /* ascii value is 99 */ float sum; sum = i + c; printf("value of sum : %f\n", sum ); When the above code is compiled and executed, it produces the following result: Value of sum : 116.000000 Here it is simple to understand that first c gets converted to integer but because final value is double, so usual arithmetic conversion applies and compiler convert i and c into float and add them yielding a float result. Generic Bitwise Operations Bitwise operators only work on a limited number of types: int and char. This seems restrictive--and it is restrictive, but it turns out we can gain some flexibility by doing some C "tricks". 3. (a) 39

: F.E. SPA It turns out there's more than one kind of int. In particular, there's unsigned int, there's short int, there's long int, and then unsigned versions of those ints. The "C" language does not specify the difference between a short int, an int and a long int, except to state that: sizeof( short int ) <= sizeof( int ) <= sizeof( long ) You will find that these sizes vary from ISA to ISA, and possibly even compiler to compiler. The sizes do not have to be distinct. That means all three sizes could be the same, or two of three could be the same, provided that the above restrictions are held. Bitwise operators fall into two categories: binary bitwise operators and unary bitwise operators. Binary operators take two arguments, while unary operators only take one. We're going to discuss binary operators first, and we'll do in the context of a fake binary operator called @. Thus, we write x @ y to perform bitwise @ on x and y. Bitwise operators, like arithmetic operators, do not change the value of the arguments. Instead, a temporary value is created. This can then be assigned to a variable. For example, when you write x + y, neither x nor y have their value changed. Let's assume that we are doing bitwise @ on two unsigned int variables. Let's assume that unsigned ints use 32 bits of memory. We define two variables X and Y where X = x 31 x 30 x 0 Y = y 31 y 30 y 0 We want to be able to refer to each bit of X and Y, which we do so by writing out the bits by writing the variable name in lowercase and adding the appropriate subscript for the bit number. The subscripts follow the convention we've used so far. The least significant bit has a subscript of 0, and is the rightmost bit. The most significant bit has a subscript of N-1 (for N bits), and is the leftmost bit. In this case N = 32 so the MSb has a subscript of 31. Let's define @ 1 to be the @ operation performed on two individual bits. @ is performed on all 32 bits simultaneously. Further more, let's call the temporary value created, T. Normally, this temporary value does not have a name. It is generated while the program is running, and used in other computations. Thus, when you write c = a + b, a temporary value is created for the sum a + b, and this temporary value then gets copied into c. Of course, for efficiency, the temporary value might not be generated, and the value written directly to c. For more complex statements, such as c = (a + b) - d, temporary values are often created to store intermediate results. These temporary values are created by the runtime system, and are not given variable names. We define Z = X @ Y as: z i = x i @ 1 y i, for 0 <= i <= N 1 40

In words, to compute the i th bit of Z, you should perform the operation on the i th bit of X and i th bit of Y. i) Bitwise AND This makes more sense if we apply this to a specific operator. In C/C++/Java, the & operator is bitwise AND. The following is a chart that defines & 1, defining AND on individual bits. x i y i x i & 1 y i 0 0 0 0 1 0 1 0 0 1 1 1 We can do an example of bitwise &. It's easiest to do this on 4 bit numbers, however. Variable b 3 b 2 b 1 b 0 x 1 1 0 0 y 1 0 1 0 z = x & y 1 0 0 0 ii) Bitwise OR The operator is bitwise OR (it's a single vertical bar). The following is a chart that defines 1, defining OR on individual bits. x i y i x i 1 y i 0 0 0 0 1 1 1 0 1 1 1 1 We can do an example of bitwise. It's easiest to do this on 4 bit numbers, however. Variable b 3 b 2 b 1 b 0 x 1 1 0 0 y 1 0 1 0 z = x y 1 1 1 0 iii) Bitwise XOR The ^ operator is bitwise XOR. The usual bitwise OR operator is inclusive OR. XOR is true only if exactly one of the two bits is true. The XOR operation is quite interesting, but we defer talking about the interesting things you can do with XOR until the next set of notes. The following is a chart that defines ^1, defining XOR on individual bits. x i y i x i ^1 y i 0 0 0 0 1 1 1 0 1 1 1 0 41

: F.E. SPA 3. (b) We can do an example of bitwise ^. It's easiest to do this on 4 bit numbers, however. Variable b 3 b 2 b 1 b 0 x 1 1 0 0 y 1 0 1 0 z = x ^ y 0 1 1 0 iv) Bitwise NOT There's only one unary bitwise operator, and that's bitwise NOT. Bitwise NOT flips all of the bits. There's not that much to say about it, other than it's not the same operation as unary minus. The following is a chart that defines ~ 1, defining NOT on an individual bit. x i ~ 1 x i 0 1 1 0 We can do an example of bitwise ~. It's easiest to do this on 4 bit numbers (although only 2 bits are necessary to show the concept). Variable b 3 b 2 b 1 b 0 x 1 1 0 0 z = ~x 0 0 1 1 Uses of Bitwise Operations Occasionally, you may want to implement a large number of Boolean variables, without using a lot of space. A 32-bit int can be used to stored 32 Boolean variables. Normally, the minimum size for one Boolean variable is one byte. All types in C must have sizes that are multiples of bytes. However, only one bit is necessary to represent a Boolean value. You can also use bits to represent elements of a (small) set. If a bit is 1, then element i is in the set, otherwise it's not. You can use bitwise AND to implement set intersection, bitwise OR to implement set union. In upcoming notes, you'll learn how to find the value of individual bits of a char or int. Relational Operators We often compare two quantities and depending on their relation, take certain decisions. For example, we may compare the age of two persons, or the price of two items, and so on. These comparisons can be done with the help of relational operators. We have already used the symbol <, meaning less than. An expression such as a < b or 1 < 20 containing a relational operator is termed as a relational expression. The value of a relational expression is either one or zero. It is one if the specified relation is true and zero if the relation is false. For example 10 < 20 is true but 20 < 10 is false 42

C supports six relational operators in all. These operators and their meanings are shown in Table 1. Table 1 : Relational Operators. Operator Meaning < is less than <= is less than or equal to > Is greater than >= is greater than or equal to == is equal to!= is not equal to A simple relational expression contains only one relational operator and takes the following form: ae-1 relational operator ae-2 ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables or combination of them. Given below are some examples of simple relational expressions and their values: 4.5 <= 10 TRUE 4.5 < 10 FALSE 35 >= 0 FALSE 10 < 7+5 TRUE a+b = c+d TRUE only if the sum of values of a and b is equal to the sum of values of c and d. When arithmetic expressions are used on either side of a relational operator, the arithmetic expressions will be evaluated first and then the results compared. That is arithmetic operators have a higher priority over relational operaors. Relational expressions are used in decision statements such as if and while to decide the course of action of a running program. Logical Operators In addtion to the relational operators, C has the following three logical operators. && meaning logical AND meaning logical OR! meaning logical NOT The logical operators && and are used when we want to test more than one condition and make decisions. An example is: a > b && x == 10 Table 2 : Truth Table op 1 op 2 Value of the expression op-1 && op-2 op-1 op-2 Non zero Non zero 1 1 Non zero 0 0 1 0 Non zero 0 1 0 0 0 0 43

: F.E. SPA 4. (a) Call by Value If data is passed by value, the data is copied from the variable used in for example main( ) to a variable used by the function. So if the data passed (that is stored in the function variable) is modified inside the function, the value is only changed in the variable used inside the function. Let s take a look at a call by value example: #include <stdio.h> void call_by_value(int x) printf("inside call_by_value x = %d before adding 10.\n", x); x += 10; printf("inside call_by_value x = %d after adding 10.\n", x); int main( ) int a=10; printf("a = %d before function call_by_value.\n", a); call_by_value(a); printf("a = %d after function call_by_value.\n", a); return 0; The output of this call by value code example will look like this: a = 10 before function call_by_value. Inside call_by_value x = 10 before adding 10. Inside call_by_value x = 20 after adding 10. a = 10 after function call_by_value. In the main( ) we create a integer that has the value of 10. We print some information at every stage, beginning by printing our variable a. Then function call_by_value is called and we input the variable a. This variable (a) is then copied to the function variable x. In the function we add 10 to x (and also call some print statements). Then when the next statement is called in main( ) the value of variable a is printed. We can see that the value of variable a isn t changed by the call of the function call_by_value( ). Call by Reference If data is passed by reference, a pointer to the data is copied instead of the actual variable as is done in a call by value. Because a pointer is copied, if the value at that pointers address is changed in the function, the value is also changed in main( ). Let s take a look at a code example: #include <stdio.h> void call_by_reference(int *y) printf("inside call_by_reference y = %d before adding 10.\n", *y); (*y) += 10; printf("inside call_by_reference y = %d after adding 10.\n", *y); int main( ) int b=10; 44

4. (b) printf("b = %d before function call_by_reference.\n", b); call_by_reference(&b); printf("b = %d after function call_by_reference.\n", b); return 0; The output of this call by reference source code example will look like this: b = 10 before function call_by_reference. Inside call_by_reference y = 10 before adding 10. Inside call_by_reference y = 20 after adding 10. b = 20 after function call_by_reference. We start with an integer b that has the value 10. The function call_by_reference( ) is called and the address of the variable b is passed to this function. Inside the function there is some before and after print statement done and there is 10 added to the value at the memory pointed by y. Therefore at the end of the function the value is 20. Then in main( ) we again print the variable b and as you can see the value is changed (as expected) to 20. POINTERS A pointer is a derived data type in C. It is built from one of the fundamental data types available in C. Pointers contain memory addresses as their values. Since these memory addresses are the locations in the computer memory where program instructions and data are stored, pointers can be used to access and manipulate data stored in the memory. Pointers are undoubtedly one of the most distinct and exciting features of C language. It has added power and flexibility to the language. Although they appear little confusing and difficult to understand for a beginner, they are a powerful tool and handy to use once they are mastered. Pointers are used frequently in C, as they offer a number of benefits to the programmers. They include: Pointers are more efficient in handling arrays and data tables. Pointers can be used to return multiple values from a function via function arguments. Pointers permit references to functions and thereby facilitating passing of functions as arguments to other functions. The use of pointer arrays to character strings results in saving of data storage space in memory. Pointers allow C to support dynamic memory management. Pointers provide an efficient tool for manipulating dynamic data structures such as structures, linked lists, queues, stacks and trees. Pointers reduce length and complexity of programs. They increase the execution speed and thus reduce the program execution time. 45

: F.E. SPA 5. (a) Example : #include<stdio.h> #include<conio.h> #include<string.h> void swap (int * d1. int * d2) int temp; temp=*d1; *d1=*d2; *d2=temp; void main() int a,b; clrscr(); printf("enter number a:"); scanf("%d", &a); printf("\nenter number b:"); scanf("%d", &b); swap(&a,&b); printf("\na contain %d",a); printf("\nb contain %d",b); getch(); #include<stdio.h> #include<conio.h> #include<string.h> struct cricket char nm[20],team[20]; int avg; ; #define total 20 int main() struct cricket player[total],temp; int i,j; clrscr(); for(i=0;i<total;i++) printf("for player %d\n",i+1); printf("enter the name of player : "); fflush(stdin); gets(player[i].nm); printf("enter the team : "); fflush(stdin); gets(player[i].team); 46

printf("enter the batting average : "); fflush(stdin); scanf("%d",&player[i].avg); printf("\nteam Name Average\n"); printf(" \n"); for(i=0;i<total;i++) printf("%-10s %-10s %7d\n",player[i].team,player[i].nm,player[i].avg); getch(); return 0; Output: For player 1 Enter the name of player : Diz Enter the team : India Enter the batting average : 100 For player 2 Enter the name of player : Tiwari Enter the team : Pakistan Enter the batting average : 5 For player 3 Enter the name of player : Tendulkar Enter the team : India Enter the batting average : 45 For player 4 Enter the name of player : Dhoni Enter the team : India Enter the batting average : 48 For player 5 Enter the name of player : Yuvi Enter the team : India Enter the batting average : 39 Team Name Average India Diz 100 Pakistan Tiwari 5 India Tendulkar 45 India Dhoni 48 India Yuvi 39 such 20 records #include<conio.h> #include<ctype.h> 5. (b) int main( ) char str[30]; 47

: F.E. SPA 6. (a) int i,c,c1,j,m; c=0; clrscr( ); printf("\n\n\t Pl. enter string > "); gets(str); i=0; while(str[i]!='\0') c++; i++; i = c-1; while(i>=0) if(str[i]== ' ') str[i+1] = toupper(str[i+1]); i--; i=0; str[i] = toupper(str[i]); printf("\n\n\t string > %s", str); getch( ); return 0; Using getchar and gets Functions We have discussed, as to how to read a single character from the terminal, using the function getchar. We can use this function repeatedly to read successive single characters from the input and place them into a character array. Thus, an entire line of text can be read and stored in an array. The reading is terminated when the newline character ( \n ) is entered and the null character is then inserted at the end of the string. The getchar function call takes the form: char ch; ch = getchar( ); Note that the getchar function has no parameters. Every time a character is read, it is assigned to its location in the string line and then tested for newline character. When the newline character is read (signaling the end of line), the reading loop is terminated and the newline character is replaced by the null character to indicate the end of character string. When the loop is exited, the value of the index c is one number higher than the last character position in the string (since it has been incremented after assigning the new character to the string). Therefore the index value c-1 gives the position where the null character is to be stored. 48

Another and more convenient method of reading a string of text containing whitespaces is to use library function gets available in the <stdio.h> header file. This is a simple function with one string parameter and called as under: gets (str); str is a string variable declared properly. It reads characters into str from the keyboard until a new line character is encountered and then appends a null character to the string. Unlike scanf, it does not skip whitespaces. For example the code segment char line [80]; gets (line) ; printf ( %s, line); reads a line of text from the keyboard and displays it on the screen. The last two statements may be combined as follows: printf( %s, gets(line)) ; Using Putchar and Puts Functions Like getchar, C supports another character handling function putchar to output the values of character variables. It take the following form: char ch = A ; purchar (ch); The function putchar requires one parameter. This statement is equivalent to: printf( %c, ch); We have used putchar function to write characters to the screen. We can use this function repeatedly to output a string of characters stored in an array using a loop. Example: char name[6] = PARIS for (i=0, i<5; i++) putchar(name[i]; putchar( \n ) ; Another and more convenient way of printing string values is to use the function puts declared in the header file <stdio.h>. This is a one parameter function and invoked as under: puts ( str ); where str is a string variable containing a string value. This prints the value of the string variable str and then moves the cursor to the beginning of the next line on the screen. For example, the program segment char line [80] ; gets (line) ; puts (line) ; reads a line of text from the keyboard and displays it on the screen. Note that the syntax is very simple compared to using the scanf and printf statements. 49

: F.E. SPA 6. (b) String Handling Functions Fortunately, the C library supports a large number of string handling functions that can be used to carry out many of the string manipulations discussed so far. Following are the most commonly used string handling functions. Function strcat( ) strcmp( ) strcpy( ) strlen( ) Action concatenates two strings compares two strings copies one string over another finds the length of a string We shall discuss briefly how each of these functions can be used in the processing of strings. (i) strcat(s1, s2) strcat( ) Function The strcat function joins two strings together. It takes the following form: strcat(string1, string2); string1 and string2 are character arrays. When the function strcat executed, string2 is appended to string1. It does so by removing the null character at the end of string1 and placing string2 from there. The string at string2 remains unchanged. For example, consider the following three strings: 0 1 2 3 4 5 6 7 8 9 0 1 Part1 = V E R Y \0 0 1 2 3 4 5 6 Part2 = G O O D \0 0 1 2 3 4 5 6 Part3 = B A D \0 Execution of the statement strcat (part1, part2); will result in: 0 1 2 3 4 5 6 7 8 9 0 1 2 Part1 = V E R Y G O O D \0 0 1 2 3 4 5 6 Part2 = G O O D \0 while the statement will result in: 0 1 2 3 4 5 6 7 8 9 0 1 2 Part1 = V E R Y B A D \0 0 1 2 3 4 5 6 Part3 = B A D \0 We must make sure that the size of string1 (to which string2 is appended) is large enough to accommodate the final string. 50

strcat function may also append a string constant to a string variable. The following is valid: strcat(part1, GOOD ) ; C permits nesting of strcat functions. For example, the statement strcat (strcat (string1, string2), string3) ; is allowed and concatenates all the three strings together. The resultant string is stored in string1. (ii) strchr(s1, char) Description : The strchr function searches string for the first occurrence of c. The null character terminating string is included in the search. Return Value The strchr function returns a pointer to the first occurrence of character c in string or a null pointer if no matching character is found. Example : #include <stdio.h> int main() char *s; char buf [] = "This is a test"; s = strchr (buf, 't'); if (s!= NULL) printf ("found a 't' at %s\n", s); return 0; It will proiduce following result: found a 't' at test (iii) isalpha(char) int isalpha(int c); Description : The function returns nonzero if c is any of: a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Return Value The function returns nonzero if c is just alpha otherwise this will return zero which will be equivalent to false. Example: #include <stdio.h> int main() if( isalpha( '9' ) ) 51

: F.E. SPA printf( "Character 9 is not alpha\n" ); if( isalpha( 'A' ) ) printf( "Character A is alpha\n" ); return 0; It will proiduce following result: Character A is alpha (iv) isdigit(char) The C library function void isdigit(int c) checks if the passed character is a decimal digit character. Decimal digits are(numbers): 0 1 2 3 4 5 6 7 8 9 Declaration Following is the declaration for isdigit() function. int isdigit(int c); Parameters c -- This is the character to be checked. Return Value This function returns nonzero value if c is a digit, else 0 Example : The following example shows the usage of isdigit() function. #include <stdio.h> #include <ctype.h> int main() int var1 = 'h'; int var2 = '2'; if( isdigit(var1) ) printf("var1 = %c is a digit\n", var1 ); else printf("var1 = %c is not a digit\n", var1 ); if( isdigit(var2) ) printf("var2 = %c is a digit\n", var2 ); else 52

printf("var2 = %c is not a digit\n", var2 ); return(0); Let us compile and run the above program, this will produce the following result: var1 = h is not a digit var2 = 2 is a digit #include <stdio.h> char *strchr(char *string, int c); (v) strcmp(s1,s2) strcmp( ) Function The strcmp function compares two strings identified by the arguments and has a value 0 if they are equal. If they are not, it has the numeric difference between the first nonmatching characters in the strings. It takes the form: strcmp(string1, string2); string1 and string2 may be string variable or string constants. Examples are: strcmp (name1, name2) ; strcmp (name1, John ) ; strcmp ( Rom, Ram ) ; Our major concern is to determine whether the strings are equal; if not, which is alphabetically above. The value of the mismatch is rarely important. For example, the statement strcmp( their, there ) ; will return a value of 9 which is the numeric difference between ASCII i and ASCII "r". That is, i minus r in ASCII code is 9. If the value is negative, string1 is alphabetically above string2. (vi) strcpy(s1,s2) strcpy( ) Function The strcpy function works almost like a string assignment operator. It takes the form: strcpy(string1, string2); and assigns the contents of string2 to string1. string2 may be a character array variable or a string constant. For example, the statement strcpy(city, DELHI ) ; will assign the string DELHI to the string variable city. Similarly, the statement strcpy(city1, city2) ; will assign the contents of the string variable city2 to the string variable city1. The size of the array city1 should be large enough to receive the contents of city2. 53

: F.E. SPA (vii) strlen(s1) strlen( ) Function This function counts and returns the number of characters in a string. It takes the form n = strlen = strlen(string); Where n is an integer variable, which receives the value of the length of the string. The argument may be a string constant. The counting ends at the first null character. (viii)islower(char) int islower(int c); DESCRIPTION The islower() function tests for any character that is a lowercase letter or is one of an implementation-defined set of characters for which none of iscntrl(), isdigit(), ispunct(), or isspace() is true. In the C locale, islower() returns true only for the characters defined as lowercase letters. The behavior of the islower() function is affected by the current locale. To modify the behavior, change the LC_CTYPE category in setlocale(), that is, setlocale(lc_ctype, newlocale). In the C locale or in a locale where character type information is not defined, characters are classified according to the rules of the U.S. ASCII 7-bit coded character set. PARAMETERS Is an integer whose value is representable as an unsigned char, or the value of the macro EOF. RETURN VALUES The islower() function returns non-zero for true and zero for false. If the parameter is not in the domain of the function, the return result is undefined. 54