Pages

Monday, November 23, 2009

Using character functions with strings

Although character functions are meant to be used with character but with the clever use of logic they can be effectivly used with strings also. To use a character function with a string we wil have to split the string into characters and then apply these functions. When a string is converted to individual characters the character function then can access all these character one by one and perform the desired operation.


Example 1: Finding out number of alphabets, digits and symbols in a given string
#include
#include
void main()
{
char str[40];
int letters=0,numbers=0,symbols=0,i,l;
printf(“\nEnter a sentence (max 40 characters) : “);
gets(str);
l=strlen(str);
for(i=0;i {
If(isalpha(str[i])
letters++;
else if(isdigit(str[i])
numbers++;
else
symbols++;
}
printf(“\nNo. Of alphabets : %d”,letters);
printf(“\nNo. Of digits : %d”,numbers);
printf(“\nNo. Of symbols : %d”,symbols);
}


Example 2: Finding out number of spaces and words in a given string.
#include
#include
int i,spaces=0;
void main()
{
char line[20];
printf(“\nEnter a string : “);
gets(line);
for(i=0;i{
if(isspace(line[i]))
spaces++;
}

printf(“\nSpaces %d”,spaces);
printf(“\nWords %d”,spaces+1);
}

Character Functions

There are many functions in C which can help the user in processing character variables. The string functions described in the previous session will work only with strings (character arrays) therfore we need some functions which can work on characters also. All these functions are defined in the header file so it is mandatory to include this file before using any of the following functions.
1. isalpha – returns true if the argument is an alphabet, returns false otherwise.
Syntax: void isalpha(char)
Example 1 : Checking if the user has entered an alphabet or not.

#include
void main()
{
char c;
printf(“\nEnter an alphabet : “);
scanf(“%c”,&c);
if(isalpha(c)) // check if the entered value is a alphabet
printf(“\nThis is an alphabet”);
else
printf(“\nThis is either a digit or a symbol”);
}

2. isalpha – returns true if the argument is a digit, returns false otherwise.
Syntax : void isdigit(char)
Example 2 : Checking if the user has entered a digit or not.

#include
void main()
{
char c;
printf(“\nEnter a digit : “);
scanf(“%c”,&c);
if(isdigit(c)) // check if the entered value is a digit
{
printf(“\nThis is a digit”);
else
printf(“\nNot a digit”);
}
3. isalnum – returns true if the argument is an alphabet or a digit, returns false otherwise.
Syntax : void isalnum(char)
Example 3: Checking if the user has entered a digit or not.

#include
void main()
{
char c;
printf(“\nEnter a digit or an alphabet : “);
scanf(“%c”,&c);
if(isalnum(c))
printf(“\nThis is either an alphabet or a digit”);
else
printf(“\nYou’ve entered a symbol”);
}

4. isupper – returns true if the argument is a capital letter, returns false otherwise.
Syntax: void isupper (char)
Example 4: Checking if the user has entered a capital case alphabet or not.

#include
void main()
{
char c;
printf(“\nEnter an alphabet : “);
scanf(“%c”,&c);
If(isalpha(c))
{
if(isupper(c))
printf(“\nThis is a capital letter”);
else
printf(“\nThis is a small letter”);
}
else
printf(“\nThis is not an alphabet”);
5. islower – returns true if the argument is a small letter, returns false otherwise.
Syntax: void islower(char)
Example 5 : Checking if the user has entered a small case alphabet or not.

#include
void main()
{
char c;
printf(“\nEnter an alphabet : “);
scanf(“%c”,&c);
if(isalpha(c))
{
if(islower(c))
printf(“\nThis is a small letter”);
else
printf(“\nThis is a capital letter”);
}
else
printf(“\nThis is not an alphabet”);
}
6. isspace – returns true if the argument is a whitespace (space), returns false otherwise.
Syntax : void isspace(char)
Example 2 : Checking if the user has entered a space or not.
#include
void main()
{
char c;
printf(“\nEnter any character : “);
scanf(“%c”,&c);
if(isspace(c))
printf(“\nSpace not allowed”);
else
printf(“\nYou entered %c”,c);
}

Saturday, November 14, 2009

String Functions

Introduction

C provides many predefined functions which are useful in manipulating strings. There are functions which can compare two strings, joins a string with another or copies a string. All these functions are provided in the header file , therefore it is a must to include this file before using any of the string functions.

1. strlen : returns the length of a string
syntax : int strlen(char s[])
Example – To Determine The Length Of A String

#include
void main()
{
char str[10];
int l;
printf(“\nEnter a string : “);
scanf(“%s”,&str);
l=strlen(str);
printf(“\nLength of the string is %d”,l);
}


Output :
Enter a string : welcome
Length of the string is 7

Description
The strlen() calculates the length of the string and returns the result to the variable “l”. when l is printed the length of the string is determined. The Null character is not counted in the length.

Note
If we enter a string with spaces in it like, “hello there” the length will be printed as 5 not 12. This is because the scanf() can not read a space so when it encounters a space it just stops reading after it. To read any space inside a string replace the scanf() statement with gets(). The statement will now look like this "gets(str);". The specifier “%s” is not used with gets()

2. strcmp() : Compares two string and assertain if they are identical. The two strings must also be in the same case.
Syntax: int strcmp(char str1[],char str2[])

If both the strings are same the function returns 0, if they are different a non-zero value is returned.

Example : Comparing two strings

#include

void main()
{
char pass1[10],pass2[10];
int result;
printf(“\nEnter your login password : “);
scanf(“%s”,&pass1);
printf(‘\nPlease re-enter your password : “);
scanf(“%s”,&pass2);
result=strcmp(pass1,pass2);
if(result==0)
printf(“\nPassword is correct. You can login”);
else
printf(“\nPassword mismatch.”);
}

Output
Enter your login password : hello
Please re-enter your password : hello
Password is correct. You can login

Description
The strcmp() compares two strings and returns 0 if they are exactly the same. If both the passwords are same then strcmp will return the result 0 and a non zero value if they are different. The strcmp() is case sensitive which means that if both the strings are same but their case (capital letter/small letter) is different the function will return a non zero value. If you want a case insensitive comparison use “strcmpi()” instead of “strcmp”. The extra “i” in strcmpi denotes that we want to ignore case while comparing.

3. strcmpi() : Compares two string and assertain if they are identical. Strcmpi ignores case while comparing
Syntax: int strcmpi(char str1[],char str2[])

If both the strings are same the function returns 0, if they are different a non-zero value is returned.

Example : Comparing two strings ignoring their case
void main()
{
char result[25];
printf(“\nWhat is the fullform of CPU ? : ”);
gets(result);// to enable the user to enter spaces.
if(strcmpi(result,”Central Processing Unit”)==0)
printf(“\nYou got it right”);
else
printf(“\nSorry. Ask your teacher for the correct answer”);
}

Output
What is the fullform of CPU ? : Central Processing Unit
You got it right

What is the fullform of CPU ? : CENTRAL PROCESSING UNIT
You got it right

What is the fullform of CPU ? : Central Power Unit
Sorry. Ask your teacher for the correct answer

3. Strcat() – Joins two strings to form a new string.
Syntax : strcat(string1,string2)
the second string will be added after the first string.


void main()
{
char fname[20],lname[10];
printf(“\nWhat’s your first name : “);
scanf(“%s”,&fname);
printf(“\nWhat’s your last name : “);
scanf(“%s”,&lname);
strcat(fname,lname);
printf(“\nHello %s”,fname);
}

Output
What’s your first name : Bill
What’s your last name : Gates
Hello Bill Gates


Description
The strcat() will append the lastname after the first name, therefore when the first name is printed the concatenated value is printed. After concatenation(joining) the first string becomes “Bill Gates” while the second string is still “Gates”.


Character Arrays (Strings)

Introduction

Till now all the arrays we have created are either of type int or float but we can also create arrays of character type. Such arrays are more popularly called “Strings”. Strings can be defined as a collection of characters terminated by null character (‘\0’) - Zero. If the collection is not terminated by ‘\0’ (zero) then it will not be called as string but just a collection of characters. They are used to store multi character values like name, address etc. They can also be used for storing integers or symbols since char allows any type of value. Strings in C are used with the modifier %s during input and output operations.

The null character – ‘\0’
The ‘\0’ plays a vital role in a string. It marks the end of a string so that when the string is printed or processed the compiler is aware that where the end of string is. Let’s understand this with an example
Example 1: Basic string input output program

void main()
{
char name[10]; //string declared with a size of 10
printf(“\nWhat’s your name ? “);
scanf(“%s”,&name); // %s denotes string.
printf(“Hello %s”,name);
}
Description
The above code declares a string (or char array) named “name” which can accept 10 characters. When the user enters his/her name the same is stored in the string starting from index 0. The C compiler automatically appends ‘\0’ after the last character to mark the end of the string. When the string is printed the compiler prints the string from the first character housed at index 0 till it reaches the ‘\0’ mark.
Output
What’s your name? Steven
Hello Steven

Why ‘\0’ is needed?
The moment we declare a string it is filled with garbage values. For example the declaration “char str[20]” will not only create a string with a capacity of 20 characters but will also fill it with 20 garbage characters. Now if the user enters a string having 12 characters the garbage values in the first 12 elements will be replaced by the characters entered by the user but the remaining 8 elements will still be garbage values. To prevent these garbage values from printing C adds the ‘\0’ after the 12th character. If this character wasn’t there then garbage values will also be printed causing unwanted character on the screen.

Example 2: Understanding the use of ‘\0’
void main()
{
char str[25];
printf(“Type a sentence (max. 25 characters) : “);
scanf(“%s”,&str);
printf(“\nyou entered %s”,str);
for(int i=0;i<25;i++)
{
printf(“\n%c”,str[i]);
}
}

Thursday, November 5, 2009

Types of arrays


Arrays are divided into two types:
1. Single Dimension Array
2. Multi Dimension Array
The arrays created in the previous session using the statement like “arr[5]” are single dimension arrays. The number within the square brackets [] signify the number of rows that the array will have. A size of 5 denotes that the array will have 5 rows inside it. What the statement above does not denote is that how many columns the array will have. Nothing is given regarding the number of columns. In such cases the compiler assumes the number of columns as 1. Therefore, the array will be created with 5 rows and a single column. Arrays having multiple columns but a single column are called single dimension array.
A multidimensional array on the other hand has multiple columns and multiple rows. Both the values are specified while the array is declared. For example, in the statement “int array[3][4]”, 3 denotes the number of rows and 4 is the number of columns, therefore this array is created as a matrix of 3 rows and 4 columns. A multidimensional array will have a storage capacity of “rows * columns” which means that the above array is capable of holding “3x4=12” values of integer type. Such types of arrays are quite handy when the data is to be stored in the form of a table. Do remember that like rows, the columns also start from 0.

Example 1 : Input and output in a multidimensional array.
void main()
{
int table[3][5],i,j;
for(i=0;i<3;i++)// the first loop will be for rows
{
for(j=0;j<5;j++)//for columns
{
printf(“\nEnter values : “);
scanf(“%d”,&table[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<5;j++)
{
printf(“%d”,table[i][j]);
}
printf(“\n”);
}
Description
In the above program an array named “table” is created with 3 rows and 5 tables. The first nested loop is used to get the values from the user and store it to the array. Note that both the outer loops are written to run from 0 to 2 because the rows are numbered like this. Similarly the inner loops are working as per the number of columns i.e. from 0 to 4.
The second nested loop is the output loop to print all the 15 values. We want the values to be printed in rows and columns therefore “\n” is being used after the printing of first row.
Let’s create some more programs using the same method.
Example 2: Program to print the sum of individual rows of an array.

void main()
{
float growth[4][8],sum;
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<8;j++)
{
printf(“\nEnter growth percentage of the company :”);
scanf(“%f”,&growth[i][j]);
}
}


for(i=0;i<4;i++)
{
sum=0;
f(j=0;j<8;j++)
{
sum+=growth[i][j];
}
printf(“\nSum of %d row is %f”,i+1,sum);
}

Description
The first loop again is an input loop to populate the array. The second loop first initializes the value of sum to 0 and starts adding the values of the array. When the second loop runs for the first time the value of i and j is 0 so the value of growth [0] [0] is added to sum. Being a nested loop the value of j is incremented to 1 while I remains at 0 therefore the next values to be added to sum is growth[0][1] and growth[0][2] and so on till growth[0][8]. When the inner loop completes its course by running eight times it terminates and prints the value of sum which will be the sum of all the values of the first row. After this the outer loop runs again repeating the whole process but since the value of i is now 1 the values of the second row will be added. Once the sum of one row is completed and printed it is very important that the value of sum is reset to 0 so that the sum of the next row starts from 0.