Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C 

print numbers with loop side by side

I have too create an output similar to this for input 5.

15
24
33
42
51

I have the code below but its just printing me this:
5
1
2
3
4
5

I don't understand why. Why is that?



Code
#include <stdio.h>
#include <stdlib.h>

int main()

{

    int x, y, z;
    printf("Introduce a number: \n");
    scanf("%d", &z);
    for (x=1;x<=z;x++)
        {
            printf("%d\n", x);
            for (int y=z;y<=0;y--)
        {
                printf("   %d\n", y);
                
                
        }
        }
A much easier solution:
PHP Code

<?php 
#include <stdio.h>

int main()
{
    
int x, y;

    
printf("Introduce a number: \n");
    
scanf(" %d", &x);

    
y = 1;
    while(
x)
    {
      
printf("%d%d\n", y++, x--);
    }

    return 
0;
} 
(Mar 30, 2015 05:48 AM)TheComet Wrote:  A much easier solution:
PHP Code

<?php 
#include <stdio.h>

int main()
{
    
int x, y;

    
printf("Introduce a number: \n");
    
scanf(" %d", &x);

    
y = 1;
    while(
x)
    {
      
printf("%d%d\n", y++, x--);
    }

    return 
0;
} 

That's a nice solution. I have to really think all my options next time but i've been reading nested for loops and decided to aplly that, clearly i have trouble with them.
Could you change the code to make it work? I can't see what's wrng.
Quote:i've been reading nested for loops and decided to aplly that

It's not a nested loop problem. You cannot solve this using nested loops, because the output of nested loops would be n^2, but you only have n outputs.
You could do a two variable for loop if its easier for you to visualize...

Code
#include <iostream>
using namespace std;

int main() {
    int x;
    cout << "Input a number" << endl;
    cin >> x;
    for (int i = 1, j = x; i <= x; ++i, --j) {
      cout << i << j << endl;
    }
}
I don't know why you guys are making this so difficult... Anyone notice that the values are increments of 9? lol! 🤝

Here, a good mathematical way to solve this:
Code
int input = 9;
for (int i = 0, x = input + 10; i < input; ++i, x += 9)
{
  printf("%d\n", x);
}

Works for 1 >= input <= 9.. I wouldn't know what kind of output you'd expect if input was 0... Perhaps just "0"? or "00"? (Your example starts at 1 however)... Or if input was greater than 9.
Getting Started: C/C++
[C/C++/.NET/x86 ASM - Automation Programmer]


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C] by ShallowMEFeb 17, 2020 07:08 PM 20 509 Feb 17, 2020 07:08 PM
Last Post: 0xDEAD10CC
[Java] by cryptobassboostMay 20, 2019 11:49 AM 4 248 May 20, 2019 11:49 AM
Last Post: bluriy
[Python] by F.A.S.TApr 15, 2019 01:25 PM 0 76 Apr 15, 2019 01:25 PM
Last Post: F.A.S.T