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.

Friday, October 30, 2009

Arrays

Arrays are defined as a finite set of values or variables of same data type. An array is a collection of values of similar data type where all the values have the same name but different index or element number. In some program there can be a condition where we want to process large number of values but are hesitating in declaring so many variables. For example, to process the roll numbers of 100 students, declaring 100 individual variables will be a tedious task. Declaring 100 variables, thinking of 100 unique names and managing so many variables is quite a time consuming task. Arrays are declared to help the user overcome this problem. With the use of array we can easily store as many values as we want without having to create multiple variables.
Syntax
datatype arrayname[size]

Example
int marks[5];
float data[10];
char name[15];


The first array, marks has been declared with a size of 5 which means that we can store any 5 integer values, while the second array data has the size of 10. The internal structure of the first array looks likes this
0
1
2
3
4

As you can see the structure of an array resembles a table having multiple rows and single column. The first row is numbered as 0 rather than 1 which means that the first value of the array will always be stored at 0 whereas the last value will be at index number , size-1.

Why should we use arrays?
One important thing to understand here is why we need arrays when we can do the same task without them. Let’s see the example given below to understand this. The following program will ask the user to enter 10 values and will display their sum.
void main()
{
int num, sum=0;
for(i=0;i<10;i++)>
{
printf(“\nEnter a number : “);
scanf(“%d”,&num);
sum+=num;
}
printf(“\nSum of all numbers is %d”,sum);
}

When you run the above program you will see that it works fine – accepts 10 values from you – adds them up – and displays the result. Even though the code is correct and so is the output there is one serious problem. What if the user wants to see all the values he entered just to confirm the output. If you try to print the value of “num” you will see that only the last value is being printed. This is because the moment the loop runs the second time the previous value gets lost from the memory. It works something like this:
a=10;
a=20;
printf(“\nA = %d”,a);
What will the value of “a” when it is printed, 10 or 20? The answer is 20, why not 10? If you ask. The answer is simple – no variable can hold more than one value at a time so when the statement “a=20” is reached “a” is assigned the value 20 and the previous value of 10 is overwritten. You cannot recover the value once it has been overwritten. The same thing happens to “num” in the above example. Since we are using only a single variable “num” to store 5 values each value overwrites the previous one, so only the last value is printed and there is no way you can get the old values? Let’s try the same problem with arrays
Example 1 : Adding the values of an array.
void main()
{
int values[5], i, sum=0;
for(i=0;i<5;i++)
{
printf(“\nEnter a number : “);
scanf(“%d”,&values[i]);
sum+=values[i];
}
}
On running this program you will get the same output which is sum of 10 values. So what have we achieved by using an array. The advantage is that the values are no longer overwriting the previous values so we can print or access any of the values which we have entered be it the first one or the last one or any other value. The array is helping us in storing these values without overwriting since it can store 10 values at the same time. After filling the array with our values it will look something like this (the values written inside are assumed values entered by the user) 12 63 47 5 93 From the above diagram it is evident that each value has been stored at a particular location which is called the index or element number. For example, 12 is stored at element number 0, 47 at index 2 and so on. Therefore, if you want to print all the values at the end of the program you can append the following code after the first program.
for(i=0;i<5;i++)>
{
printf(“\n%d”,values[i]);
}
In case you want only a particular value you can even do that by specifying the index number of the value which you want to see. For example, printf(“%d”,values[3]); Will print the third value of the array (which will be the fourth value since arrays count them from 0)
Properties of an array
1. An array always starts from index number 0. It is not possible to start it from any other location.
2. The array elements are always stored in contiguous memory. This means that the array elements are always allocated memory in continuous memory blocks.
3. Arrays are static in nature which means that once an array has been declared we cannot increase or decrease its size.
4. If the array is declared with a large size and number of values is less the remaining memory will be wasted similarly if a small size is decided upon it will lead to storage problem.

Example 2: Finding out the highest number among a list of numbers.
This problem can be solved by two methods, first using the && operator along with an if-else block the statement for which can be something like
if(a>b && a>c && a>d && a>e)
printf(“\na is greatest”);
else if(b>a && b>c && b>d && b>e)
printf(“\nb is greatest”);
This approach can solve the problem but we will have to write many lines of code. The same problem can be solved easily using arrays
void main()
{
int list[10],max,i;
for(i=0;i<10;i++)>
{
printf(“\nenter values in the array “);
scanf(“%d”,&list[i]);
}
max=list[0];
for(i=1;i<10;i++)>
{
if (list[i]>max)
max=list[i];
}
printf(“\nMaximum value is %d”,max);
}
When the above program is run it will ask the user to enter 10 values and will store then one by one to the array. The storage will happen from element number 0. After all the values have been stored the variable max has been assigned the first value of the array. The second loop then compares the value of max with the remaining array values starting from 1. If it finds any value having data larger than then max, it replaces the value of max with that number.

Monday, October 19, 2009

The while loop

While is a conditional loop which is used when we want to do some repetitive task till a certain conditions evaluates to true. It is useful in conditions when do not know the exact number of times the task is to be repeated. For example : when we say that we are going to study till 5’o clock it is an example of for loop since 5 is a fixed value but if the sentence is changed to “till dark” instead of “till 5’o clock” this become while loop since we don’t know when it will get dark. Check out its syntax :

while(condition)

{

loop body

}

Lets understand this with a basic example

void main()

{

int a=1;

while(a<=10)

{

printf(“\n%d”,a);

a++;

}

}

The condition part has “a<=10” written which states that the loop will run till the value of a is less than 11. As soon as the condition becomes false the loop terminates. Therefore the values that will be printed as 1,2,3…10. This is not a perfect example of while since the value 10 is fixed but it is a good example to start with. Lets create some more sensible while examples.

Example 2 : program to accept numbers from the user till he enters a negative number

void main()

{

int num;

while(num>=0)

{

printf(“\nenter a number : “);

scanf(“%d”,&num);

}

}

The above program will prompt the user to enter any values. The user will continue to enter values as long as they are positive. The moment he enters a negative value the condition will become false and the loop will terminate.

Example 3: running the program as long as the user wishes

void main()

{

int num,square;

char ch=’y’;

while(ch==’y’)

{

printf(“\nenter a number : “);

scanf(“%d”,&num);

square=num*num;

printf(“\nsquare of the number is %d”,square);

fflush(stdin);

printf(“\ndo you want to continue : “);

scanf(“%c”,&ch);

}

Example 4 : Program to ask password from the user until he enters the correct password

void main()

{

int pass,cnt=0;

while(pass!=786)//assuming that the correct password is 786

{

printf(“\nguess the password : “);

scanf(“%d”,&pass);

cnt++;

}

printf(“\ncorrect. you took %d chances”,cnt);

}