I am facing difficulaties in writing nested loops

Hi There,

I am new to coding when ever if a problem involves in nested loops.
i am ending up in infiniate loops this is not because of inc/dec of the variables. this is because of not resetting some variable at outerloop thus by resulting in running the code in infinate loops

What is the best way to be comfortable with nested loops. Need some tips in this regard.

Thanks and Regards,
Ramesh Varma.

The best way is just to use them.

And depending on your language, there may be options other than a for loop with exposed iteration variables - like JS we have for...in, for...of, and a bunch of array prototype methods that often preferable. I work in JS and I almost never write a for loop (or while or do while). I almost always use a prototype method.

If you can share code, we can also point out issues.

1 Like

@kevinSmith Thank you so much i am currently learning c.
i just figured that i am not resetting the values at outer loop level thus i am getting wrong input i just corrected it through debugging
As you said i will try to code daily till i comfortable in nested loops

in this below program i forgot to reset the values(in bold)

/C Prog for Armstrong numbers without using any inbuilt mathematical function such as pow()/

#include <stdio.h>

int main()
{
    int lower_interval,upper_interval,temp,count=0,cnt,mul=1,result=0,rem,i=0;
    printf("enter lower interval:\n");
    scanf("%d",&lower_interval);
    printf("enter upper interval:\n");
    scanf("%d",&upper_interval);
    for(i=lower_interval;i<=upper_interval;i++)
    {
        temp=i;
        //count no of digits
        while(temp!=0)
        {
            temp=temp/10;
            count++;
        }
        temp=i;
        cnt=count;
     //calculate the nth power of its digits and sum it up
        while(temp!=0)
        {
            rem=temp%10;
            while(cnt!=0)
            {
                mul=mul*rem;
                cnt--;
            }
            result=result+mul;
            mul=1;
            cnt=count;
            temp=temp/10;
        }
        if(result==i)
            printf("%d ",i);
        **//reset the values**
        count=0;
        result=0;
    }
}

Now i got it
Thanks
Ramesh Varma.

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

1 Like

Having looked at the code (and remembering that I haven’t done C in decades), I’m still not sure what this is trying to do. If you are not sure what is happening, put in some log statements. I would also suggest breaking things into some well named functions.