Friday, October 30, 2009
Arrays
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);
}
The Nested If
Nested if refers to an If statement within another if statement. Is shouldn’t be mixed with multiple if statements where a program contains more than one if condition. Nested if statement first checks the outermost condition to see whether it is true, then proceeds to the inner if condition. If the outermost condition is false the program will skip all the inner conditions and will directly process the else part. Lets first compare it with multiple if
If (x>0)
printf(“\nX is a positive number”);
else
printf(“X is a negative number”);
If(x%2==0)
printf(“\nX is an even number”);
else
printf(“\nX is an odd number”);
The above program will process the second if irrespective of whether the first condition was true or not. Which means that if we enter X as 10, the first if evaluate to true since it is a positive number. The second if will also result in true since x is an even number and dividing it by 2 will yield 0. Note that since both the conditions are different the second condition will be processed even if the first condition evaluates to false. Now compare it with nested if :
If (x>0)
{
printf(“\nX is a positive number”);
if(x%2==0)
printf(“\nX is an even number”);
else
printf(“\nX is an odd number”);
}
else
printf(“X is a negative number”);
The above program is an example of nested if because the second if statement starts and ends within the first if condition. So if we enter a negative value the first condition will become false and the program will jump to the else part and will print “X is a negative number” without checking the inner condition.
Here’s is the syntax
if(outercondition)
{
if(innercondition)
Statements if innercondition is true
else
Statements if innercondition is false
}
else
statements if outercondition is false
Example 2:
Lets write a program that will check the username and password of a user and prints the appropriate error message.
void main()
{
char name,pass; //single char username and password
printf(“\nEnter username : “);
scanf(“%c”,&name);
printf(“\nEnter password : “);
scanf(“%c”,&pass);
if(uname==’A’)
{
if(pass==’$’)
printf(“\nUsername and password are valid. You can login”);
else
printf(“\nInvalid Password”);
}
else
printf(“\nInvalid username”);
Output (If both inputs are correct)
Enter username : A
Enter password : $
Username and password are valid. You can login
Output (If password is incorrect)
Enter username : A
Enter password : %
Invalid Password
Output (If username is incorrect)
Enter username : G
Enter password : $
Invalid username
Saturday, October 10, 2009
Using the logical operators with If
There will be situations where we want to use more than one condition at a time. For example if a company gives promotions to its employees based on two conditions a) They should have an experience of more than 3 years and b) They should score more than 7 points in personal interview. Now an employee has two conditions to fulfill – his/her experience should be more than 3 years and at the same time he/she must score more than 7 points. In such cases where there are multiple conditions we can use either and which is symbolized as ‘&&’ and or which is represented as ‘||’. The && (and) operators combines two or more given conditions and if all of them evaluate to true returns the result as true. On the other hand || (or) will return true if even one of the given conditions is true. Let’s start with && which uses the following logical table
True + True = True
True+ False = False
False+ True = False
False+ False = False
As evident from the above table, and operator when used will yield TRUE only if all the given conditions are true, otherwise it will return false.
Example 1
void main()
{
int experience,points;
printf(“\nEnter Your Experience (In Years) : “);
scanf(“%d”,&experience);
printf(“\nEnter points scored in personal interview : “);
scanf(“%d”,&points);
if(experience>3 && points>7)
printf(“\nYou will be promoted”);
else
printf(“\nYou do not meet the specified criteria”);
}
Notes :
1. Read && as “And”.
2. The message “You will be promoted” will be printed only if both experience is more than 3 years and points are higher than 7. If any of these values is less the message given in the else part will be printed.
Here is the output if both conditions are true
Enter Your Experience (In Years) : 5
Enter points scored in personal interview : 9
You will be promoted
If one condition fails, here is what you will see
Enter Your Experience (In Years) : 2
Enter points scored in personal interview : 8
You do not meet the specified criteria
Example 2
void main()
{
float height,speed;
char grade;
printf(“\nWhat is the height of the candidate “);
scanf(“%f”,&height);
printf(“\nWhat was the speed in seconds to compelte 100 meters “);
scanf(“%f”,&speed);
fflush(stdin);
printf(“\nWhat was the grade in the written examination “);
scanf(“%c”,&grade);
if(height>6.0 && speed<=13 && grade==’A’)
printf(“\nYou have cleared the first phase of selection”);
else
printf(“\nSorry ! You have failed in at least one parameter”);
}
Note :
1. There can be as many conditions joined by &&.
2. If you enter a small ‘a’ as grade, the condition will become false.
The OR(||) operator
The Or operator is a bit different from && as it returns true even if any of the given conditions is true. It uses the following logical table
True + True = True
True+ False = True
False+ True = True
False+ False = False
As given in the above table OR will return false, if all the conditions are false.
Example 1
void main()
{
int sub1,sub2,sub3;
printf(“\nEnter marks in subject 1 “);
scanf(“%d”,&sub1);
printf(“\nEnter marks in subject 2 “);
scanf(“%d”,&sub2);
printf(“\nEnter marks in subject 3 “);
scanf(“%d”,&sub3);
if(sub1>=60 || sub2>=60 || sub3>=60)
printf(“\nPASS”);
else
printf(“\nFAIL”);
}
The if - Else if Statement
There will be many cases where just an if - else won't work, since it can include just one condition. If there are multiple conditions to evaluate we can use the if-else if statement. Consider the following program where we want to find out profit or loss of a particular transaction.
void main()
{
int cp,sp;
printf(“\nEnter cost price : “);
scanf(“%d”,&cp);
printf(“\nEnter selling price : “);
scanf(“%d”,&sp);
if(sp>cp)
printf(“\nProfit”);
else
printf(“\nLoss”);
}
If the program in run and we enter 100 as the cost price and 200 as the selling price, we will see that the program will display the result as profit since the condition has resulted in true. On the other hand had we entered cost price as 200 and selling price as 100 the result would have been “Loss”. But what if we enter 100 as both the selling price and cost price? Enter the same value (100, 200 or whatever) at both the places you will see that the result will displayed as “Loss” !!. Why is this happening is pretty simple, just because when you enter same value, say 100 at both the places the condition becomes false since 100 is not greater than 100 and therefore prints “Loss”. To correct the problem we can introduce the else if statement in our program. Check the correct version yourself.
void main()
{
int cp,sp;
printf(“\nEnter cost price : “);
scanf(“%d”,&cp);
printf(“\nEnter selling price : “);
scanf(“%d”,&sp);
if(sp>cp)
printf(“\nProfit”);
else if (cp>sp)
printf(“\nLoss”);
else
printf(“\nNo profit or loss”);
}
As you can see now the else if statement is taking care of “cp being higher than sp” and if it is it will again print “Loss”. Now if we enter 100 again in both prompts the compiler first checks if sp (which is 100) is greater than cp (which also is 100). Since 100 is not greater than 100 it skips to the else if part, incidentally the same processing happens again and 100 is again compared with 100. Since both the above conditions are false the only option left for the compiler is to execute the statements given in the else part. Therefore the result will be “No profit or loss”.
Remember
1. Place a space between else and if.
2. You can use as many else if in a program but there can be only one else statement and that too at the end.
Example 2 – Menu Based Program
A menu based program simply refers to a program that displays a list of available options to the user and proceeds as per the choice made. Take a look
void main()
{
int option;
printf(“\nMain menu”);
printf(“\n1. Air ticket”);
printf(“\n2. Train ticket”);
printf(“\n3. Bus ticket”);
printf(“\nSelect your mode of transport”);
scanf(“%d”,&option);
if(option==1)
printf(“\nRs. 25000”);
else if(option==2)
printf(“\nRs. 500”);
else if(option==3)
printf(“\nRs. 230”);
else
printf(“\nInvalid choice selected by the user”);
}
The above program displays a list of option to the user to select from. When run, the output will look like this
1. Air Ticket
2. Train Ticket
3. Bus Ticket
Select your mode of transport
Now if the user enters “1” as his choice the program will display the result as “Rs. 25000” but if you enter your choice as “2”, it will display Rs. 500 and Rs. 230 if 3 is entered. If we enter 2 or 3 as our input the compiler doesn’t directly jump to the else if statement. It will start comparing the conditions one by one and will evaluate the result accordingly. If any other choice is made except 1,2 or 3 all the above given condition will evaluate to false and the program will display the “Invalid Choice” message.
Menu Based Program Using char Input
We can also create a menu based program using character input. The only difference is that we will have to use single quotation (‘’) marks. Consider the example given below.
void main()
{
char op;
int no1,no2,result;
printf(“\nEnter first number “);
scanf(“%d”,&no1);
printf(“\nEnter second number “);
scanf(“%d”,&no2);
fflush(stdin);
printf(“\nEnter a symbol like (+,-,*,/) “);
scanf(“%c”,&op);
if(op==’+’)
{
result=no1+no2;
printf(“\n Addition of both the numbers is %d”, result);
}
else if if(op==’-’)
{
result=no1-no2;
printf(“\n Subtraction of both the numbers is %d”,result);
}
else if(op==’*’)
{
result=no1*no2;
printf(“\n Product of both the numbers is %d”, result);
}
else if(op==’/’)
{
result=no1/no2;
printf(“\n Division of both the numbers is %d”, result);
}
else if(op==’%’)
{
result=no1%no2;
printf(“\n Remainder of both numbers is %d”, result);
}
else
printf(“\n Unrecognised Symbol Entered”);
The above program will ask the user to enter two numbers and an operator (mathematical symbol). It will print the result as per the symbol entered. The output will look like
Enter first number 25
Enter second number 5
Enter a symbol like (+,-,*,/) +
Addition of both the numbers is 30
Notice the use of “fflush(stdin)”. It is written here because sometime C does not allow the user to enter integer and character values successively. If you remove the fflush() statement chances are that the program will terminate unexpectedly.