Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How can I get my result to be the same as the number I entered? (in while loop)

+4 votes
asked Nov 21, 2021 by Lexus Guevara (1,010 points)
#include <stdio.h>

int main()
{
    int n, x, i, y; // [((n * (n - 1)) + 1) ] +2 repeatedly until the value of n
    
    printf("Input integer value : ");
    scanf("%d", &n);
    
    i = n * n * n;
    x = (n * (n - 1)) + 1; //formula to get the first addend
    y = 2; //since the first addend is an odd number, then by adding 2 to the first addend will result into another  odd addned
   
    if (n >= 1 && n <= 30){ //when the input is in range //2
        do {
            (x <= i);//as it will repeatedly executed until the value is less than or equal to i
            printf("%d\n", x);
            x += y; //the first addend will repeatedly add 2 to itself
        }
        while (x <= n);//I thought that this loop will help us to print the same count of the inputted number
            printf("%d\n", x);
        
        
    }
        
    else { //when the input is out of range
        printf("The integer input is out of range!");
    }
    

    return 0;
}

2 Answers

0 votes
answered Nov 22, 2021 by Peter Minarik (84,720 points)
edited Nov 22, 2021 by Peter Minarik
 
Best answer

You Have To Be More Specific

It's hard to tell you what's wrong when one's not even sure what your code's supposed to do in the first place.

You should explain the following when you're posting:

  • What is your program supposed to do?
  • What do you think is not working right?

Let's See Some Issues

Without knowing what exactly you're trying to do here, let me run some analysis on your code.

16 (x <= i);//as it will repeatedly executed until the value is less than or equal to i

this line does nothing. This is an empty instruction. You ask the compiler to compare if x is less or equal to i, but then that's it, you don't do anything with the result, just throw it away.

Consequently, i is an unused variable and for this, the following lines could be removed:

 5 int i;
10 i = n * n * n;

The value of i is never read, so there's no point in writing the value of i and no point in creating this variable.

21 printf("%d\n", x);

has a wrong indentation. It should have the same indentation as the line above. This is not a problem to the compiler, but to the reader, making humans confused.

10 x = (n * (n - 1)) + 1; //formula to get the first addend
12 y = 2; //since the first addend is an odd number, then by adding 2 to the first addend will result into another  odd addned
18 x += y; //the first addend will repeatedly add 2 to itself
20 while (x <= n);//I thought that this loop will help us to print the same count of the inputted number

It's easy to see that x is always greater than any non-negative n, so the while statement in line 20 will be always false (except for when an overflow happens). So you probably wanted to do something differently.

UPDATE

Problem specified

Thank you for specifying the problem in more detail. Now it is clear what your program is supposed to do. Now I can give you advice on how to fix it.

More Problems

Apart from the problems mentioned above, I've found that the formula you use (n * (n - 1) + 1) does not really work. So I had to create a new formula. Actually two: one for even one for odd numbers.

A Possible Solution

I came up with the solution below for the given problem. I used your code as a start and fixed it up.

I needed an array to store the actual addends that the program is supposed to print and called it addends for simplicity.

In the next step we apply the formula (depending on even or odd) to calculate the middle addend then iterate toward the beginning of the array and set every element being 2 less than the previous one.

Then do this toward the other direction: starting from the middle iterate through every element toward the last in the addends array and set every element 2 more than the previous one.

After this, all is left is to print the elements of addends.

I grouped the relevant code into a single function called Pow3().

I've also created a small function TestPow3() to test if the Pow3() works correctly. This utilizes a macro called TEST that checks if the function's return value (the n3) matches an expected value.

The Code

#include <stdio.h>

// Checks if `testToRun` equals `expected`
#define TEST(testToRun, expected)   \
    if ((testToRun) == (expected))  \
        printf(" <<< SUCCESS\n");   \
    else                            \
        printf(" <<< FAILURE\n")

// Calculates n ^ 3 based on addition and returns it. Additionally, it prints the addends on the standard output
int Pow3(int n)
{
    //
    // Validating the input parameter
    //
    if (n < 1 || n > 30)
    {
        printf("The integer input is out of range!");
        return -1;
    }

    //
    // Calculating the addends
    //
    int addends[n];
    int middle = (n - 1) / 2; // Start index of the addends
    addends[middle] = n % 2 == 0 ? n * n - 1 : n * n;
    for (int i = middle - 1; i >= 0; i--)
        addends[i] = addends[i + 1] - 2;
    for (int i = middle + 1; i < n; i++)
        addends[i] = addends[i - 1] + 2;
    
    //
    // Printing the addends and the sum
    //
    int sum = 0;
    for (int i = 0; i < n; i++)
    {
        sum += addends[i];
        printf("%d", addends[i]);
        if (i != n - 1)
            printf(" + ");
    }
    printf(" = %d", sum);
    return sum;
}

