Pages

Wednesday, December 16, 2009

Local and global variables

According to the declaration, variables can be of two types – local and global. The variable which are declared inside a function are called “local” variables which those variables that are defined outside a function are called “global” variables.

Local variables
Any variable which has been declared inside a function is called its local variable. The name local denotes that the variable is accessible from within the function it which it is declared. It cannot be used from outside the function. Local variables are also called “private” variables since they are kind of “private property” of a function. We can declare many variables with the same name provided that all of them are declared in different functions.



Example 1 : Working of a local variable


void main()


{


int local=10;


void display();


display();


printf(“\nvalue is %d”,local);


}


void display()


{


int local=20;


printf(“\nvalue is %d”,local);


}


Output


value is 20


value is 10


Description


As you can see we have declared a variable named “local” both in the main() and in display(). The “local” variable declared inside main() has the value 10 while the one declared in display() as the value 20. When the function is called the value 20 is printed first and then 10 is printed. It is quite clear that both the functions are displaying their own value of the variable.





Example 2 : Understanding the function of a local variable






void main()


{


void calculate();


int data;


data=1000;


calculate();


printf(“\nIn main data is %d”,data);


}


void calculate()


{


int data;


data=2000;


printf(“\nIn calculate data is %d”,data);


data+=1000;


}






Output


In calculate data is 2000


In main data is 1000


Description


There are two local variables named “data” each in main () and data(). Before printing the value of data of main, the function is called. Inside calculate () there is another variable with the name “data” which has a value of 2000. After printing 2000 the value is incremented by 1000 making it 3000 but since there is no printf() after it, we won’t see 3000 printed on the screen. After returning to main() , the value of data which was available in main() which is 1000 is printed. The increment has no effect in the main since there are two “data” variables. The “data” of calculate() will be incremented and not the one declared in main()





Example 3 : Local variables and multiple functions






void main()


{


void fun1();


int value=1;


fun1();


value=value+1;


printf(“\nIn main value is %d”,value);


}






void fun1()


{


int value=2;


void fun2();


fun2(); //calling fun2


value=value-1;


printf(“\nIn fun 1 value is %d”,value);


}


void fun2()


{


void fun3();


int value=3;


printf(“\nIn fun2 value is %d”,value);


fun3(); //calling fun3


}


void fun3()


{


int value=4;


printf(“\nIn fun 3 value is %d”,value);


value=value+1;


}






Output


In fun2 value is 3


In fun 3 value is 4


In fun 1 value is 1


In main value is 2










Description


The above program has four function (main(),fun1(),fun2() and fun3()) . All of these functions have a declaration of the variable “value”. Since each function has declared a variable with the same name, there are four different variables with the same name “value”. The compiler starts processing from main() where main declares “its” value variable with the value 1,but before it can get printed the function fun1() is called. The compiler leaves the main() midway and goes to fun1() where another variable “value” is declared with a value of 2. fun1() contains a call to fun2() so the compiler goes on to call fun2(). The printf() inside fun2() is the first value to be printed which is 3 after which the compiler moves to fun3(). The variable declared inside fun3() has the value 4, this is the second value to be printed. After printing 4 the value is incremented by 1. But since there is no printf() after than 4 is not printed. When fun4() has finished its processing the control returns to the calling function which is fun3(). Now that the processing of fun3() is also finished the program returns to the calling function of fun3() which is fun2(). Inside fun2 the value is decremented by 1, remember that all the declarations are local therefore the decrement will take place on the value declared inside fun1() which is 2. After decrementing the result is printed therefore 1 is the next value to be printed. When fun1 () is also finished the controls move to main() since it called fun1() where again 2 is printed which was the local value of the variable.



Global Variables


Variables which are does not fall under a particular function are called global variables. Such variables are declared outside a function scope. Sometimes all referred to as public variables, global variables are accessible from any function within a program.


Example 1 : Using a global variable


int points=10


void main()


{


void show();


printf(“\nPoints in main %d”,points);


points+=10;


show();


}


void show()


{


printf (“Points In show %d”, points);


}


Output


Points in main 10


Points in show 10


Description


The above example declares a variable above “main ()” named points. Since “points” is declared outside main () or any other function it is not a local variable of any function. The value of points is first printed inside main then the value is incremented by 10 making it 20. When the show () is called it will print the incremented value which is 20. As you can see the value of points is shared by both main () and show () and if it is modified in one function the change can be seen in the other function.






