2018-07-25 14:46:45

So, this will be my first time asking for help with something on this site.

Currently, I am learning c, and I have progressed up to the nested loops.

I think you guys will understand my problem if I present the program, and explain what I want to do.

#include <stdio.h>
void main()
{
int i, n1, n2;
printf("Enter the value of n1 and n2:");
scanf("%d%d",&n1,&n2);
while(n1<=n2)
{
i=1;
while(i<=10)
{
printf("%2d*%2d=%2d\n",n1,i,i*n1);
i++;
}
n1++;
}
}

Currently, the program above gives the output like this:

If I entered the values like five and seven:

5*1=5
5*2=10

It would go up to 50.

Same thing for the six and seven.

But I want the output in this manner:

Once more, I enter the values five and seven:

Then I want the output in this way:

5*1=5
6*1=6
7*1=7

Until the table of all three number is over. (reaching the 50, 60, and 70.) So how can I accomplish this?

2018-07-25 15:58:57

You need to switch the loops and use a temp variable to save the contents of n1.

int i = 1, n1, n2, temp;

while (i <= 10)
{
    temp = n1;

    while (temp <= n2)
    {
        printf("%2d*%2d=%2d\n",temp,i,i*temp);
        temp++;
    }
    i++;
}
I don’t believe in fighting unnecessarily.  But if something is worth fighting for, then its always a fight worth winning.
check me out on Twitter and on GitHub

2018-07-25 18:29:46

Thank you very much, Kyle.

2018-08-06 20:05:57

so with the program below, I want to print the list of prime numbers in a given range. (like 1 to 10, 20 to 50, etc.) but apparently, I am missing something.

#include <stdio.h>
void main()
{
int i=2, n1, n2, f=0, n;
printf("Enter the value of n1 and n2:");
scanf("%d%d",&n1,&n2);
while(n1<=n2)
{
n=n1;
while(i<n)
{
if(n%i==0)
{
f=1;
}
i++;
}
if(f==0)
printf("%d\n",n);
n1++;
}
}

Also, I hope you guys won’t mind if I post some more problems like these, since I am learning c, and I have no other way for asking help or advice other than from my teacher, and he is not available all the time.

Besides, most of the time, I do solve my problems, but if a particular problem is not getting solved by me, then I hope I can post it here.

2018-08-07 10:47:27

I am confused.

last time I checked this topic, there was an answer to my question, but before I could test it, it is gone.

ah well, nothing to do then wait for another one I guess...

2018-08-07 11:30:24

I had misinterpreted your question, the example did not actually calculate prime numbers. This one should work:

#include <stdio.h>
void main()
{
    int i=2, n1, n2, f=0;
    printf("Enter the value of n1 and n2:\n");
    scanf("%d%d",&n1,&n2);
    while(n1<=n2)
    {
        i=2;
        f=0;
        if(n1>1)
        {
            while(i<n1)
            {
                if(n1%i==0)
                {
                    f=1;
                    break;
                }
                i++;
            }
            if(f==0)
            {
            printf("%d\n",n1);
            }
        }
        n1++;
    }
}
-BrushTone v1.3.3: Accessible Paint Tool
-AudiMesh3D v1.0.0: Accessible 3D Model Viewer

2018-10-29 12:17:07 (edited by Dark Eagle 2018-10-29 12:20:00)

So, I have these four outputs which I need to have:

Pattern 6:
1 2 3 4 5
1 2 3 4 -
1 2 3 - -
1 2 - - -
1 - - - -

Pattern 7:
1 ----
1 2 ---
1 2 3 --
1 2 3 4 -
1 2 3 4 5

Pattern 8:
1 2 3 4 5
- 1 2 3 4
- - 1 2 3
- - - 1 2
- - - - 1

Pattern 9:
1 2 3 4 5 5 4 3 2 1
1 2 3 4 - - 4 3 2 1
1 2 3 - - - - 3 2 1
1 2 - - - - - - 2 1
1 - - - - - - - - 1

I did solved the first one like this, (Pattern 6):

for(i=1;i<=5;i++)
{
    for(j=1;j<=n-i+1;j++)
{
printf("%d",j);
}
for(j=1;j<i;j++)
{
printf("-");
}
printf("\n");
}

But how can I solve the remaining three?

Note: the outer loop, while it is stated i<=5, but in actuality, it is supposed to be i<=n. sorry if you get confused by that.

