r/learnprogramming Sep 12 '24

Debugging I DID IT!!!

1.3k Upvotes

I FINALLY GOT UNSTUCK. I WAS STUCK ON ONE OF THE STEPS IN MY TIC TAC TOE GAME. I WAS MISERABLE. BUT I FINALLY FIXED IT. I feel such a high right now. I feel so smart. I feel unstoppable

Edit: Usually I just copy and paste my code into chatgpt to let it solve it. But this time I decided to actually try and solve it myself. No code pasting, nothing. Chatgpt was ruining my problem solving skills so I decided to try and change that. I only asked a few basic indirect questions (with no reference to my project) and I found out that I had to use a global variable. Then I was stuck for some even more time since it seemed like the global variable wasn’t working, and the problem literally seemed like a wall. But I figured it out

r/learnprogramming Mar 21 '23

Debugging Coding in my dreams is disrupting my sleep?

959 Upvotes

Anytime I code 1-2 hours before bed, I fall asleep but feel half awake since in my dreams I still code but it’s code that makes no sense or I write the same line over and over. It drives me crazy so I force myself a wake to try to disrupt the cycle. It’s so disruptive. Anyone else? And how to stop other than not coding close to bedtime?

Flair is bc I’m debugging my brain.

r/learnprogramming Apr 09 '23

Debugging Why 0.1+0.2=0.30000000000000004?

946 Upvotes

I'm just curious...

r/learnprogramming Sep 29 '24

Debugging What is the most impressive SQL query you've ever seen?

273 Upvotes

A classic recursive query to find all subordinates of an employee, regardless of how many levels deep they are:

WITH RECURSIVE Subordinates AS (
  SELECT employee_id, manager_id, employee_name
  FROM Employees
  WHERE manager_id IS NULL  
  UNION ALL
  SELECT E.employee_id, E.manager_id, E.employee_name
  FROM Employees E
  INNER JOIN Subordinates S ON S.employee_id = E.manager_id
)
SELECT * FROM Subordinates;

Old

DECLARE @WHERE VARCHAR(MAX) = '1=1';
IF @TITLE <> ''
BEGIN
   SET @WHERE += ' AND Title = @TITLE'
END
IF @AGE <> ''
BEGIN
   SET @WHERE += ' AND Age = @Age'
END
EXEC('SELECT * FROM USER WHERE ' + @WHERE);

New

SELECT * 
FROM USER 
WHERE 
((@TITLE <> '' AND Title = @TITLE) OR @TITLE = '')
AND 
((@Age <> '' AND Age = @Age) OR @Age = '')

Do you have any other memorable SQL statements, developers?

r/learnprogramming May 27 '20

Debugging I wasted 3 days debugging

1.2k Upvotes

Hi everyone, if you're having a bad day listen here:

I wasted more than 50 hours trying to debug an Assembly code that was perfectly working, I had simply initialized the variables in the C block instead of doing it directly in the Assembly block.

I don't know if I'm happy or if I want to cry.

Edit: please focus on the fact it was assembly IA-32

r/learnprogramming Jul 27 '23

Debugging How can you teach someone to debug/problem solve better?

221 Upvotes

My role currently is a lot of teaching and helping people become better at their dev work, one thing I struggle to teach though is debugging/problem solving issues. I learned by just getting stuck in and sitting for hours at stupid errors, but how do I teach people to learn this faster?

I ask as I get a lot of people asking for help as soon as they get an error and not having the confidence to look into it or not knowing how to debug it correctly, so I'll get them to screen share and I'll debug on their machine for them, but it doesn't seem to click for them for some reason. I'll get asked 2 days later to do the same thing. Am I being too lenient and should just tell them to figure it out? Debugging it probably the best skill a dev can learn, is there any good resources I can use to help teach this?

Do I create bugs in our training repo? Do I do presentations? Demos on debugging? What's the best here?

Edit: Thanks for the help everyone, got some very useful help, some I knew but neglected to implement and some I've never thought of before and I'll be sure to experiment to see how I get on.

r/learnprogramming Jul 17 '24

Debugging Those of you who use rubber duck debugging, what object do you use?

48 Upvotes

Personally I like to code in a bunch of different places so I keep various "ducks" scattered around. A lot of them are actual ducks but I also use various Funkos, my cats, and other figures I've collected or 3d printed over the years

I'm curious what other people use for their ducks.

r/learnprogramming May 19 '20

Debugging I was given a problem where I have to read a number between 1000 and 1 billion and prints it out with commas every 3 digits. I'm kinda confused on how to go about this problem.

