Algorithm & programming part III

Alhamdulillah, in this part , I feel so glad because I’ve already build the appearance for my old weblog. In this part we’re gonna discuss about looping. Looping is a repeated statements based on centain condition which is determined by the programmer.Pascal and C have same models of looping. Below is models of looping in Pascal and C

Model Pascal C
1. For For [condition] to [condition] do…[action]…. For (condition;conditon;terms){…….[action]………..

}

2. While While [condition] dobegin

…..[action]…………..

end;

While (conditon){……[action]…………….

}

3. Do …while repeat….until Repeat[action]

until

[condition]

Do{

[action]

}

while (condition)

Looping used to make programmer think harder, because in creating a program, looping must be tried repeatedly, in order to get match value. Moreover nested loop. Nested loop means looping inside looping.Looping is separated into descending and ascending loop.

Example (program to count average value):

PASCAL

 

program average;
uses crt;
var
a,b,c,d:integer;
e:real;
begin
d:=0;
write('input sum of number :');read(a);
 for b:=1 to a do
 begin
 write('index[',b,']=');read(c);
 d:=d+c;
 end;
e:=d/a;
writeln('average = ',e:2:2);
end.

C

 

#include <stdio.h>

int main(){
int a,b,c,d;
float e;
d=0;
printf("input sum of a number = ");scanf("%d",&a);
 for (b=1;b<=a;b++){
 printf("index[%d]=",b);scanf("%d",&c);
 d+=c;
 }
e=d/a;
printf("average=%2.2f\n",e);
}

PASCAL

program average_by_while;
uses crt;
var
a,b,c,d:integer;
e:real;
begin
d:=0;
write('input sum of number :');read(a);
b:=1;
 while b<=a do
 begin
 write('index[',b,']=');read(c);
 d:=d+c;
 b:=b+1;
 end;

 e:=d/a;
 writeln('average = ',e:2:2);

end.

C

#include <stdio.h>

int main(){
int a,b,c,d;
float e;
d=0;
printf("input sum of a number = ");scanf("%d",&a);
b=1;
 while (b<=a){
 printf("index[%d]=",b);scanf("%d",&c);
 d+=c;
 b+=1;
 }

e=d/a;
printf("average=%2.2f\n",e);
}

PASCAL

program average_by_repeat;
uses crt;
var
a,b,c,d:integer;
e:real;
begin
d:=0;
write('input sum of number :');read(a);
b:=0;
 repeat
 begin
 write('index[',b,']=');read(c);
 d:=d+c;
 b:=b+1;
 end;
 until b=a;

e:=d/a;
writeln('average=',e:2:2);

end.

C

#include <stdio.h>

int main(){
int a,b,c,d;
float e;
d=0;
printf("input sum of a number = ");scanf("%d",&a);
b=1;
 do{
 printf("index[%d]=",b);scanf("%d",&c);
 d+=c;
 b+=1;
 }
 while(b<=a);

e=d/a;
printf("average=%2.2f\n",e);
}

Okay, that’s all example for models of looping in PASCAL and C . So, have fun with your algorithm…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: