I have problem translating C code in fortran - c

for(i=1;i<=ntype;i++)
for(cnt=0,j=1;j<=nbeta[i];j++) {
cnt++;
pos[i][cnt]=j;
if (lll[i][j]==0) {
for(kk=1;kk<=kkbeta[i];kk++)
bfunc[i][cnt][kk]=bfunctmp[i][j][kk];
llltmp[i][cnt]=lll[i][j];
} // if
if (lll[i][j]>0) {
for(kk=1;kk<=kkbeta[i];kk++)
bfunc[i][cnt][kk]=0.5*(bfunctmp[i][j ][kk]+
bfunctmp[i][j+1][kk]);
llltmp[i][cnt]=lll[i][j];
j++;
} // if
} // j,i
!my translated fortran code is
do i =1,ntype
cnt =0
do j =1,nbeta(i)
cnt = cnt+1
pos(i,cnt) =j
if(lll(i,j) ==0) then
do kk =1, kkbeta(i)
bfunc(i,cnt,kk)= bfunctmp(i,j,kk)
end do !end kk
llltmp(i,cnt) =lll(i,j)
! write(*,*)i,j,lll(i,j)
! write(*,*)i,cnt,llltmp(i,cnt) ! '(5x,3I5)'
end if
! cnt1 =j
if(lll(i,j) > 0) then
do kk =1, kkbeta(i)
bfunc(i,cnt,kk)= 0.5 *(bfunctmp(i,j,kk) + bfunctmp(i,j+1,kk))
end do !end kk
llltmp(i,cnt) =lll(i,j)
j =j+1
end if
end do !end j
end do !end i
! A do-variable within a DO body shall not appear in a variable definition context. [j]
I am looking forward to solve this issue soon. Thank you!

As #TomKarzes remarked in comments, you may not assign to the control variable of a DO loop within the body of that loop. Sometimes you can resolve such issues by using a different variable, instead. In your code, however, the objective of the j=j+1 appears to be to skip a loop iteration, and you simply cannot do that in a DO loop.
You can, however, replace your DO loop with a DO WHILE loop:
j = 1
do while (j <= nbeta(i))
! ...
if (lll(i,j) > 0) then
! ...
j = j + 1
end if
j = j + 1
end do
That should work for your particular code, but you must take considerable care when making such a transformation. There are at least these considerations that must be accounted for:
In an iterated DO loop, the loop variable is automatically incremented after each execution of the loop body, even if execution of the body terminates early by execution of a CYCLE statement. In a DO WHILE loop, however, variables are modified only by statements that are executed, so a CYCLE will not, itself, cause any variable to be updated.
The number of iterations for an iterated DO loop to perform is computed before the first iteration is performed, based on data (such as the value of nbeta(i)) gathered when execution reaches the DO statement. That number of iterations can be changed only by prematurely discontinuing the loop via an EXIT, RETURN, GOTO, or STOP statement, or by executing a procedure that causes the program to terminate. On the other hand, the condition of a DO WHILE is evaluated before every iteration.

Related

Why does this for-loop and while-loop produce different outcomes, even though their values are the same? Btw I am using Javascript

My novice understanding of the difference between for-loops and while-loops is that they differ in format and we use for-loops when we know the exact number of iterations to complete and we use while-loops when we know what condition must be met to stop. That said could someone explain the difference in outcome of the following code?
let countDown = 2;
while(countDown>1){
countDown--;
console.log(countDown)
}
1
for(let countDown = 2; countDown>1; countDown--){
console.log(countDown)
}
2
As U. Windl had commented, for is just "syntactic sugar" for a while loop. The output of your program varied for for and while loop because in while loop countDown is decremented first and then logged, in for loop countDown is logged first and then decremented. With the below change in while loop the output would be same for both and its equivalent to for loop.
let countDown = 2;
while(countDown>1){
console.log(countDown)
countDown--;
}
Lets see what for and while loop says JavaScript For Loop
The For Loop
The for loop has the following syntax:
for (statement 1; statement 2 (condition); statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
While Loop
while (condition) {
// code block to be executed
}
In your program in for loop Statement 3 (i.e countDown--) is executed after the code block (i.e console.log) has been executed, that is the reason the output was 2.
In while loop we have to take care when to execute Statement 3 (i.e countDown-- in this case) and in for loop Statement 3 is always executed after executing code block
for equivalent for while
for (; condition; ) {
// code block to be executed
}
while equivalent for for
Statement 1
while (Statement 2) {
// code block to be executed
Statement 3
}

do-while loop into for loop

I made a game but didn't wanted to use do-while loops.
So instead I tried to use for loops. The problem is when I run with do-while
it works but when I run with for loops it doesn't work in the same way.
I think I changed do-while into for loops correctly. Can someone let me know what I am missing?
do {
crntShowBottle = rand() % 2 + 2;
} while (crntShowBottle == prevShowBottle);
prevShowBottle = crntShowBottle;
for (;;)
{
crntShowBottle = rand() % 2 + 2;
if (crntShowBottle == prevShowBottle)
break;
}
prevShowBottle = crntShowBottle;
First, try to understand the mechanism of loop and how they are different from do-while loop and for loop.
Based on your code, what is happening!
In the do-while section, you are giving instructions that "first do something" and then checking the condition. If the condition (checking) is true crntShowBottle == prevShowBottle then the loop must run again. Otherwise, if the condition is false crntShowBottle != prevShowBottle the loop must terminate.
In the for loop section, you used the infinite loop for(;;). Means loop will be running infinite times. But, inside the loop you wrote the break condition. So, when the condition is matching crntShowBottle == prevShowBottle your loop is shutting down. So, you must use crntShowBottle != prevShowBottle
You also need to understand, how break works!

For loop control with 1 variable start and another variable stop

int ix = 0;
int jx = 5;
for (ix = 0; ix <= jx; ix++)
{
// foo
}
In the above foo will execute 6 times if jx = 5
But what if jx = 0????
will foo execute just once? or not at all?
In a for loop, there are three sections
for (initialize;precondition;post increment)
It's important to realize that the first time you go through a loop, it initializes as well as checks the precondition before even executing the following block of code. Once it completes the block, the is executed.
Then it checks the precondition to check whether it should go in to the loop again.

What is wrong in this C code ? If its a logical error please suggest the right way

int i;
for(i=7;i<6;i--)//loop does not execute
{
printf("*");
}
The above code should print one * but it does nothing. Shouldn'tit run same as for(i=7;i<8;i++) ?
Is this a logical error ? Please help.
A for loop has 3 parts
for( init ; cond ; step )
When the execution reaches the loop,
init is executed.
cond is evaluated.
If false, break the loop
If true, proceed to the next step
Execute the body of the loop.
Do step(in many cases, this is increment/decrement)
Goto step 2
In your case , i is set to 7. Then the condition i<6 is checked. Obviously, 7<6 is false. So the loop never gets executed.
And No.
for(i=7;i<6;i--)
and
for(i=7;i<8;i++)
aren't the same.
Perhaps you wanted to write
for(i=7;i>6;i--) //'>' instead of '<'
in which the loop will execute once.
Let's look at the loop
for( i = 7 ; i < 6 ; i-- )
i is initialized 7, but you have the condition i < 6, but i is 7, and therefor, it does not satisfy the condition of the loop. So, the code does not even go through one iteration of the loop.
Maybe, you meant i > 6
In this loop
for(i=7;i<6;i--)
at first you set i to 7 and then check whether i is less than 6. As i is equal to 7 then it is not less than 6 and the loop iterate never.
If you want that the loop would iterate one time then you should write
for(i=7; i > 6;i--)
Though with these magic numbers the loop looks strange.:) It is not clear what is the intention of the programmer.
int i;
for(i=7;i<6;i--)//loop does not execute
{
printf("*");
}
In first execution of this loop value of "i" is 7
next we have to check the condition "i<6" it is false because 7<6 is false ,then it not give any output
for(i=7;i<8;i++) is different because first "i" value is 7
then it checks condition it is i<8 (7<8) it is true.then it executes once ,after that it increment from 1 (i++),then it checks condition .then it is false because "i" is 8
then it stops execution.