Example 2: Declaring a local and a global variable with the same name.






int sample=100; // Global Variable


void main ()


{


int sample=200; // Local Variable


printf(“\nLocal variable %d”,sample);


printf(“\nGlobal variable %d”,::sample); // printed using double colons ( : : )


}


Output


Local variable 200


Global variable 100


Description

If a program has both local and global variable with the same name, then by default the value of the local variable will be processed. If we want to print the global variable then we must prefix the variable name with the symbol :: , called the scope resolution operator. This operator will help the compiler differentiate between the local and the global variable. The scope resolution operator is not required if both the names are different.

Return value

  • What is return value?


The value or output returned by a function is called return value. There are two ways a function can work, first is by printing the result itself within its own body and second is by returning the result to the calling function. Those functions which return a value are called functions with return value.

  • Types of functions on the basis of return value

As discussed in previous posts functions can be categorized according to different criteria like on the basis of declaration the functions are divided as library functions and user defined functions. Another criteria is on the basis of arguments, again we have two varieties, function with arguments and functions without arguments. Similarly we can divide functions on the basis of return value also.

a) functions without return value: functions which do not return a value are called functions without return value. Such functions work by printing the final output themselves. functions like printf(),scanf(),clrscr() are functions without a return value.

b) functions with return value: Although functions without return value are quite capable, there may be some conditions where a return value will be needed. In such a scenario we will have to create a function with return value. Such functions instead of managing the output themselves return the output to the calling function, letting the calling function decide what to do with the output. The calling function can print the value as it is or it can use this value for further processing. Library functions like strcmp(), strlen() are some of the examples of this type.

  • Why do we need return value functions?

Whenever a function is called it is not necessary that the output the function has achieved is the final result. Sometime it can happen that the output is an “intermediate” output and not the final output. Such intermediate output can be sent back to the calling function for final decision. The calling function will have the final say in deciding what to do with the value it has received from the called function. It can print the value as it is or can keep the value for any future processing.

  • How to distinguish between functions with and without return value?

It is quite easy to tell whether a function is returning value or not by looking at its declaration. All the functions which do not return a value are declared using the keyword “void” which means null or nothing. if a function starts with “void” then it is a kind of signal to the compiler that it won’t be returning any value. On the other hand functions that return a value do not start with void instead they have the datatype written in place of void. The datatype will obviously depend on the type of value the function is returning like int or float.



Syntax – functions without return type

void funname()


{


function body;


}



Syntax – functions with return value

datatype funname()


{


function body;


return value;


}

Note that the first declaration starts with the keyword “void” which means that function will not return a value.





Example 1 : Basic return value program

void main()


{


int show(int);


int a,b;


printf(“\nEnter a value “);


scanf(“%d”,&a);


b=show(a);


printf(“\nreturned value is %d”,b);


}


int show(int x)


{


x+=10;


return x;


}



Output

Enter a value 20


returned value is 30



Description

The first line declares a function using the statement “int show(int”). the “int” before show() denotes that the function will return an integer value while the “int” written as argument denotes that the function will take an integer as input. We can also say that the function show will take an integer as input and will return another integer as output. Since the function is declared with an integer value we must declare an extra variable that will handle the returned value. The statement “b=show (a)” denotes that the function will be passed the value of “a” as argument and the value returned by the function will be stored in the variable “b”. When the function is called the value of “a” is passed to “x”, show() increments the value by 10 and returns the incremented value to the calling function which is main(). The returned value (30) is stored in b and this value is then printed.

Example 2 : Program to print cube of the square of a number.




In the following program we want the user to enter a number and the program will calculate the cube of the square of the number. For example if the user enters 2 the value 64 will be printed since 64 is the cube of 4 which is the square of 2.

No. -->  Square --> Cube of square

2 --> 4 -->  64



void main()


{


int square(int);


void cube(int);


int num,sq;


printf(“\nEnter any numeric value “);


scanf(“%d”,&num);


sq=square(num);


cube(sq);


sq=square(4);


printf(“\nSquare of 4 is %d”,sq);


}


int square(int n)


{


int s=n*n;


return (s);


}


void square(int n)


{


int c=n*n*n;


printf(“\nSquare is %d”,c);


}



Output

Enter any numeric value 2


Square is 64


Square is 16



Description

