#Calculate Sum of First N Integers

1 messages ยท Page 1 of 1 (latest)

wind belfryBOT
#

@zenith chasm has a question:

nenfal

I'm doing a training course and I admit I'm a bit off-putting, I find it a totally stupid exercise. Concerning Swing

"1. Write an application that calculates the sum of the first N integers.
The variable N will be entered by the user using a "readInteger()" function provided to you and used as follows:

N=readInteger();```
Calling this function will produce the following display:
After entering the value 6 (for example) and after validating the dialog box above, the variable N is set to 6.
You will write the three solutions to this exercise using the three iterative structures: WHILE, REPEAT, and FOR. ๏‚ท The result will be displayed by calling the displayDialogBox(...) procedure
also provided, which will be used as follows:
displayDialogBox("The result with while() {...} is: " + result,
"Result with While");
... to produce the following display:
The solution will be provided with the SumFirstIntegers project"
#

<@&987246399047479336> please have a look, thanks.

rugged garden
#

whats ur question, how can we help you? ๐Ÿ™‚

junior sedge
#

@zenith chasm you can use the loops with the following flow : ```
int sum = 0;
for(int _ = 1; _<= n; _++){
sum+= _}

u can do this for all the methods u specified, and put the input for N and the output format as needed.
wind belfryBOT
zenith chasm
#

Hello, thanks for your help

#

I'm in training, brand new to Java and Swing. In fact, I just don't find any sense in this exercise which consists of giving a value to N from a textField and then creating a loop

#

It automatically made a thread for it

tight topaz
#

to get help, you need to specify which part confuses you

#

that way you wont be confused the next time this problem pops up

zenith chasm
#

I didn't find the meaning of this exercise, why make a loop for a dialog box
I also thought at first that it was a scanner that had to be used to record the text

tight topaz
#

oh, these kinds of assignments dont tend to have production value

#

they are for exposure & practice

zenith chasm
#

Yeah exactly

#

Its for my training

tight topaz
#

you gotta be able to solve problems like this if you expect to be on the field

#

a problem like this should be a non-issue. but if you do have issues with it, then that highlights a knowledge gap

zenith chasm
#

We just started learning java

tight topaz
#

but yes, most assignments at the beginner level dont focus on "what is good for production?"

#

its all about exposing you to new tools and APIs, ways to think of logic, how to have 2 systems interact, etc..

zenith chasm
#

I see, k

#

Do you have some advices to become a good developer?

#

I lost some motivation, trying to practice and focus but It doesn't seem to work

tight topaz
zenith chasm
#

Right now? Not really

hollow oriole
tight topaz
#

now we're treading into opinion-based territory

#

what even is a good developer?

tight topaz
#

what is it you even want to do?

zenith chasm
#

In fact, I have logic, I know that I could do great things but currently I am starting to lose what I have learned. In our training, we did not have enough time or support in what we do. It is more discovery than real practice, I do not know how to explain

tight topaz
#

someone who is good with graphics may suck with networking

tight topaz
zenith chasm
#

I'm training as an Application Developer, so we're full-stack.

tight topaz
#

didnt practice it enough for it to become familiar

hollow oriole
#

If you like math, knowing how things work, and like to write in general (not code, but words on paper) then it's a good avenue to pursue.

zenith chasm
#

oops wrong person sorry

tight topaz
#

me too, im not great at math. programming isnt all math

#

someone who is good with math may be bad with code architecture

zenith chasm
#

I see that yeah

tight topaz
#

and vice versa

#

so it sums up to: what is your goal? what apps are you trying to write?

#

or what job are you aiming for?

zenith chasm
#

In fact, development has gone from a pleasure to a job.

I almost force myself to do it. I have projects, including a portfolio, but I can't even finish them due to lack of motivation

tight topaz
#

what you should do next will depend on things like that

#

are you currently employed in the domain?

#

if not, thats a bad sign, to be burnt out before even getting onto the field

zenith chasm
#

Nope

#

Looking for internship

tight topaz
#

but maybe you just havent been exposed to programming in the right light. a light that fits you

