Animoise
Animoise

Reputation: 11

Loop counting code doesn't work correctly

I'm pretty new and just started programming around 3 days ago. I've finished learning the basics and am now stuck in this problem, but I can't seem to debug it.

I want it to go through the integer to find all 3s, but instead, it counts every number in it (for example, if I enter 1212, it answers back 4. I want a 0.)

#include<iostream>
using namespace std;

int main() {
    long long n; 
    cin >> n; 
    int cnt = 0;
    while (n != 0) {
        int k = n % 10; 
        if (k == 3); { 
            cnt++;
        }
        n /= 10;
    }
    cout << cnt;
}

All help would be appreciated. Thanks for reading!

EDIT: I just found out that this question was asked before. Stackoverflow won't let me delete this post, so I'll just put a reminder here. Thank you all!

Upvotes: -1

Views: 130

Answers (3)

yurich
yurich

Reputation: 175

You have a semicolon after the condition in the if statement.

Brackets in C form compound statements or "blocks". When you write an if statement or a loop, you add brackets to form a compound statement, otherwise only the first statement will be executed.

If you place a semicolon directly after the condition it will think that you just ended the statement and the body is empty (equivalent to {};). The compount statement after the semicolon is now not related to the if statement - in C you can have them on their own (to limit variable scopes and stuff), that's why it works and works every time.

Upvotes: 0

Sneha
Sneha

Reputation: 3

You have used a semicolon after the if statement which terminates it and the counter runs normally without considering the condition. Remove the semicolon and the loop should work fine.

Upvotes: 0

Hamza Aziz
Hamza Aziz

Reputation: 21

This is because you are using a semi colon after the if statement

if (k == 3);

The correct way is (and after removing ; the code worked perfectly fine)

if (k == 3)

In C++, you do not add ; after if statement.

Upvotes: 2

Related Questions