// Unit tests for Pow3()
void TestPow3()
{
    //
    // Testing all the positive test cases
    //
    for (int i = 1; i <= 30; i++)
        TEST(Pow3(i), i * i * i);

    //
    // Testing some negative test cases  
    //
    TEST(Pow3(0), -1);
    TEST(Pow3(31), -1);
}

int main()
{
    //TestPow3(); // Uncomment to run unit tests for Pow3()
    
    //
    // User input
    //
    int n = 0;
    printf("Input integer value in range [1, 30]: ");
    scanf("%d", &n);
    return Pow3(n);
}

Note #1

The above code works only on Linux/Unix based systems as the Microsoft C compiler does not support variable-length arrays:

    int addends[n];

In this case, the array needs to be dynamically allocated and deallocated, once it's not needed anymore (see malloc() and free()). This involves some performance hit, but probably this is not a concern at all for this task.

Note #2

Feel free to modify my code to your needs. It is just one example of how it could be done. Feel free to enhance it. Make it better! Experiment!

Have fun! :)

commented Nov 22, 2021 by Lexus Guevara (1,010 points)
uhm sir, I will post my problem here, and I think it is hard to explain it

Cube of a number can also be solved using addition instead of multiplying the number three times, and this is the pattern:

1 = 1
2 = 3 + 5 = 8
3 = 7 + 9 + 11 = 27
4 = 13 + 15 + 17 + 19 = 64
5 = 21 + 23 + 25 +27 +29 = 125
So on so forth...

Write a program in which you enter an integer value from 1 to 30 and it will display all the addends. If  the user input less than 1  or greather than 30, the program will display a message "The integer input is out off range".

As  a check, you migt also try to add all the addends to see if you displayed all the correct addends.


OUTPUT :

Input integer value : 5
Addends : 21 23 25 27 29
Sum of Addends : 125

it looks like the addends shown should be the same number as the number itself, (e.g. 10 is the integer, then 10 addends should be seen in the output. Also as you add all the addends, the sum will be the cube of the integer.
commented Nov 22, 2021 by Peter Minarik (84,720 points)
Thank you, sir. Now I know what your program is supposed to do. Let me see how to correct your code...

First of all, your

x = (n * (n - 1)) + 1; //formula to get the first addend

does not work. Try it with 4: the result will be 11 + [13] + 15 + 17 = 56, but correctly it should be 13 + [15 ] + 17 + 19 = 64

So I had to update your formula.

Please, see the solution in the original answer of mine under the UPDATE section.
commented Nov 22, 2021 by Lexus Guevara (1,010 points)
thank you ,sir. I already update your output, I changed my output based on the example that I have shown you. Thank you very much again. I'm just a first year college that's why I don't yet understand those #define thingy but definitely I will tackle it very soon.
commented Nov 22, 2021 by Peter Minarik (84,720 points)
Good luck with your journey! I hope you'll enjoy it. :)
commented Nov 22, 2021 by Peter Minarik (84,720 points)
One more thing: #define thingy. :)

It's called a macro. The name of the macro gets automatically replaced during the preprocessing phase of the compilation by the value of the macro.

Read how they work: https://docs.microsoft.com/en-us/cpp/preprocessor/hash-define-directive-c-cpp?view=msvc-170

It's a bit lengthy and contains Microsoft specific descriptions (feel free to skip them if you're only interested in Linux/Unix; definitely read them if you are interested in Microsoft Windows development).
0 votes
answered Nov 21, 2021 by VerySomething (140 points)
Hello, I do the simulation :

I choose 10 in input

So n=10 I think

Then i=1000 and x=91

Then I enter the if{...} and only x change, it becomes 93

The if is terminated and 93 is printed

I want enter the while loop: I can't because x>n

n didn't change
commented Nov 22, 2021 by Lexus Guevara (1,010 points)
I also think about that when I input an integer, the result should be the same number as the integer, (e.g. 10 is the integer, then the result should be 91 93 95 97 99 101 103 105 107 109.) then as you add those numbers, you can get 1000 to it which is the cube of the integer value.

but I don't figured it out yet that's why I am also finding for solutions
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...