zenith chasm
#

But nobody is looking for developers

#

the market is f*cked

tight topaz
#

which brings me to: why are you still programming? what keeps you here?

#

theres gotta be SOMETHING you like

#

it was a hobby before, yeah?

zenith chasm
#

The desire to get a degree and the hope of gaining that developer status

#

Yes, my passion is computing in all areas

tight topaz
#

cold hard truth: youll never be seen as a true dev. only by those under you

#

but there will always be people over you too

zenith chasm
#

yeah

tight topaz
#

the best you can be is just a dev, who is capable

#

we can move this to #geek-speak or even #career-talk if you wanted to go down the career route

#

or even open a new #1051826284008853505 in regards to your perspective on programming. "why do they have me doing this? what should i do next?" etc..

#

cause this post is still about calculating sums

zenith chasm
#

Sure

It's super interesting to talk with experienced developers, I want to succeed

tight topaz
#

ping me if you make a post

zenith chasm
#

Sorry!

tight topaz
#

no worries, we're here to help. just don't wanna clog up this thread with unrelated stuff, as others may view the thread (either to help, or to learn from it)

zenith chasm
#

Of course

hollow oriole
#

Challenge: Find this sum of first N integers without looping at all.

rugged garden
junior sedge
#

@zenith chasm are you by any chance, doing this as a college practice thing?

rugged garden
left nest
#

and thus I would actually avoid using it in this context

#

because it usually has a different meaning

junior sedge
#

Ah okay, i used to use it in python all the time , didnt know its a bad practice for java

junior sedge
#

can you send me a picture / screenshot of how the problem is presented to you, and how are u expected to submit the code and the output, I can help you understand the purpose if I can see that part

zenith chasm
#

Well it is in french

#

I need to use while, repeat and for

queen ginkgo
#

It is not repeat, it is do while, while and for.

junior sedge
#

@zenith chasm well the goal of your training is to get you well-versed with concepts of looping , Do you want actual help with the code or were you just trying to understand the point? its basic practice problems, approaching it with all three just helps you realize what seems best, because after certain time, you will be able to recognize patterns and see which kind of control structure suits your needs the best.

zenith chasm
#

Bad at maths, I still need to find how to proceed with the calculation method

junior sedge
#

there is not much math involved, to find the sum of first N integers, simply add the given integers one by one?

#

Set an initial var called sum, initialize it with value = 0 as the sum of first 0 natural numbers will be 0 itself

zenith chasm
#
package org.algo;

import javax.swing.*;
import java.awt.event.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Valeur de N");
        frame.setSize(300, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);

        JLabel label = new JLabel("Entrez un nombre N :");
        label.setBounds(20, 20, 150, 25);
        frame.add(label);

        JTextField textField = new JTextField();
        textField.setBounds(150, 20, 100, 25);
        frame.add(textField);

        JButton button = new JButton("Valider");
        button.setBounds(100, 60, 100, 30);
        frame.add(button);


        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int N = 0;
                int i = 1;
                while (i <= N) {
                    N = N + i;
                    i++;                    
                }
                JOptionPane.showMessageDialog(frame, "La somme des " + N + " premiers entiers est : " + N);
            }
        });

        frame.setVisible(true);
    }
}
junior sedge
#

then as u go on increasing the value of n, u keep adding it to the sum variable

wind belfryBOT
junior sedge
#

I think u need to take N as input from the user, Or use a pre defined value, and use another int to use for the N = N+i; operation

#

int sum = 0; would be better, and also you dont need to explicitly define var = var + i; just do var += i

#
int N = // take input
int Sum = 0;
                int i = 1;
                while (i <= N) {
                    Sum += i;
                    i++;                    
                }
wind belfryBOT
tight topaz
#

id agree with zab: its technically not an unused variable. beyond that, its a mutable variable

#

so having it basically labeled as an "unused variable" is misleading

zenith chasm
#

Alright thank you, checking

#
package org.algo;

