Back Next

Programming in C

Lesson 3


Course support : You can ask your course questions in Learnem support forums .

Please support us by visiting our support forums and asking your questions and answering questions of others.

3-1 Operators 

There are many kinds of operators in each programming language. We mention some of these operators here: 

() Parentheses
+ Add
- 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.

 


3-2 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. It is obvious that if for example we need to execute some part of code for a hundred times it is not acceptable to repeat the code.

Alternatively we can use our code inside a loop.

while(not a hundred times)
{
code
}

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


3-3 while loop

while loop is constructed of a condition and a command or a block of commands that must run in a loop. As we have told later 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 has a value of 0 or 1 at any given time.

Example 3-1:

#include<stdio.h>
main()
{
int i=0;

while( i<100 )
 {
 printf("\ni=%d",i);
 i=i+1;
 }
}

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 later, 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.



3-3 Type Conversion

From time to time you will need to convert type of a value or variable to assign it to a variable form other type. This type of conversions may be useful in other situations for example you can 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.

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

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

3- In an assignment statement, final result of calculation will be converted to the type of variable that result is 
being assigned to it. 

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


3-4 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 :

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

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

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


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 : 12
Enter score : 14
Enter score : -1

Average=13.000000
Sum=26.000000

When user enters -1 as the value of num, logical expression inside loop condition becomes false as num>=0 is not acceptable. 

Just remember that,  while loop will continue until the logical condition inside its parentheses is true.


3-4 for loop

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

For loop is something like 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 True. If condition becomes false 
then loop will terminate.


‘Run every time command’ section will be performed every loop cycle. We use this part to reach the final condition for terminating the loop. For example we can increase or decrease loop value so that we no more have the condition to continue performing loop and therefore terminate the loop.

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 inserted inside for condition phrase.


Example 3-3:

#include<stdio.h>
main()
{
int i=0;

for(i=0;i<100;i++ )
printf("\ni=%d",i);

}



Example 3-4: 

Write a program that gets temperatures of a week 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 score : ");
  scanf("%f",&num);
  sum=sum+num;
}

avg=sum/7;
printf("\nAverage=%f",avg);
printf("\nSum=%f",sum);
}


3-5 End

We learned most important types of loop commands in this lesson. In next lesson we will have more useful examples on loops. 


Exercises:

Course support: 
Paid students must send exercises to their tutor. Tutor will return corrected exercise to the student. Others can ask their  questions in Support forums in our web site.

http://www.learnem.com/forums


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

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 taxes and finally calculate Average of sales after tax deduction for a day. Print results on the screen.

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

© 2000,2001 Siamak Sarmady and Learnem Group . All rights reserved. This text is licensed to be used on ProgrammingUni website. Any kind of reproduction, redistribution in any form is strictly prohibited without written permission of the writer. 

Back Next