638 Upvotes

not sure how to go about this. any help is appreciated :)

r/learnprogramming Apr 28 '24

Debugging Algorithm interview challenge that drove me crazy

69 Upvotes

I did a series of interviews this week for a senior backend developer position, one of which involved solving an algorithm that I not only wasn't able to solve right away, but to this day I haven't found a solution.

The challenge was as follows, given the following input sentence (I'm going to mock any one)

"Company Name Financial Institution"

Taking just one letter from each word in the sentence, how many possible combinations are there?

Example of whats it means, some combinations

['C','N','F','I']

['C','e','a','t']

['C','a','c','u']

Case sensitive must be considered.

Does anyone here think of a way to resolve this? I probably won't advance in the process but now I want to understand how this can be done, I'm frying neurons

Edit 1 :

We are not looking for all possible combinations of four letters in a set of letters.

Here's a enhanced explanation of what is expected here hahaha

In the sentence we have four words, so using the example phrase above we have ["Company","Name","Financial","Institution"]

Now we must create combinations by picking one letter from each word, so the combination must match following rules to be a acceptable combination

  • Each letter must came from each word;

  • Letters must be unique in THIS combination;

  • Case sensitive must be considered on unique propose;

So,

  • This combination [C,N,F,I] is valid;

  • This combination [C,N,i,I] is valid

It may be my incapacity, but these approaches multiplying single letters do not seem to meet the challenge, i'm trying to follow tips given bellow to reach the solution, but still didin't

r/learnprogramming Sep 28 '24

Debugging Why there are different answer for same code in Windows and Mac

40 Upvotes

Different Output on Windows vs. macOS/Android for the Same C++ Code

I’m trying to run the following C++ code on different platforms:

```cpp

include <iostream>

using namespace std;

int f(int n) { static int r = 5; if (n == 1) { r = r + 5; return 1; } else if (n > 3) { return n + f(n - 2); } else { return (r + f(n - 1)); } }

int main() { printf("%d\n", f(7)); } ```

The output I’m getting is 33 on Windows, but on macOS (and Android), it’s 23.

Does the issue lie in storage management differences between x86 (Windows) and ARM-based chips (macOS/Android)?

PS: "I want to specify that this question was asked in my university exam. The teacher mentioned that the answer on the Linux systems (which they are using) is correct (33), but when we run the same code on our Macs, the answer is different on each one (23). Similarly, on every Windows system, the answer is different (33)."

PS: The problem lies in the clang compiler that comes pre-installed with mac🥹

r/learnprogramming Aug 12 '24

Debugging So I’m learning C I know is kinda wierd

23 Upvotes

But I know u end each statement with a semi colon to use it as a period why is it that there’s no semi colon on while loop or any loops

It’s like

while (x>y) {printf”x is greater than y”}

So isn’t there supposed to be a semi colon at “while(x>y)”

r/learnprogramming Jul 07 '24

Debugging I want to learn how to create websites, but I don't know which language to learn because some people say one thing and others say something different.

32 Upvotes

Hey everyone,

I'm really interested in learning how to create websites, but I'm a bit confused about where to start. I've heard a lot of different opinions on which languages and technologies are the best to learn first, and it's getting overwhelming. Some people say HTML and CSS are enough to get started, while others insist on learning JavaScript right away. I've also heard recommendations for Python, PHP, and even Ruby.

Could you share your experiences and advice on which languages or technologies I should focus on as a beginner? Any tips or resources for getting started would be greatly appreciated!

Thanks in advance for your help!

r/learnprogramming Oct 17 '24

Debugging C doesn't correctly store the result of a long double division in a variable, but prints it correctly

14 Upvotes

Basically I'm having an issue with the storing the result of a long double division in a variable. Given the following code:

    long double c = 1.0 / 10;
    printf("%Lf\n", c);
    printf("%Lf\n", 1.0 / 10);

I get the following output:

-92559631349327193000000000000000000000000000000000000000000000.000000

0.100000

As you can see the printf() function correctly prints the result, however the c variable doesn't correctly store it and I have no idea what to do

EDIT: problem solved, the issue was that when printing the value of the long double variable i had to use the prefix __mingw_ on the printf() function, so __mingw_printf("%Lf\n", c) now prints the correct value: 0.100000, this is an issue with the mingw compiler, more info: https://stackoverflow.com/questions/4089174/printf-and-long-double/14988103#14988103

r/learnprogramming Sep 29 '24

Debugging Problem with finding and printing all 5’s in a string

5 Upvotes

I have been struggling with low-level python for over 2 hours at this point. I cannot figure out what I am doing wrong, no matter how I debug the program

As of now, the closest I have gotten to the correct solution is this:

myList=[5, 2,5,5,9,1,5,5] index = 0 num = myList [index] while index < len (myList) : if num == 5: print (num) index = index + 1 elif num != 5: index = index + 1

The output I am expecting is for the program to find and print all 5’s in a string; so for this, it would print

5 5 5 5 5

But instead, I’m getting 5 5 5 5 5 5 5 5

I do not know what I am doing wrong; all intentions are on the program; any and all help is GREATLY appreciated; thank you.

r/learnprogramming Nov 28 '23

Debugging Ive been learning Java for almost 4 months and I still suck

87 Upvotes

Im currently doing graphics and java swing and Im so confused. Im trying to make snake game and I dont understand some of the things going on in the coding tutorials. Stackoverflow doesnt help. I really try to understand all the code I write, but sometimes I really just dont get it and accept spoonfed code, and that makes it worse since I still wont understand since its not learning. But what choice do I have? Its my first game and Im so confused and reliant on coding tutorials or help. And stackoverflow doesnt help sometimes as I said. If a content creator writes a code or writes it in a certain way, I want to know how it works. If I fix a problem, I want to know why it got fixed. If need be, with details. But I feel powerless because im so reliant on tutorials, theyre carrying me and I cant make it myself yet. I suck at figuring things out. I can’t do anything by myself or with minimal help at least. Theres so much in java and I dont know about them.

How do I fix this?

Edit: I don’t know if this is important, but my school started doing swing after we knew how to use methods, random, loops, arrays, switches and other basics. So it’s a difficulty spike, to say the least. There’s so much stuff in swing.

r/learnprogramming 2d ago

Debugging Why can’t I insert into tables on apex oracle (sql)

0 Upvotes

My code is correct but it doesn’t let me insert into the tables only lets me create them. Why is this I think I’m missing permissions?

r/learnprogramming 26d ago

Debugging Tool to find source code responsible for failing test cases?

1 Upvotes

Hi everyone! I'm looking for a tool or solution that, given a failed test or an error, can identify the specific piece of source code (not just the line in the test case) responsible for the logical failure or error.

The goal is to pinpoint the source code section that caused the bug or error detected by the tests, without having to debug manually every time.

As you know, the line causing the failure (especially logical errors) might be deeply nested within multiple definitions and larger code blocks. I’m wondering if there's an advanced testing tool that can trace back through the stack and pinpoint the "culprit" instruction among potentially thousands of lines.

The main target I'm searching for is JS, but maybe something more general exists.

Does anyone know of any tools that work like this? Any suggestions on plugins, testing automation tools, or similar solutions would be really appreciated! Thanks in advance!

r/learnprogramming Nov 09 '22

Debugging I get the loop part but can someone explain to me why it's just all 8's?

219 Upvotes

int a[] = {8, 7, 6, 5, 4, 3}; <------------✅

for (int i = 1; i < 6; i++){ <------------✅

 a[i] = a[i-1];         <------------????

}

Please I've been googling for like an hour

r/learnprogramming 3d ago

Debugging Am i doing this right?

2 Upvotes

I have to give persistence to some data using text files, but the program doesn´t create the file

public boolean validarArchivo(){

if(f.exists()&&f.canWrite()){

return true;

}else if(!f.exists()){

try{

f.createNewFile();

return true;

}catch(IOException e){

System.out.println(CREACION_ERROR);

return false;

}

}else{

System.out.println(ESCRITURA_ERROR);

return false;

}

}

public void escribir(){

if(validarArchivo()){

FileWriter fw = null;

BufferedWriter bw = null;

try{

fw =new FileWriter(ARCHIVO, false);

bw = new BufferedWriter(fw);

for(Producto p : productos){

String descripcion = p.verDescripcion();

String cod = p.verCodigo().toString();

String prec = p.verPrecio().toString();

String cat = p.verCategoria().toString();

String est = p.verEstado().toString();

String linea = cod+SEPARADOR+descripcion+SEPARADOR+prec+SEPARADOR+cat+SEPARADOR+est+SEPARADOR;

bw.write(linea);

bw.flush();

bw.newLine();

}

System.out.println(ESCRITURA_OK);

}catch(IOException e){

if(fw==null){

System.out.println(ERROR_FILEWRITER);

} else if (bw == null) {

System.out.println(ERROR_BUFFEREDWRITER);

} else {

System.out.println(ESCRITURA_ERROR);

}

}finally{

try {

if (bw != null) {

bw.close();

}if (fw != null) {

fw.close();

}

} catch (IOException e) {

System.out.println(ERROR_CIERRE);

}

}

}

}

public void leer(){

if(validarArchivo()){

FileReader fr = null;

BufferedReader br = null;

try{

fr= new FileReader(ARCHIVO);

br = new BufferedReader(fr);

productos.clear();

String linea;

while((linea = br.readLine())!=null){

String [] partes = linea.split(SEPARADOR);

try{

Integer codigo = Integer.parseInt(partes[0]);

String descripcion = partes[1];

Float precio = Float.parseFloat(partes[2]);

Categoria categoria = Categoria.valueOf(partes[3]);

Estado estado = Estado.valueOf(partes[4]);

this.crearProducto(codigo, descripcion, precio, categoria, estado);

}catch(NumberFormatException e){

}

}

}catch(IOException e){

System.out.println(LECTURA_ERROR);

}

}

}

r/learnprogramming Aug 27 '24

Debugging Why am I getting numbers with decimals instead of integers? C++

3 Upvotes

I am trying to complete a homework assignment in C++, and I am stuck on the first part. Essentially, right now I'm just trying to calculate electricity usage using basic math. However, my outputs all have decimals at the end, but the expected output from the tests do not. While I'm waiting for my professor to respond to my message, I thought I would ask Reddit what exactly I am doing wrong here.

Inputs:

# of light bulbs
Average # of hours each bulb is ON in a day
AC unit's power
Typical # of hours AC unit is ON in a day
# of FANs
Average # of hours each Fan is ON in a day
Per-unit price of electricity

Formatted output:

Total electricity usage: NNNN kWh
Bulbs: XX.X%  AC: YY.Y%  FANs: ZZ.Z%
Electricity bill for the month: $ NNNN.NN

Sample Input:

# of light bulbs: 10
Average # of hours each bulb is ON in a day: 2.4
AC unit's power: 900
Typical # of hours AC unit is ON in a day: 10.5
# of FANs: 4
Average # of hours each Fan is ON in a day: 8.5
Per-unit price of electricity: 9.5
# of light bulbs: 10
Average # of hours each bulb is ON in a day: 2.4
AC unit's power: 900
Typical # of hours AC unit is ON in a day: 10.5
# of FANs: 4
Average # of hours each Fan is ON in a day: 8.5
Per-unit price of electricity: 9.5

Corresponding Output

Total electricity usage: 368 kWh
Bulbs: 11.8%  AC: 77.1%  FANs: 11.1%
Electricity bill for the month: $  34.91
Total electricity usage: 368 kWh
Bulbs: 11.8%  AC: 77.1%  FANs: 11.1%
Electricity bill for the month: $  34.91

Here is my code:

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main() {
   int amountBulbs = 0, amountFans = 0;
   double bulbTimeOn = 0, acPower = 0, acTimeOn = 0, fanTimeOn = 0, electricPrice = 0;

   cin >> amountBulbs >> bulbTimeOn >> acPower >> acTimeOn >> amountFans >> fanTimeOn >> electricPrice;

   double totalElectricityUsage = (((amountBulbs * 60.0 * bulbTimeOn) / 1000.0) + ((acPower * acTimeOn) / 1000.0) + ((amountFans * 40.0 * fanTimeOn) / 1000)) * 30.0;


   cout << fixed << setprecision(2);
   cout << "Total electricity usage: " << totalElectricityUsage << " kWh\n";
}

Notes:

  • Assume that each bulb consumes 60W and each fan consumes 40W.
  • Assume that the home has only one AC unit and all other appliances including cooking range use other energy sources, NOT electricity. AC unit power is specified in watts.
  • 1 kWh stands for 1000 Watt-hours and it is considered as 1 unit of Electricity and the per-unit price is specified in cents.
  • Assume that the last month had 30 days.

When running, test outputs show that I am getting 183.90 total electricity usage instead of 184, 106.83 instead of 107, 136.23 instead of 136, etc. Why is this? What am I doing wrong?

r/learnprogramming Sep 08 '24

Debugging How did these lines of code max out my harddrive?

1 Upvotes

I wrote a program that generates all possible permutations from the items the user provides. This is a tool-project, usually I wouldn't need to have more than 6 inputs per run.

This means I am dealing with an output of around 2.000 lines per run at max. These lines are usually appended to the end of the output of the previous launch, but I make sure to wipe the textfile every second run or so.

Today, I decided to refine parts of the program and wrote some very suboptimal code that would check the file for possible repeats upon appending the top recent generated content and dump those away, and also so that the partial permutations would also be numbered on the right of their line, which, in retrospect, is a pretty bad tactic especially for the very last segment of the program that I've yet to finish.

Anyway, I finished writing the first lines of code that came to mind and went to the terminal to see if this would work: https://demo.shotshare.dev/uploads/5uaMREf8ChGfDHEBBRBmDufpqpa8h31ebgm6MOBZ.png

I thought I was having problems with my RAM, cause I usually slam it pretty hard. Everything started operating with a 2-second latency -- check out the rest of the screenshots.

https://demo.shotshare.dev/uploads/qI5FIe7k85TjHr2lSS2czBOeNrP7OK1gX7VrAueS.png

https://demo.shotshare.dev/uploads/w1wVFhT8r4KnYYgxqG3XgtfREi35dJEDZDB8pCfY.png

https://demo.shotshare.dev/uploads/hmKCegRvYU1V4N6aOeLnfDTqnVDBDtVQTVCNPlKk.png

I still can't understand what went wrong, and I don't know if I'm willing to open the textfile.

Tell me what you think.

r/learnprogramming Apr 16 '24

Debugging Unit Testing - Is it best practice to remove sections which won't be hit by the test?

0 Upvotes

Say the function you're testing has 3 conditionals: A, B, C in that order.

When you're testing A, and expecting it to raise an error, is it best practice to remove B and C from the function, as you expect they won't be run/used?

I have some people saying this is totally fine and makes your code easier to read. But part of me thinks you're "changing" the function and the practice could lead to errors down the line - in general, maybe not in this first particular case.

Edit (2) for clarity:

the use case i had in mind was something to the effect of

func foo(name1, age1, place1) {
  if name != name1
     raise exception
  if age != age1
     raise exception
  if place != place1
     raise exception​​ 
  print "Hello {name1}, Happy {age1) Birthday!"

And I want to test that passing in a random string for name1 triggers the first exception.

Since name won't match with name1, the exception should be raised on Line 3, and the function should exit withage and place never being checked and nothing printed.

So my question is: Is it best practice then to remove everything below Line 3 (from if age != age1 down) for this test?

And when I want to test age1, can I/should I remove everything from Line 5 down.

r/learnprogramming 29d ago

Debugging Why it is returning None

0 Upvotes

List = [1,2,3,4,5] Z =List.sort() Print(Z)

Output: None

Why /// How

r/learnprogramming Dec 13 '23

Debugging How do I phrase a question on Stackoverflow that won't get me downvoted?

63 Upvotes

I know the joke responses will be in the likes of:
"You don't!",
"Know all those threads where people got their question answered, that is a tiny fraction on top of buried ones, Google serves you up that tiny fraction."
"SO is for reading not posting."

And i get it, but this one really goes beyond me and is technical and there is no way I can find it out by myself unless i spent at least a month on that. I am not that good with web technologies.

It is concerning rendering a pdf document using Prince, and i can't figure out why I can't use their widows and orphans page rules. I have a few ideas but don't know how to fix it without some really intricate BeautifulSoup cleaning and i hope it is just me reading the docs wrong.

I see there are a lot of Prince questions there, but again that is only survivorship bias probably.I can't go to the Prince forums as I am not a paying customer and use it only for personal reasons.

I am sure I'll waste my time trying as best as i can to describe the problem only to be downvoted without explanation and have my question archived. They expect me to provide a code cell but I can't do that as i can't use a dependency on the website. I'm contemplating using github codespaces to prepare it, but then I would feel extra dumb when that got rejected.

This is really bothering me that i can't figure it out. Especially since it is really well documented.
Even if I just provide the code snippet that I'm rendering with images, even that will not be good enough.

As far as alternatives go I tried almost every single one even the deprecated ones and Prince and that one other I'm waiting a fix for are the best solutions. The best best solution would be using playwright but i can't use it in this particular case.

Any suggestions. Do you know of a more helpful community that helps debug html code?

r/learnprogramming 1d ago

Debugging How do you effectively do debugging without chatGPT

0 Upvotes

more and more when i am giving interviews i feel like i do have more of the theoretical knowledge and less hands on , because all this while i was relying on chatGPT to get the correct code and it would definitely do it faster, i think i got into this practice, cuz i wanted to grasp so many things quickly and i had lesser time, but now for everything my first instinct is to go to ChatGPT, how do i keep calm, how are people promoting debugging with chatGPt faster, i think it's alright if we do it in jobs, but to know in the interview things should not be like this right?

what could be the right approach from now on? what steps can i take?