2018-10-30 00:57:45

You can rewrite pattern 6 like this:
for(int i=n; i >= 0; i--) {
for(int j = 1; j <= n; j++) {
if(j > i) printf("%d ", j);
else printf("-");
}
printf("\n");
}
Try figuring out the other patterns now.

Roel
golfing in the kitchen

2018-10-30 03:10:33

If memory serves, you can also do this too...
for(int i=n, j=1; i >= 0, j<=n; i--, j++) {
if(j > i) {
printf("%d ", j);
} else {
printf("-");
}
}
printf("\n");

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2018-10-30 06:06:01

The problem is, I need the dashes printed as well, that is why another entirely different loop.

otherwise I would have used if else from the beginning.

2018-11-02 16:13:15

So I managed to solve the pattern 6, 7, and 8, but pattern 9 is still giving me trouble. some help would be nice about now.

2018-11-07 11:55:08

This should work:

#include <stdio.h>

void main()
{
    for(int i=1;i<=5;i++)
    {
    //count forward
        for(int j=1;j<=5-i+1;j++)
        {
            printf("%d",j);
        }
        for(int j=1;j<i;j++)
        {
            printf("-");
        }
    //count backward
        for(int j=1;j<i;j++)
        {
            printf("-");
        }
        for(int j=5;j>=1+(i-1);j--)
        {
            printf("%d",j-(i-1));
        }

        printf("\n");


    }
}
-BrushTone v1.3.3: Accessible Paint Tool
-AudiMesh3D v1.0.0: Accessible 3D Model Viewer

2018-11-07 19:32:55

Thanks, Magurp.

2018-11-15 17:53:51 (edited by Dark Eagle 2018-11-15 17:55:30)

Now, I hate to do this, because I know people get annoied that I always keep these nubi problems here, but honestly, I don't have any place or a person to ask these questions.

this time, I only have to print the number output, but the problem is, I have to print them in a increasing and decreasing manner in the same program.

Also, I have to print them by using only nested forloops, if that helps to you guys.

you will read what I am trying to say below:

1 1
1 2 2 1
1 2 3 3 2 1
1 2 3 4 4 3 2 1
1 2 3 4 5 5 4 3 2 1

second program:

1 1
1 2 2 1
1 2 3 3 2 1
1 2 3 4 4 3 2 1
1 2 3 4 5 5 4 3 2 1
1 2 3 4 4 3 2 1
1 2 3 3 2 1
1 2 2 1
1 1

As I said early in the post, sorry if you guys get annoied at this.

2018-11-16 00:19:44

Meh, its no problem really. Its been awhile since i've worked in C, so getting a bit of practice in as time allows is fine. Hm, it looks like the first program is very similar to pattern 9 in one of your previous posts, and the second one is an extension of that. Try removing the dash loops and adjusting the parameters of the first outer for loop for the first answer. For the second, try copying the loops of the first program and paste a copy of them below it, and rewrite the outer for loop to function like pattern 9.

-BrushTone v1.3.3: Accessible Paint Tool
-AudiMesh3D v1.0.0: Accessible 3D Model Viewer

2018-11-16 13:28:56

@Magurp:

Could you give me  example of loop? I only need loop, nnot entire program.

2018-11-17 01:50:28 (edited by magurp244 2018-11-17 01:54:34)

Sure, its just a slight modification of pattern 9:

void main()
{
    for(int i=5;i>=1;i--)
    {

//your code here

    }
}

That would throw everything in reverse, then you just get rid of the loops that add dashes.

-BrushTone v1.3.3: Accessible Paint Tool
-AudiMesh3D v1.0.0: Accessible 3D Model Viewer

2018-11-18 00:01:52

Thanks for that, I did a dry run and after that, a compiled run of the program, and both times I got the output I want for the first program.

My biggest problem from the start is the second pattern. because not only it starts from,

1 1

It peaks at,

1 2 3 4 5 5 4 3 2 1

And ends at,

1 1

Basically, it counts upwards and downwards in a same program. now, I know that I can put more than one incriment or decrement in one loop, but I don't think it would be useful in this particular case. so, once again, I am lossed to what exactly should I do.

Note: if you are confused what I am trying to say, take another look of the second program which I have already posted the output.

2018-11-18 03:11:10 (edited by magurp244 2018-11-18 03:11:40)