The value entered by the user is passed as an argument to the function square. Square calculates the square of that number but instead of printing the result returns it to main. main() stores this value in the variable “sq”. Since this is not the final output it is sent to cube() to calculate cube. The second time when square is called we don’t want to print the cube of its square. Therefore when square returns the square of 4 it is again stored in sq and printed as it is.



Example 3 : returning a character value.



void main()


{


char showgrade(int);


char gr;


int salary;


printf(“\nEnter your basic salary “);


scanf(“%d”,&salary);


gr=showgrade(salary);


printf(“\nGrade according to the salary is %c”,gr);


}


char showgrade(int sal)


{


char g;


if(sal>=1 && sal<1000)


g=’D’;


else if(sal>=1000 && sal<5000)


g=’C’;


else if(sal>=5000 && sal<10000)


g=’B’;


else if (sal>=10000)


g=’A’;


return (g);


}



Output

Enter your basic salary 4500


Grade according to the salary is B

Description

The function prototype “char showgrade(int)” signifies that the function will return a char value while the argument is of integer type. When the salary is passed as argument the showgrade() will return the grade of the employee as per the salary entered. The returned value is copied to the variable “gr” in main where it is printed. You can also call the function by a statement like “showgrade(2300)” since 2300 is also an integer value.



Example 4: returning a float value

void main()


{


float bankloan(char);


char type;


float interest;


printf(“\nH. Home Loan”);


printf(“\nE. Education Loan”);


printf(“\nP. Personal Loan”);


printf(“\nSelect a loan type (H,E,P) : “);


scanf(“%c”,&type);


interest=bankloan(type);


if (interest==0)


printf(“\nInvalid loan type selected”);


else


printf(“\ninterest rate of this category is %f”,interest);


}


float bankloan(char ty)


{


float roi; // rate of interest


if (ty==’H’  || ty==’h’)


roi=8.5;


else if (ty==’E’  || ty==’e’)


roi=11.25;


else if (ty==’P’  || ty==’p’)


roi=12.75;


else


return 0;


return roi;


}

Output

H. Home Loan


E. Education Loan


P. Personal Loan


Select a loan type (H,E,P) : P


Interest rate of this category is 12.75



Description

The above function has a return value of float while the input value of char. The user selects a type of loan from the given menu (H for home, E for education and P for personal). The function checks the loan type and accordingly returns the interest applicable on it. The return value is sent to the variable “interest” and then printed. if the user enters an invalid choice the function returns 0 and “Invalid loan type selected” message is printed.

Monday, December 7, 2009

Function with arguments

What are arguments ?
Functions can also be categorized on the basis of arguments. Argument or parameter is the value that we pass to a function while calling it. for example while calling the printf(), we always the message that we want to print on the screen, like printf(“Hi there !!”). The value or message written inside the circular brackets is called the argument. Of course, not all functions accept values inside like clrscr(),getch() etc. such functions are called functions without arguments.


Why do we need arguments?

Imagine a program that wants to perform addition,subtraction,product and division on a single pair of values. if we create four different functions for this purpose one each for addition, subtraction and product, we will have to write the code to get the input from the user in each function since we cannot pass values from a function to another. Consider the following example

void main()


{


void add();


void product();


void subtraction();


void division();


add();


product();


subtraction();


division();


}


void add()


{


int a,b,c;


printf(“\nEnter first number “);


scanf(“%d”,&a);


printf(“\nEnter second number “);


scanf(“%d”,&b);


c=a+b;


printf(“\nAddition is %d”,c);


}


void subtraction()


{


int a,b,c;


printf(“\nEnter first number “);


scanf(“%d”,&a);


printf(“\nEnter second number “);


scanf(“%d”,&b);


c=a-b;


printf(“\nSubtraction is %d”,c);


}


void product()


{


int a,b,c;


printf(“\nEnter first number “);


scanf(“%d”,&a);


printf(“\nEnter second number “);


scanf(“%d”,&b);


c=a*b;


printf(“\nProduct is %d”,c);


}


void division()


{


int a,b,c;


printf(“\nEnter first number “);


scanf(“%d”,&a);


printf(“\nEnter second number “);


scanf(“%d”,&b);


c=a/b;


printf(“\nDivison is %d”,c);


}



As you can see, we have to take input in each function causing the program to lengthen. We cannot move the values of “a” and “b” from one function to another since they are all local variables. The solution to this problem is the use of arguments. Arguments or parameters can be moved to another function so that we don’t have to input the values again and again.

