"Learn C programming!"

4-1 More about "for" loops

   

4-1 More about "for" loops

As we saw in previous lesson we can use "for" statement to create a loop for executing a command or a block of commands.

for(initialization; test condition; run every time command)
command;

There are three parts inside condition phrase. Initialization statement you can initialize any variable including loop
counter or any other variable. In condition statement you can use any kind of logical statement that will specify the condition for loop execution. As we told later if this condition becomes false loop execution will terminate.

Last part is a statement that will be executed every time loop is being executed. In previous examples we used a statement like i++ and count++. These will increase the value of a variable each time loop is executed. Increase in this variable can change the loop condition section to false if the condition is based on this variable.

In this lesson we first see a more complex example of a "for" loop and then continue to new concepts.

Example 4-1:

Below example will print a multiplication chart (from 1*1 to 9*9). Run the program and see the results.


#include<stdio.h>
main()
{
int i,j;

for(i=1;i<10;i++)
{
for(j=1;j<10;j++)
printf("%3d",i*j);
printf("\n");
}
}

-----------------------------------------------------------------------------


4-2 "if" statement

Sometimes you will need a command or a block of commands to be executed when a condition exists or vice versa, when a condition does not exist.

if(condition)
command;

if(condition)
{
block of commands;
}

If statement is a branching statement because it provides a way to select a path from several paths in a program. If condition is true the command or block of commands will be executed.

Example 4-2:
What does this program do?

#include<stdio.h>
main()
{
int n;
printf("Enter a number: ");
scanf("%d",&n);
if(n>=0)
printf("Number is positive !\n");
if(n<0)
printf("Number is negative !\n");
}


Now let's see a more complex example.

Example 4-3:
Write a program to solve a second-degree equation ax^2+bx+c=0.

#include<stdio.h>
#include<math.h>
main()
{
float delta,a,b,c,x1,x2;

printf("Enter a : ");
scanf("%f",&a);
printf("Enter b : ");
scanf("%f",&b);
printf("Enter c : ");
scanf("%f",&c);
delta=b*b-(4*a*c);

if(delta<0)
{
printf("Equation has no answer !\n");
exit(0);
}

if(delta==0)
{
x1=-b/(2*a);
printf("Equation has two equal answers !\n");
printf("x1=x2=%f",x1);
exit(0);
}

x1=(-b+sqrt(delta))/(2*a);
x2=(-b-sqrt(delta))/(2*a);
printf("\nX1=%f",x1);
printf("\nX2=%f\n",x2);
}

-----------------------------------------------------------------------------


4-3 More complex "if" statements

Simple form of "if" statement gives you the choice of executing or skipping a command or block of commands. If in a program you decide to execute a command when condition is true and execute another command when it is false, you will need two simple "if" statements.

if(condition)
command;
if(!condition)
command

! Sign reverses the logical value of a Boolean expression. If it is true the result will become false with '!' sign and
vice versa.

There is another option. "if" statement has more complex forms. Below you see another form of "if" statement.

if(condition)
command;
else
command

In above statement there is an additional "else" section. When condition is true first command (or block of commands) is executed otherwise "else" section will be executed.

Example 4-3:

#include<stdio.h>
main()
{
int n;
printf("Enter a number: ");
scanf("%d",&n);
if(n>=0)
printf("Number is positive !\n");
else
printf("Number is negative !\n");
}

-----------------------------------------------------------------------------


4-4 A useful example and more complex "if" statement

Example 4-5:

#include<stdio.h>
#include<stdlib.h>
main()
{
int choice;

while(1)
{
printf("\n\nMenu:\n");
printf("1- Math Program\n2- Accounting Program\n");
printf("3- Entertainment Program\n4- Exit");
printf("\n\nYour choice -> ");
scanf("%d",&choice);

if(choice==1)
printf("\nMath Program Runs. !");
else if(choice==2)
printf("\nAccounting Program Runs. !");
else if(choice==3)
printf("\nEntertainment Program Runs. !");
else if(choice==4)
{
printf("\nProgram ends.\n");
exit(0);
}
else
printf("\nInvalid choice");
}
}


Above example is a very interesting example of what is used in most of menu driven programs. A loop that continues forever prints menu items on screen and waits for answer. Every time an answer is entered, proper action is done and again menu appears to accept another choice.

Loop continues forever unless you enter 4 as the answer for menu question. When this takes place the 'exit (0)' function terminates the program.

A more complex form of "if" statement is used here.

if(choice==1)
command;
else if(choice==2)
command;
else if(choice==3)
command;
else if(choice==4)
{
block of commands;
}
else
command;


This kind of "if" command is used in cases that you need multiple actions in case of different values or states. At the end of if statement there is an else section again. So you can do whatever you want when answer does not matches any of your conditions.

-----------------------------------------------------------------------------

4-5 End

With this lesson you will be able to write many useful programs.

As there are many commands and programming techniques you will not be able to remember all of them. So you must start programming. Start with lesson exercises and continue with more programs otherwise all your efforts will be useless in a while.

I always tell this sentence in my programming classes

" No one becomes a programmer without programming "


-----------------------------------------------------------------------------

Exercises:



--------------------------------------------------------------------------------

1- Write a program that accepts 10 scores between 0 and 20 for each student. (use "for" loop) Then calculate average for the student. We want to determine an alphabetical score for each student according below table.

A 16-20
B 12-16
C 10-12
D 7-10
E 4-7
F 0-4

Print both average score in numerical and alphabetical form.


2- Rewrite example 4-5 to do the following tasks:

1- Add two numbers
2- Subtract two numbers
3- Multiply two numbers
4- Exit

Write necessary program inside a block to accept two numbers and perform necessary action for each menu choice. Program execution must continue until user enters 4 as menu choice.


============================================================

BreBru.Com Extra Information Technology HTML