For the second output question, you'll need to combine the original version of pattern 9, and the new version of pattern 9 with all the dashes stripped out, so it will count up on each row, and then down again. Using just the outer loops again as an example:

void main()
{
//print top half
    for(int i=5;i>=1;i--)
    {

//your code here

    }

//print bottom half
    for(int i=2;i<=5;i++)
    {

//your code here

    }
}
-BrushTone v1.3.3: Accessible Paint Tool
-AudiMesh3D v1.0.0: Accessible 3D Model Viewer

2018-11-27 08:22:32

So by your help, I managed to complete the program, and learned a lesson how you should always close the loops when you are working with more than one outer loop, and what I got in return?

Recursion.

And my teacher said that it is the hardest program in c. and I am kind of starting to believe that.

2018-11-27 09:20:02

I wouldn't worry too much about it, Recursion is just a different kind of loop like While and For loops, only with functions.

-BrushTone v1.3.3: Accessible Paint Tool
-AudiMesh3D v1.0.0: Accessible 3D Model Viewer

2018-11-27 16:29:48 (edited by Ethin 2018-11-27 16:31:57)

Recursion is far more difficult to master than a loop is. To those experienced in it it can be extremely easy, but to newcomers its very difficult. The thing recursion and loops have in common is that they either have an end condition or they don't. Take the Fibonacci sequence, for example: in mathematics it is defined as f(n)=f(n-1)+f(n-2) if n>1 with the seed values f1=1, f2=1 or f(0)=0, f(1)=1.
As you can no doubt see, this function is recursive by definition alone. So long as n is greater than zero, it recursively solves itself, until n is equal to one, whereupon it terminates. This is a critical key ingredient to recursion in mathematics, and in programming: if you do not set a terminating condition, the function or equation becomes unsolvable, and "runs" forever. Sometimes this is the desired behavior, such as in an application that (perhaps every hour) checks for game updates: you can set a timer and when the event on the timer fires, the function calls itself and resets the timer. Most of the time though, you need some kind of ending condition. Either (as in the Fibonacci sequence) you keep calling until n is not greater than one, or you determine some other condition that results in a termination. It is very easy to forget the condition and cause a recursive function to run indefinitely until forcefully killed by either the user or the operating system. (The latter indicates you really messed up.) So, when writing recursive functions, always remember the following:
* Always provide a terminator somewhere: either it times out, or the thread is killed, etc. Never run recursive functions on the main thread of your application unless that is the only thing you want your application to do -- always run it either in another thread, task or coroutine.
* Never call the recursive function in the terminator condition; terminate the recursion. Calling the recursive function in the terminating condition makes the condition useless.
* And, last but not least, be careful with the recursive functions you write -- it is incredibly easy for a recursive function to go rogue! Remember the other two rules and you should swiftly be free and happy with recursion.
You may find that recursion is definitely less resource intensive than a while loop. Hell, it might even be faster! That all depends on the programming language though: in languages like C it can have overhead caused by the need to allocate a new stack frame per function call, but some C compilers (including GCC) have compilation options that can eliminate this overhead. The performance gained by recursion versus standard looping/iteration most likely won't be noticeable unless you profile your code though.

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2018-11-28 09:27:35

thanks for the detailed explanation Ethin.

the thing is, I have to run the program without compiling, and then tell the output to my teacher.

not that I have much trouble with it, after several tries, I finally got it right.

2018-11-28 17:50:57

@23, you can't run a C program without compiling it first (so far as I know) unless you've got a C interpreter of some kind.

"On two occasions I have been asked [by members of Parliament!]: 'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out ?' I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question."    — Charles Babbage.
My Github

2019-05-30 11:20:24

@Ethin:

Sorry for replying so late. I usually just do not come at this topic to check for the replies until I have posted a problem, because it is not a discussion topic.

Anyway, what I was refering to was the way in which once you read the program, you have to predict it's output. of course no human can answer with the speed of a compiler, but still it can be done.

But this is only for the purpose of practice, it would be madness to look a real C application code and trying to predict its output, while the code itself is hundreds or thousands of lines larger.

I asked my teacher about this oneday, and he told me that it is done so the students can understand what steps does the computer takes to compile the program and show the results on screen.

As for why I am replying now? you would guess correctly if you thought that I have a new problem. but I will post the problem in the new post.