Example : Using arguments


void main()

{


void add(int,int);


void product(int,int);


void subtraction(int,int);


void division(int,int);


int a,b,c;


printf(“\nEnter first number “);


scanf(“%d”,&a);


printf(“\nEnter second number “);


scanf(“%d”,&b);






add(a,b);


product(a,b);


subtraction(a,b);


division(a,b);


}


void add(int a,int b)


{


int c;


c=a+b;


printf(“\nAddition is %d”,c);


}


void subtraction(int x,int y)


{


int z;


z=x-y;


printf(“\nSubtraction is %d”,z);


}


void product(int i,int j)


{


int k;


k=i*j;


printf(“\nProduct is %d”,k);


}


void division(int m,int n)


{


int o;


o=m/n;


printf(“\nDivison is %d”,o);


}

Description

After accepting values from the user and saving them in a and b the first call is made to the add(). Notice that inside the circular brackets the values a and b are written (a ,b). This is called passing arguments to a function – in this case a and b are arguments while “add” is the name of the function. When the compiler sees that a call is made to add() it will copy the values of a and b defined in main() to the arguments a and b given in the definition of add(). Which means that the value of a will be copied to a and b will be copied to b. inside the add (), c will add both the values and the result is printed. After this the second function subtraction is called using the same arguments (a and b) but this time their value are copied to x and y which are defined in the subtraction () definition. Similarly values of and b are copied to I and j in product() and to m and n in division. The main benefit of using arguments in this program is that we don’t have to ask the user to enter values in all the functions. The values have been entered just once and are copied to all the functions using arguments.

Points to remember

1. The argument given while calling the function is called actual arguments, while the arguments given in the function definition are called formal arguments.

2. The names of the formal and actual arguments can be same or different.





Example : Calculating area of circle using functions with arguments






void main()


{


clrscr(); // to clear all previous messages on the screen (optional)


void area(int r); // prototyping the function with the name area and one integer arg.


int radius;


printf(“\nEnter Radius Of The Circle : “);


scanf(“%d”,&radius);


area(radius);//calling the function with user defined radius as argument


area(4); // calling the function with a constant


}


void area(int rad)// the value of radius will be copied to rad


{


float ar;


ar=3.14*r*r; // calculating area of circle using the formula pi * radius * radius


printf(“\nArea of circle is %f”,ar);


}



Description

As you can see the function is declared to accept an integer value as argument and therefore must be given while calling it. Before calling the function for the first time, the user is prompted to enter a value as radius. After this the function is called with the statement “area(radius)”. At this point the value of the actual argument “radius” is copied to the formal argument “rad” declared in the function definition. The area function calculates the area using the mathematical formula “3.14*radius*radius”. When the area is printed the control returns to the calling function (which is main()) which again calls the function with a constant value of 4. Please note that the function need an integer value to run. Whether this value is being provided by the user as in the first case or if it is a fixed value like in the second case is immaterial. The function definition does not care how the argument is passed – by the user or as a fixed value – as long as the method of passing the value is correct.



Example : Calling a function with arguments passed in four ways



void main()


{


void si(int,float,float);


int p;


float r,t;


printf(“\nEnter Principle Amount : “);


scanf(“%d”,&p);


printf(“\nEnter Rate Of Interest : “);


scanf(“%f”,&r);


printf(“\nEnter Time Duration : “);


scanf(“%f”,&t);


si(p,r,t);// function call with user values


si(4000,5.3,3.2); // function call with constant values


si(p,6.4,4);// calling the function with a user defined value and two constants


si(4000+2000,r,t*3); // calling the function with different type of arguments.


}






void si(int princ,float rate,float time)


{


float s=(princ*rate*time)/100;


printf(“\nSimple Interest is %f”,s);


}



Description

In this example a function named “si” is declared to calculate simple interest. The function has three arguments one integer and two floats. The function has been called four time 1) With the values entered by the user 2) With fixed values 3) With a combination of user entered values and constants 4) With a formula result, user entered values and again a formula result.

As exaplained earlier the function has nothing to do with the way the arguments are passed to it. It will only check whether the number of arguments is correct and whether the datatype of arguments is matching or not. If these things are correct it will calulcate and print the result.

Wednesday, December 2, 2009

Creating a function

