Advice On Computer Concepts - Programming Using C : Lesson 3
posted on 08/04/2009
Having equipped ourselves with the data types and operators we now have to check out the control structures that would finally be used to implement a logic in programming
The if-else statement
The if statement is used to check a condition and do what is expected if the condition fails under if and do what is required when the condition fails under else part. The if can be nested to take care of more complex conditions.
Example
----------------
In the example below we see that based on the value of a being 5 or not b gets a 3 or a 10. This is a simple usage of if statement.
if (a == 5)
{
b = 3;
}
else
{
b = 10;
}
While Loop
The while loop is for iterating over a period of time until a condition is not met. If for example we need to keep looping till user hits exit button in a program that can be taken care of using while
Example
--------------
When user hits exit a will get a value of 100. We can continue doing whatever we want till then
a = 0;
while (a != 100)
{
/* Do whatever is required here */
}
Now initially a is 0 and hence while condition is met and we do in. But when a finally gets a 100 (user hits exit) we come out of the loop
For Loop
This loop is usually used when the number of iterations is known in advance. If there are 60 students in a class and we need to print each student's name. We can use for loop to go around 60 times printing the student's name
for (i=1; i<=60; i++)
{
/* Get and print the ith student's name */
}
After printing 60 names the condition fails and it comes out of the loop
Basic input output
In C basic input output is handled by a standard libary called stdio.h. This file can be included in the program and then we can use the functions present in it
printf
------------
For printing stuff out (in the console) we use printf function. This is used to print names and numbers also. To print names we use %s and for numbers we use %d (for int) and %f (for float)
printf ("How are you");
printf ("%s", "my name");
printf ("%d", 5);
scanf
-----------
For getting input to a variable from user we use scanf. This gets numbers (int and float) and names also.
int d;
float f;
char s[100];
printf ("Enter one integer, one float and one name : :);
scanf ("%d",&d);
scanf ("%f",&f);
scanf ("%s", &s);
Note that we give a & in front of the variables. All this will be dealt with in greater detail in the advanced concepts section. In the next article we will put all that we have learned so for in our first C program



Comment on this article
You must be logged in to post comments.
Previous Comments