Main | Search | Courses | Login

C
Lesson Title : Operators, Loops, Type Conversion   Author : Siamak Sarmady   Creation : 2010-02-19   Update : 2010-02-19   Lessen Score Weight : 15%

## Operators, Loops, Type Conversion

In previous lesson you learned about arrays, strings and preprocessors. In this lesson we will learn about using mathematical and logical operators.  Mathematical operators are equivalent to the operators being used in mathematics (+-*/…). There are differences which we will mention in this lesson however. Loops are also important part of programming languages. In this lesson we will also learn how to convert variables from a specific type into variables with other types.

## Operators

There are many kinds of operators in each programming language. We mention some of the operators being used in C language here:

()  Parentheses
-  Subtract
*  Multiply
/  Divide

There are also some other operators which work differently:

%  Modulus
++  Increase by one
--  Decrease by one
=  Assignment

sizeof( )  return value is the size of a variable or type inside parentheses in bytes. It is actually the size that variable takes in system memory.

Examples:

c=4%3;    c will be equal to 1 after execution of this command.
i=3;
i=i*3;    i will be equal to 9
f=5/2;    if f is integer then it will be equal to 2. If it
is a float type variable its value will be 2.5
j++;      Increases the value of j by one.
j--;          Decreases value of j by one
sizeof(int)   returned value is 2 in dos and 4 in windows
int a=10;
c=sizeof(a);  c will be 2 in dos and 4 in windows as the size of integer
is different in different Os.

## Loops

Sometimes we want some part of our code to be executed more than once. We can either repeat the code in our program or use loops instead. It is obvious that if for example we need to execute some part of code for a hundred times it is not practical to repeat the code. Alternatively we can use our repeating code inside a loop.

while(not a hundred times)
{
code
}

There are a few kinds of loop commands in C programming language. We will see these commands in next sections.

## While loop

while loop is constructed of a condition and a single command or a block of commands that must run in a  loop. As we have told earlier a block of commands is a series of commands enclosed in two opening and closing braces.

while( condition )
command;
while( condition )
{
block of commands
}

Loop condition is a boolean expression. A boolean expression is a logical statement which is either correct or incorrect. It has a value of 1 if the logical statement is valid and its value is 0 if it is not. For example the Boolean statement (3>4) is invalid and therefore has a value of 0. While the statement (10==10) is a valid logical statement and therefore its value is 1.

Example 3-1: example3-1.c

#include<stdio.h>
main()
{
int i=0;
while( i<100 )
{
printf("\ni=%d",i);
i=i+1;
}
system("pause");
}

In above example i=i+1 means: add 1 to i and then assign it to i or simply increase its value. As we saw earlier, there is a special operator in C programming language that does the same thing. We can use the expression i++ instead of i=i+1.

We will learn more about logical operators in next lessons.

## Type Conversion

From time to time you will need to convert type of a value or variable to assign it to a variable from another type. This type of conversions may be useful in different situations, for example when you want to convert type of a variable to become compatible with a function with different type of arguments.

Some rules are implemented in C programming language for this purpose.

·         Automatic type conversion takes place in some cases. Char is automatically converted to int. Unsigned int will be automatically converted to int.

·         If there are two different types in an expression then both will convert to better type.

·         In an assignment statement, final result of calculation will be converted to the type of the variable which will hold the result of the calculation (ex. the variable “count” in the assignment count=i+1; )

For example if you add two values from int and float type and assign it to a double type variable, result will be double.

## Using loops in an example

Write a program to accept scores of a person and calculate sum of them and their average and print them.

Example 3-2 : example3-2.c

#include<stdio.h>
main()
{
int count=0;
float num=0,sum=0,avg=0;

printf("Enter score (-1 to stop): ");
scanf("%f",&num);

while(num>=0)
{
sum=sum+num;
count++;
printf("Enter score (-1 to stop): ");
scanf("%f",&num);
}

avg=sum/count;
printf("\nAverage=%f",avg);
printf("\nSum=%f\n",sum);

system("pause");
}

In this example we get first number and then enter the loop. We will stay inside loop until user enters a value smaller than 0. If user enters a value lower than 0 we will interpret it as STOP receiving scores.

Here are the output results of a sample run:

Enter score (-1 to stop): 12
Enter score (-1 to stop): 14
Enter score (-1 to stop): -1
Average=13.000000
Sum=26.000000

When user enters -1 as the value of num, logical expression inside loop condition becomes false (invalid) as num>=0 is not a valid statement.

Just remember that “while loop” will continue running until the logical condition inside its parentheses becomes false (and in that case it terminates).

## For loop

As we told earlier, there are many kinds of loops in C programming language. We will learn about for loop in this section.

“For loop” is something similar to while loop but it is more complex. “For loop” is constructed from a control statement that determines how many times the loop will run and a command section. Command section is either a single command or a block of commands.

for( control statement )
command;
for( control statement )
{
block of commands
}

Control statement itself has three parts:

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

Initialization part is performed only once at “for loop” start. We can initialize a loop variable here. Test condition is the most important part of the loop. Loop will continue to run if this condition is valid (True). If the condition becomes invalid (false) then the loop will terminate.

‘Run every time command’ section will be performed in every loop cycle. We use this part to reach the final condition for terminating the loop. For example we can increase or decrease loop variable’s value in a way that after specified number of cycles the loop condition becomes invalid and “for loop” can terminate.

At this step we rewrite example 3-1 with for loop. Just pay attention that we no more need I=I+1 for increasing loop variable. It is now included inside “for loop” condition phrase (i++).

Example 3-3: example3-3.c

#include<stdio.h>
main()
{
int i=0;
for(i=0;i<100;i++ )
printf("\ni=%d",i);

system("pause");
}

Example 3-4: example3-4.c

Write a program that gets temperatures of week days and calculate average temperature for that week.

#include<stdio.h>
main()
{
int count=0;
float num=0,sum=0,avg=0;

for(count=0;count<7;count ++)
{
printf("Enter temperature : ");
scanf("%f",&num);
sum=sum+num;
}
avg=sum/7;
printf("\nAverage=%f\n",avg);

system("pause");
}

In next lesson we will learn more examples about using loops and also other control structures.

## Exercises

1. Using while loop; write a program that prints alphabets ‘a’ through ‘z’ in separate lines. Use %c in your format string. You can increment a character type variable with ++ operand.

2. Write a program that accepts time in “seconds” format and prints it in minutes and seconds. For example if you enter 89 it must print : 1:29 (you can use % modulus operator to compute the remaining of a division)

3. Using for loop, write a program that accepts net sales of a shop for each day. Then calculate sales for a month then deduct %5 tax and finally calculate “Average daily sales” after tax deduction. Print results on the screen.

Help | Terms | Privacy Statement | About | Report Software Bugs | Society50 Asian Social Network | CupidB Free Matchmaker