Creating a user defined function
To create a user defined function we have to carry out three basic tasks.
1. Prototype the function (declaration) : Just like a variable a function must also be declared prior to its use. The term “prototyping” is more used instead of the term “declaring”. To prototype the function the following syntax is used returntype functionname(args);
Example : void func1();void test();int square();float interest();
2. Define the function (Function body) : Declaration just tells the compiler about the name, arguments and return value of the function, what it doesn’t tell is what the function will do. The function definition or the function body tells what the function will do.
3. Call the function (Execution) : To see how a function works it must be called explicitly from the program. If we fail to call it we won’t be able to see its output. Therefore it is compulsory to call the function to see it working


Example 1 : Function to print a “Hello World” message.
void main()
{
void hello(); // function prototype
hello(); // function calling
printf(“\nEnd of the program”);

}
void hello() // function definition

{
printf(“Hello World”);
}
Output

Hello World
Description
The statement “void hello()” declares the function. The declaration part starts with the keyword “void” which tells the compiler that the function will not return any kind of value. Some functions do return a value and therefore do not start with “void”. “hello” is the function name which can be any valid name. The rules of naming a function are quite same as those of naming a variable – it shouldn’t contain any space, no symbol is allowed except an underscore, shold begin with a letter or underscore. After prototyping the function the next statement “hello()” calls the function. When the compiler reaches the function call it searches for the function definition which is given at the end of the main(). The body contains just one statement which is “printf(“Hello World”)”. This message is printed and the control moves back to main() which prints “End of the program”.

Note that the main() contains a call to the hello(). Therefore in this example main() will be called the “calling function” and the function which is being called (hello – in this example) will be called the “called function”. After the call to the calling function is complete the control returns to the calling function. A called function cannot close the program. One question which arises here is – if main() is calling hello(), who is calling main() ? the answer is “the compiler or the C software” . the compiler is preprogrammed to search for the main() and start its execution from there. Once the execution of main() begins, it the main() which decides what next to do. In this example main() decides to call hello() apart from printing the message “End of the program”.

Example 2 : Finding out greater number using functions


Keep in mind that functions do not teach a new logic to create a program or solve a problem rather they teach you a different approach towards it. Therefore if you want to create a program using functions the basic logic of the problem will remain same the only thing that will change is that we will divide the program into small functions



void main()


{


void great();//prototype


great(); // function call 1


printf(“\nOther code between the two function calls”);


great();// function call 2


}


void great()


{


int a,b;


printf(“\nEnter any value : “);


scanf(“%d”,&a);


printf(“\nEnter second value : “);


scanf(“%d”,&b);


if(a>b)


                printf(“\nFirst number is greater “);


else if(b>a)


                   printf(“\nSecond number is greater”);


else


                printf(“\nBoth the numbers are equal”);


}

Output

Enter first value : 230


Enter second value : 401


Second number is greater

Description

As you can see there is nothing new inside the function definition. It contains a basic if – else comparison to find out the greater number. So why are we creating a function for it ? The reason has already been explained in the introduction that now if we want to do the same comparison again for another pair of values we don’t need to write the code again. We can just call the function as many times as we want. But can’t it be done using a loop ? yes, of course. But remember that a loop runs continuously without interruption whereas a function is called as and when required. Therefore we can easily do some other tasks between two function calls which we can’t with a loop. Take a look at the next example for more information.



Example 3 : Write a program to first find out the square of a number, then cube of a number and again square of a new number.



Solution

Method 1 : Without using a function or a loop.



void main()


{


int num,square,cube;


printf(“\nEnter the number whose square is to be found : “);


scanf(“%d”,&num);


square=num*num;


printf(“\nSquare is %d”,square);


printf(“\nEnter the number whose cube is to be found : “);


scanf(“%d”,&num);


cube=num*num*num;


printf(“\nCube is %d”,cube);






printf(“\nEnter the number whose square is to be found : “);


scanf(“%d”,&num);


square=num*num;


printf(“\nSquare is %d”,square);


}



Description

The program will ask the user to enter a value and after printing its square will ask the user to enter another value for cube. Once the cube is also printed the program will once again ask for another value to determine the square. The problem ? We are writing the same code of calculating the square twice leading to wastage in terms of memory, time and effort. Let’s see if a loop can provide a solution



Method 2 : Using a loop



void main()

{


int num,square,cube,i;


for(i=0;i<2;i++)


{


printf(“\nEnter the number whose square is to be found : “);


scanf(“%d”,&num);


square=num*num;


printf(“\nSquare is %d”,square);


}


printf(“\nEnter the number whose cube is to be found : “);


scanf(“%d”,&num);


cube=num*num*num;


printf(“\nCube is %d”,cube);


}