import javax.swing.*;
import java.awt.event.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Valeur de N");
        frame.setSize(300, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);

        JLabel label = new JLabel("Entrez un nombre N :");
        label.setBounds(20, 20, 150, 25);
        frame.add(label);

        JTextField textField = new JTextField();
        textField.setBounds(150, 20, 100, 25);
        frame.add(textField);

        JButton button = new JButton("Valider");
        button.setBounds(100, 60, 100, 30);
        frame.add(button);


        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int N = Integer.parseInt(textField.getText());
                int i = 1;
                while (i <= N) {
                    N += i;
                    i++;
                }
                JOptionPane.showMessageDialog(frame, "La somme des " + N + " premiers entiers est : " + N);
            }
        });

        frame.setVisible(true);
    }
}
wind belfryBOT
# zenith chasm ```java package org.algo; import javax.swing.*; import java.awt.event.*; publi...

Detected code, here are some useful tools:

[WARNING] The code couldn't end properly...

Problematic source code:

package org.algo;

import javax.swing.*;
import java.awt.event.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Valeur de N");
        frame.setSize(300, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);

        JLabel label = new JLabel("Entrez un nombre N :");
        label.setBounds(20, 20, 150, 25);
        frame.add(label);

        JTextField textField = new JTextField();
        textField.setBounds(150, 20, 100, 25);
        frame.add(textField);

        JButton button = new JButton("Valider");
        button.setBounds(100, 60, 100, 30);
        frame.add(button);


        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int N = Integer.parseInt(textField.getText());
                int i = 1;
                while (i <= N) {
                    N += i;
                    i++;
                }
                JOptionPane.showMessageDialog(frame, "La somme des " + N + " premiers entiers est : " + N);
            }
        });

        frame.setVisible(true);
    }
}```
Cause:
The code doesn't compile:
illegal start of expression

## System out
[Nothing]
junior sedge
#

Basically, N will define how many Natural numbers, the first n natural numbers, you have to take for the addition, and its task is complete, you do not need to edit it again. You compute the algebraic sum of all the first n-natural numbers, for an example, if you use N=5, your loop must go from 1 to 5, which is done via while(i <= n and further the i++.
the correction will look like this :

                int N = Integer.parseInt(textField.getText());
                int Sum = 0;
                int i = 1;
                while (i <= N) {
                    Sum += i;
                    i++;
                }
                JOptionPane.showMessageDialog(frame, "La somme des " + N + " premiers entiers est : " + N);
            }```
wind belfryBOT
junior sedge
#

Also Integer.parseInt(textField.getText()) can throw a NumberFormatException if the input isn't a valid integer. ( it isnt really necessary for the current project and its learning scope but is some extra info you may want to use.)

zenith chasm
#

What sum is doing here ๐Ÿค”
Still confused

junior sedge
zenith chasm
#

ahh

junior sedge
#

in your code, int N = Integer.parseInt(textField.getText()); int i = 1; while (i <= N) { N += i; i++; }
once you do N += i; , the value of N will be changed, and the scope of the while loop will also be changed along with it since the break condition is i <= N

wind belfryBOT
zenith chasm
#

Idk why I don't have the logic lmao

#

Alright

junior sedge
# zenith chasm Idk why I don't have the logic lmao

its simple, you take N to identify how many numbers your loop will add, like how many times the loop will execute, and you calculate and store the sum independently from it, here using a new variable called sum.

hollow oriole
#

What if N is large? Is int an appropriate type for sum?

junior sedge
#

But yeah if the use case is a big value for N, shifting to long is better.

zenith chasm
wind belfryBOT
# zenith chasm

I uploaded your attachments as Gist. This makes them more accessible, for example to mobile users.

zenith chasm
#

I could just use one common var like sum

junior sedge
# zenith chasm

The individual workings are fine if this suits your task ( having all three in one isnt good but isnt necessarily bad either as long as it is for learning ), There is a slight issue in the 'do-while' part though, Initializing with 1 here is wrong for the edge case that N=0, your current program will return '1' here instead of zero because of how do-while works

#

Initializing the var9 with 0 is better for just this case, as the code inside Do will always run once, even if the condition is actually false.

zenith chasm
#

ahh I see, thank you

hollow oriole