For vs. while in C programming?

There are three loops in C: for, while, and do-while. What's the difference between them?
For example, it seems nearly all while statements can be replaced by for statements, right? Then, what's the advantage using while?
A while loop will always evaluate the condition first.
while (condition) {
//gets executed after condition is checked
}
A do/while loop will always execute
the code in the do{} block first
and then evaluate the condition.
do {
//gets executed at least once
} while (condition);
A for loop allows you to initiate a counter variable, a check condition, and a way to increment your counter all in one line.
for (int x = 0; x < 100; x++) {
//executed until x >= 100
}
At the end of the day, they are all still loops, but they offer some flexibility as to how they are executed.
Here is a great explanation of the reasoning behind the use of each different type of loop that may help clear things up. Thanks clyfe
The main difference between the for's
and the while's is a matter of
pragmatics: we usually use for when
there is a known number of iterations,
and use while constructs when the
number of iterations in not known in
advance. The while vs do ... while
issue is also of pragmatics, the
second executes the instructions once
at start, and afterwards it behaves
just like the simple while.
For loops are especially nice because they are concise. In order for this for loop:
for (int x = 0; x < 100; x++) {
//executed until x >= 100
}
to be written as a while loop, you'd have to do the following:
int count = 0;
while (count < 100) {
//do stuff
count++;
}
In this case, there's just more stuff to keep up with and the count++; could get lost in the logic. This could end up being troublesome depending on where count gets incremented, and whether or not it should get incremented before or after the loop's logic. With a for loop, your counter variable is always incremented before the next iteration of the loop, which adds some uniformity to your code.
For the sake of completeness, it's probably meaningful to talk about break and continue statements here which come in handy when doing loop processing.
break will instantly terminate the current loop and no more iterations will be executed.
//will only run "do stuff" twice
for (int x = 0; x < 100; x++) {
if (x == 2) {
break;
}
//do stuff
}
continue will terminate the current iteration and move on to the next one.
//will run "do stuff" until x >= 100 except for when x = 2
for (int x = 0; x < 100; x++) {
if (x == 2) {
continue;
}
//do stuff
}
Note that in a for loop, continue evaluates the part3 expression of for (part1; part2; part3); in contrast, in a while loop, it just jumps to re-evaluate the loop condition.
If there is a strong concern about speed and performance, the best approach is to verify the code produced by the compiler at the assembly level.
For instance, the following code shows that the "do-while" is a bit faster. This because the "jmp" instruction is not used by the "do-while" loop.
BTW, in this specific example, the worst case is given by the "for" loop. :))
int main(int argc, char* argv[])
{
int i;
char x[100];
// "FOR" LOOP:
for (i=0; i<100; i++ )
{
x[i] = 0;
}
// "WHILE" LOOP:
i = 0;
while (i<100 )
{
x[i++] = 0;
}
// "DO-WHILE" LOOP:
i = 0;
do
{
x[i++] = 0;
}
while (i<100);
return 0;
}
// "FOR" LOOP:
010013C8 mov dword ptr [ebp-0Ch],0
010013CF jmp wmain+3Ah (10013DAh)
for (i=0; i<100; i++ )
{
x[i] = 0;
010013D1 mov eax,dword ptr [ebp-0Ch] <<< UPDATE i
010013D4 add eax,1
010013D7 mov dword ptr [ebp-0Ch],eax
010013DA cmp dword ptr [ebp-0Ch],64h <<< TEST
010013DE jge wmain+4Ah (10013EAh) <<< COND JUMP
010013E0 mov eax,dword ptr [ebp-0Ch] <<< DO THE JOB..
010013E3 mov byte ptr [ebp+eax-78h],0
010013E8 jmp wmain+31h (10013D1h) <<< UNCOND JUMP
}
// "WHILE" LOOP:
i = 0;
010013EA mov dword ptr [ebp-0Ch],0
while (i<100 )
{
x[i++] = 0;
010013F1 cmp dword ptr [ebp-0Ch],64h <<< TEST
010013F5 jge wmain+6Ah (100140Ah) <<< COND JUMP
010013F7 mov eax,dword ptr [ebp-0Ch] <<< DO THE JOB..
010013FA mov byte ptr [ebp+eax-78h],0
010013FF mov ecx,dword ptr [ebp-0Ch] <<< UPDATE i
01001402 add ecx,1
01001405 mov dword ptr [ebp-0Ch],ecx
01001408 jmp wmain+51h (10013F1h) <<< UNCOND JUMP
}
// "DO-WHILE" LOOP:
i = 0;
. 0100140A mov dword ptr [ebp-0Ch],0
do
{
x[i++] = 0;
01001411 mov eax,dword ptr [ebp-0Ch] <<< DO THE JOB..
01001414 mov byte ptr [ebp+eax-78h],0
01001419 mov ecx,dword ptr [ebp-0Ch] <<< UPDATE i
0100141C add ecx,1
0100141F mov dword ptr [ebp-0Ch],ecx
01001422 cmp dword ptr [ebp-0Ch],64h <<< TEST
01001426 jl wmain+71h (1001411h) <<< COND JUMP
}
while (i<100);
For the sake of readability
They're all interchangeable; you could pick one type and use nothing but that forever, but usually one is more convenient for a given task. It's like saying "why have switch, you can just use a bunch of if statements" -- true, but if it's a common pattern to check a variable for a set of values, it's convenient and much easier to read if there's a language feature to do that
If you want a loop to execute while a condition is true, and not for a certain number of iterations, it is much easier for someone else to understand:
while (cond_true)
than something like this:
for (; cond_true ; )
Remember, a for loop is essentially a fancy while loop. They're the same thing.
while <some condition is true> {
// do some stuff
// possibly do something to change the condition
}
for ( some var, <some condition is true>; increment var ) {
}
The advantage of a for loop is that it's harder to accidentally do an infinite loop. Or rather, it's more obvious when you do one because you generally put the loop var in the initial statement.
A while loop is more clear when you're not doing a standard incrementing pattern. For example:
int x = 1;
while( x != 10 ) {
if ( some condition )
x = 10;
else
x += 5;
}
You should use such a loop, that most fully conforms to your needs.
For example:
for(int i = 0; i < 10; i++)
{
print(i);
}
//or
int i = 0;
while(i < 10)
{
print(i);
i++;
}
Obviously, in such situation, "for" looks better, than "while".
And "do while" shoud be used when some operations must be done already before the moment when condition of your loop will be checked.
Sorry for my bad english).
One common misunderstanding withwhile/for loops I've seen is that their efficiency differs. While loops and for loops are equally efficient. I remember my computer teacher from highschool told me that for loops are more efficient for iteration when you have to increment a number. That is not the case.
For loops are simply syntactically sugared while loops, and make iteration code faster to write.
When the compiler takes your code and compiles it, it is translating it into a form that is easier for the computer to understand and execute on a lower level (assembly). During this translation, the subtle differences between the while and for syntaxes are lost, and they become exactly the same.
A for suggest a fixed iteration using an index or variants on this scheme.
A while and do... while are constructions you use when there is a condition that must be checked each time (apart from some index-alike construction, see above). They differ in when the first execution of the condition check is performed.
You can use either construct, but they have their advantages and disadvantages depending on your use case.
I noticed some time ago that a For loop typically generates several more machine instructions than a while loop. However, if you look closely at the examples, which mirror my observations, the difference is two or three machine instructions, hardly worth much consideration.
Note, too, that the initializer for a WHILE loop can be eliminated by baking it into the code, e. g.:
static int intStartWith = 100;
The static modifier bakes the initial value into the code, saving (drum roll) one MOV instruction. Of greater significance, marking a variable as static moves it outside the stack frame. Variable alignment permitting, it may also produce slightly smaller code, too, since the MOV instruction and its operands take more room than, for example an integer, Boolean, or character value (either ANSI or Unicode).
However, if variables are aligned on 8 byte boundaries, a common default setting, an int, bool, or TCHAR baked into code costs the same number of bytes as a MOV instruction.
They are all the same in the work they do. You can do the same things using any of them. But for readability, usability, convenience etc., they differ.
A difference between while and do-while is that while checks the loop condition and if this is true, the body is executed and the condition checked again. The do-while checks the condition after execution of the body, so with do-while the body is executed at least one time.
Of course you can write a while loop as a do-while and vv, but this usually requires some code duplication.
One peculiarity of the do while is that you need a semi-colon after the while to complete. It is often used in macro definitions to execute several statements only once while constraining the impact of the macro. If macros where defined as blocks, some parsing errors may occur.
One explanation among others
For loops (at least considering C99) are superior to while loops because they limit the scope of the incremented variable(s).
Do while loops are useful when the condition is dependant on some inputs. They are the most seldom used of the three loop types.
Between for and while: while does not need initialization nor update statement, so it may look better, more elegant; for can have statements missing, one two or all, so it is the most flexible and obvious if you need initialization, looping condition and "update" before looping. If you need only loop condition (tested at the beginning of the loop) then while is more elegant.
Between for/while and do-while: in do-while the condition is evaluated at the end of the loop. More confortable if the loop must be executed at least once.
WHILE is more flexible. FOR is more concise in those instances in which it applies.
FOR is great for loops which have a counter of some kind, like
for (int n=0; n<max; ++n)
You can accomplish the same thing with a WHILE, of course, as others have pointed out, but now the initialization, test, and increment are broken across three lines. Possibly three widely-separated lines if the body of the loop is large. This makes it harder for the reader to see what you're doing. After all, while "++n" is a very common third piece of the FOR, it's certainly not the only possibility. I've written many loops where I write "n+=increment" or some more complex expression.
FOR can also work nicely with things other than a counter, of course. Like
for (int n=getFirstElementFromList(); listHasMoreElements(); n=getNextElementFromList())
Etc.
But FOR breaks down when the "next time through the loop" logic gets more complicated. Consider:
initializeList();
while (listHasMoreElements())
{
n=getCurrentElement();
int status=processElement(n);
if (status>0)
{
skipElements(status);
advanceElementPointer();
}
else
{
n=-status;
findElement(n);
}
}
That is, if the process of advancing may be different depending on conditions encountered while processing, a FOR statement is impractical. Yes, sometimes you could make it work with a complicated enough expressions, use of the ternary ?: operator, etc, but that usually makes the code less readable rather than more readable.
In practice, most of my loops are either stepping through an array or structure of some kind, in which case I use a FOR loop; or are reading a file or a result set from a database, in which case I use a WHILE loop ("while (!eof())" or something of that sort).
They are pretty much same except for do-while loop. The for loop is good when you have a counter kind of variable. It makes it obvious. while loop makes sense in cases where a flag is being checked as show below :
while (!done) {
if (some condtion)
done = true;
}
while and for statements can both be used for looping in programming. It will depend on the programmer as to whether the while loop or for loop is used. Some are comfortable using while loop and some are with for loop.
Use any loop you like. However, the do...while loop can be somewhat tricky in C programming.
/*
while loop
5 bucks
1 chocolate = 1 bucks
while my money is greater than 1 bucks
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1
end
come to home and cant go to while shop because my money = 0 bucks
*/
#include<stdio.h>
int main(){
int money = 5;
while( money >= 1){
printf("inside the shopk and selecting chocolate\n");
printf("after selecting chocolate paying 1 bucks\n");
money = money - 1 ;
printf("my remaining moeny = %d\n", money);
printf("\n\n");
}
printf("dont have money cant go inside the shop, money = %d", money);
return 0;
}
infinite money
while( codition ){ // condition will always true ....infinite loop
statement(s)
}
please visit this video for better understanding
https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s
/*
for loop
5 bucks
for my money is greater than equal to 1 bucks 0 money >= 1
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1 1-1 => 0
end
*/
#include<stdio.h>
int main(){
int money = 5;
for( ; money >= 1; ){ 0>=1 false
printf("select chocolate \n");
printf("paying 1 bucks to the shopkeeper\n");
money = money - 1; 1-1 = 0
printf(" remaining money =%d\n", money);
printf("\n\n");
}
return 0;
}
For better understanding please visit https://www.youtube.com/watch?v=_vdvyzzp-R4&t=25s

Resources