Discussion

if you compare both the above methods, you can easily see that the second method is quite short when compared to the first method. So have we found a solution to the problem without having to create a function ? Not exactly. if you can recall the problem wanted the following sequence of events – square, cube and again square. The first method(without loop) though lengthy is following the sequence but the second method is not at all following the correct sequence of events. It will process the result as square,square,cube which is not at all required. Therefore it can be concluded that the first method is lengthy while the second method is not processing the result it the correct sequence. Enter Functions and both the problems will be solved. The program will not only be short but also in correct sequence.



Method 3 : Using functions

void main()


{


void square();


void cube();


square();


cube();


square();


}


void square()


{


int num,square,cube;


printf(“\nEnter the number whose square is to be found : “);


scanf(“%d”,&num);


square=num*num;


printf(“\nSquare is %d”,square


}


void cube()


{


int num,cube;


printf(“\nEnter the number whose cube is to be found : “);


scanf(“%d”,&num);


cube=num*num*num;


printf(“\nCube is %d”,cube);


}



Description

Inside main() first we have called the square() which will print the square followed by the calling of cube. To calculate square again all we have to do is to call it again. As compared to the above two methods we didn’t have to write the code twice and even the sequence is correct.

Functions

In our day to day life we depend on several individuals to us in our daily activities. Like we depend on the plumber to fix the taps and pipes, carpenter to mend our furniture etc. we cannot perform all these tasks alone so we need the help and support of these persons. When we need their services we call them, they visit our place, perform the tasks and leave. Similarly in a program all the tasks cannot be performed by a single function or code. We’ll require many small programs to carry out the various tasks for us. These small programs are called functions.
By definition, function is “a small program that has a name and a particular task”. Of course, there are many predefined functions in C but since the requirements vary from user to user we cannot have a predefined function for every occasion. Therefore we need to create our own functions called “User Defined Functions”. A user defined function or UDF is a function created by the user as per his/her requirements.

Types of functions on the basis of declaration

On the basis of declaration we can divide functions in two categories

  1. Library functions : Those function which come precompiled in the language are called library functions or inbuilt functions. All such kind of functions is declared in some header files which must be included prior to calling these functions. For example the library function strcmp() is defined in the header file string.h, clrscr() in conio.h and isalpha() in ctype.h. The user is not required to create these functions as they are already declared in their respective header files.
    Examples : printf(),scanf(),strcmp(),strcpy(),clrscr(),getch() etc.
  2. User defined function: Functions which are declared by the user as per his/her need are called user defined functions. Since they are not pre-defined the user to provide all the definition to make it work. There can be no specific example of a user defined function since it depends on the user requirements.
Advantages of functions

1.
Functions encourage the concept of modular programming where a large problem is divided into small manageable chunks. These small parts are easy to understand and debug than a large problem.
2. One of the biggest advantages of a function is its reusability. A function once declared can be used again and again without having to retype the whole code.
3. Reusability in turn offers many other benefits like saving on resources. If a function can be called multiple times it saves both primary and secondary memory.
4. The time taken in compiling the code is also reduced since a function will be compiled just once irrespective of how many times it is being called.
5. Functions are tested for errors only once. Once the errors are removed we can call it as many times as we want.

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);

}

Loops

Loops or iterative statements are a very important ingredient of a good program. They can be defined as statements which repeats a block of code continuously. They are used when we want to execute a particular statement or statements till the user wishes. Without a loop if the user want to perform a particular task repeatedly he/she will have to write the code again and again manually. Copy/paste utility will save us from the trouble of typing but the program length will increase even then. The following drawbacks of manual typing proves that it is not a good idea to repeat the same code again and again.

1. More memory : More lines of code will require more memory to compile and to store the program in the disc.

2. More time : Typing the code again and again will need more time. More effort will be needed to type the code.

3. Difficult to debug : A large program will also be difficult to debug(making it error free).

4. Inaccurate : To check whether it is running for the exact number of times as we wanted will have to checked by manual counting. This can cause inaccuracy since manual counting can be incorrect.

These problems are sufficient to prove that it is not a good idea to use manual coding to perform repeated tasks. The solution is Loops.

C offers three type of loops

1. For

2. While

3. Do –While

Let’s explore how “for” works


The for loop

For is a time based loop and is used when we already know that how many time a task is to be done. For example if we are asked to print a message say “Programming is fun” for 30 times we can use this loop since we know that the task it to be performed 30 times.

Syntax:

for(start;condition;increment/decrement)

{

loop body

}

Where

· Start : Denotes the starting point of the loop. This is the value from where the loop will begin it execution.

· Condition : the loop continues to run as long as this condition is true. As soon as the condition becomes false the loop terminates.

· Increment /decrement : increases or decreases the value of the variable so that at any point the condition becomes false.

Example 1 : To print “C is fun” 30 times

void main()

{

int i;

for(i=1;i<31;i++)

{

printf(“\n C is fun”);

}

}

Run the program and you will the message “C is fun” printed 30 times.

Note :

1. Use can use any other variable name instead of “i” like – for(a=1;a<31;a++)

2. Running the above code 30 times can also be achieved through the following statement since all of them have the same meaning :

a. for(i=1;i<=30;i++)

b. for(i=0;i<30;i++)

c. for(i=100;i<131;i++)

d. for(i=250;i<=280;i++)

let’s compare the program with the syntax mentioned above:

· for (i=1; -- is the start value. It denotes that the initital value of I will be 1 so the loop will start from 1.

· i<31>

· i++ : the third part informs the compiler to increase the value of I by 1. If this part is omitted I will not be incremented and hence will stay at 1 making the condition false forever. Such a loop is called a “Infinite loop”

Program 2 – Printing the counting from 1 to 100

void main()

{

int i;

for(i=1;i<=100;i++)

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

}

The output of the above program will be printing of numbers from 1 to 100. Inside the loop the value of i is being printed which increments by 1 after each step. It works like this :

i++ increments the value by 1 , similarly we can increment the variable by any other value by using the short hand assignment operator.

Program 3 – Incrementing the value by any other number

Let’s create a program to print even numbers from 1 to 50.

void main()

{

int i;

for(i=2;i<=50;i+=2)

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

}

Note that the above for statement has “i+=2” in the increment section. This will increment the value of I by 2 rather than 1. Therefore you will a series of 2,4,6,8,….48,50. As you can see it is fairly easy to change the increment value to any number. For example i+=5,i+=20 will increase the value by 5 and 20 respectively.

Decrement Loops

We can also write decrement loops which will instead of incrementing the value decrements it. For this we’ll just have to replace the increment operator (++) with the decrement operator (- -). Take a look at the following program that prints the same series created before but in decreasing order.

void main()

{

int i;

for(i=10;i>0;i--)

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

}

The above program will print the series 10,9,8,….1 since we are using (--) operator.


Some practical examples :

Example 1 : Program to print multiplication table of any number entered by the user.

void main()

{

int num,i,result;

printf(“\nEnter any number : “);

scanf(“%d”,&num);

for(i=1;i<=10;i++)

{

result=num*i;

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

}

}

Example 2 : program to print sum of 10 numbers entered by the user

void main()

{

int num,i,sum=0;

for(i=0;i<10;i++)

{

printf(“\nEnter a value : “);

scanf(“%d”,&num);

sum+=num;

}

printf(“\nSum of all numbers is %d”,sum);

}

Example 3 : program to print the details of the highest scorer of an examination

void main()

{

int i,rollno,topper_rollno;

float per,topper_per,max=0.0;

char name,topper_name;

for(i=0;i<10;i++)

{

printf(“\nenter the details of student number %d : “,i+1);

printf(“\nenter rollno : “);

scanf(“%d”,&rollno);

printf(“\nenter name : “);

scanf(“%c”,&name);

printf(“\nenter perecentage : “);

scanf(“%f”,&per);

if(per>max)

{

max=per;

topper_rollno=rollno;

topper_name=name;

}

}

printf(“\nfollowing are details of the topper : “);

printf(“\nrollno : %d”,topper_rollno);

printf(“\nname : %c”,topper_name);

printf(“\npercentage : %f”,max);

}

Example 4 : program to count number of even and odd values

void main()

{

int i,no,even=0,odd=0;

for(i=0;i<10;i++)

{

printf(“\nenter a value : “);

scanf(“%d”,&no);

if(no%2==0)

even++;

else

odd++;

}

printf(“\ntotal number of even values : %d”,even);

printf(“\ntotal number of odd values : %d”,odd);

}