-1

Hey there! In the following code, I am trying to count frequency of each non zero number

My intention of the code is to update freq after testing each case using nested loop but value of freq is not updating. freq value remains to be either 0 or 1. I tried to debug but still ending up with the same bug.

Code:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int size;
    cin>>size;
    int freq=0;
    int d[size];
    for(int i=0;i<size;i++){ //To create array and store values in it
            cin>>d[i];
    }
    for(int i=0;i<size;i++){
            if(d[i]==0 )continue;
            for(int j=0;j<size;j++){
            if(d[i]==d[j]){
                    freq=freq+1;
                    d[j]=0;
                }
            }
            cout<<"Frequency of number "<<d[i]<<" is "<<freq<<endl;
            d[i]=0;
            freq=0;
    }
}

Input:

5

1 1 2 2 5

Expected output:

Frequency of number 1 is 2


Frequency of number 2 is 2 


Frequency of number 5 is 1

Actual output:

Frequency of number 0 is 1

Frequency of number 0 is 1

Frequency of number 0 is 1

Frequency of number 0 is 1

Frequency of number 0 is 1

Some one please debug the code and fix it. Open for suggestions.

cigien
  • 57,834
  • 11
  • 73
  • 112
  • If you are trying to learn C++ programming from those "competition" or "code challenge" websites, then please don't. They are not teaching you the right skills. – n. m. could be an AI Oct 15 '22 at 05:59
  • @n. 1.8e9-where's-my-share m but companies expects us to code like that right and what is wrong in writing my code short? why is it wrong to type my code like that? – Kharinandan D N Oct 15 '22 at 06:25
  • [Why should I not `#include `?](https://stackoverflow.com/q/31816095/995714), [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/q/1452721/995714). Use both of them brings disaster – phuclv Oct 15 '22 at 07:32
  • 1
    C++ **must** be learnt using a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of by solving random online puzzles. These are also available as PDFs for free. – Jason Oct 15 '22 at 07:58
  • *"Some one please debug the code and fix it..."* No, **we're not going to debug your code for you**. That's not how stack overflow works. You should write your own test cases and learn to use a debugger. Also refer to [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). – Jason Oct 15 '22 at 07:58

2 Answers2

0

To build an histogram, you actually need to collect history.

Example:

int main() {
    int size;
    cin >> size;

    int d[size];
    int hist[size + 1]{};             // all zeroes - this is for the histogram
    for (int i = 0; i < size; i++) {  // To create array and store values in it
        cin >> d[i];
    }
    for (int i = 0; i < size; i++) {
        ++hist[d[i]];
    }
    for(int i = 0; i < size; ++i) {
        cout << "Frequency of number " << i << " is " << hist[i] << endl;
    }
}

Note: VLAs (Variable Length Arrays) are not a standard C++ feature. Use std::vector instead.

A slightly different approach would be to not be limited by the size parameter when taking the input values. std::map the value to a count instead:

#include <iostream>
#include <vector>
#include <map>

int main() {
    int size;
    if(not (std::cin >> size) or size < 1) return 1;

    std::map<int, unsigned long long> hist; // number to count map

    for(int value; size-- > 0 && std::cin >> value;) {
        ++hist[value];
    }

    for(auto[value, count] : hist) {
        std::cout << "Frequency of number " << value << " is " << count << '\n';
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Hi @Ted Lyngmo ! What was wrong with my approach? My `if` statement `if(d[i]==0)` is not getting true for some reason. When d[j] turns zero, next time when d[i] runs it should ignore the value zero and continue the loop right? But the if statement is not working like it should. – Kharinandan D N Oct 15 '22 at 05:43
  • @KharinandanDN The problem is that your loop has a bad idea about history since it tries to determine the frequency while still collecting values. Collect values first, then count the number of occations. – Ted Lyngmo Oct 15 '22 at 05:46
  • I used variable `freq` to store values of the frequency. Once a number is checked inside an array `freq` value turns zero. So next time I can still use the `freq` variable to store the frequency of other consecutive non zero numbers. Why do we need history, if `freq` variable is doing the job. I am just beginner in coding, sometimes my technical terms are absurd, Sorry for that. – Kharinandan D N Oct 15 '22 at 05:55
  • _"variable `freq` to store values"_ - It can hold _one_ value at a time - not value**s**. _"Why do we need history"_ - because you are creating a histogram. You won't know about the number of times a certain number has occured until you've gotten all the input. – Ted Lyngmo Oct 15 '22 at 05:56
  • I use `freq` to just update value everytime. Just like the example following. ```for(int i=0;i<5 – Kharinandan D N Oct 15 '22 at 06:00
  • @KharinandanDN Think about it for a second. If you are responsible for counting more than one thing, like colors of peoples shirts at a gate if you will: "1 yellow, 1 black, 1 tan, a second yellow ..." - when do you think you need more than one variable to keep track of it? You need one counter per thing you are counting. – Ted Lyngmo Oct 15 '22 at 06:03
  • But i can directly say the value of shirt color at that instance right. For example I say 1 yellow shirt if I see one at that instance. Please check my code once again Ted. – Kharinandan D N Oct 15 '22 at 06:07
  • @KharinandanDN You can say "one yellow" shirt when it passes. Does that tell you how many yellow shirts that will have passed at the end of the day? You've used the variable name `freq` which in itself implies "somethings / unit". – Ted Lyngmo Oct 15 '22 at 06:08
  • what exactly should I do now to get my desired output?? – Kharinandan D N Oct 15 '22 at 06:09
  • You are in a mind-trap and need to get out of it. You need one counter per thing you are counting. The one `freq` counter you have now will not be enough. – Ted Lyngmo Oct 15 '22 at 06:10
  • I'll try your approach and get back to you. Thanks for your time :) – Kharinandan D N Oct 15 '22 at 06:13
  • @TedLyngmo OP tries the following approach. "This is yellow, so let's count yellow thing and paint them black as we go. This is red, so let's count red things and paint them black as we go. This is black, we are not counting black things, skip." It totally works if done correctly, although not efficiently. – n. m. could be an AI Oct 15 '22 at 06:16
  • @n.1.8e9-where's-my-sharem. Yeah, you're right. I'm stuck in old habbits and didn't consider making the current approach actually working. – Ted Lyngmo Oct 15 '22 at 06:26
  • @n. 1.8e9-where's-my-share m. How long are you coding. How come you figured the problem so quickly. How long will it take for me to be like you? Can you please suggest me a right path – Kharinandan D N Oct 15 '22 at 07:06
0

#include <bits/stdc++.h>

This is not standard C++. Don't use this. Include individual standard headers as you need them.

using namespace std;

This is a bad habit. Don't use this. Either use individual using declarations for identifiers you need, such as using std::cout;, or just prefix everything standard in your code with std:: (this is what most people prefer).

int d[size];

This is not standard C++. Don't use this. Use std::vector instead.

      for(int j=0;j<size;j++){
      if(d[i]==d[j]){

Assume i == 0. The condition if(d[i]==d[j]) is true when i == j, that is, when j == 0. So the next thing that happens is you zero out d[0].

Now assume i == 1. The condition if(d[i]==d[j]) is true when i == j, that is, when j == 1. So the next thing that happens is you zero out d[1].

Now assume i == 2. The condition if(d[i]==d[j]) is true when i == j, that is, when j == 2. So the next thing that happens is you zero out d[2].

Now assume i == 3 ...

So you zero out every element of the array the first time you see it, and if(d[i]==d[j]) never becomes true when i != j.

This can be fixed by changing the inner loop to

   for (int j = i + 1; j < size; j++) {

This will output freq which is off by one, because this loop doesn't count the first element. Change freq = 0 to freq = 1 to fix that. I recommend having one place where you have freq = 1. A good place to place this assignment is just before the inner loop.

Note, I'm using spaces around operators and you should too. Cramped code is hard to read.

Here is a live demo of your program with all the aforementioned problems fixed. No other changes are made.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • why do we have to use standard c++ style of typing my code. The way I type my code is much faster right? I am just a beginner, so please help you me out. – Kharinandan D N Oct 15 '22 at 06:18
  • 2
    "The way I type my code is much faster right?" Wrong. "I am just a beginner" Teach yourself the right habits from the get go, because if you teach yourself wrong habits, they will hurt you when you try to do non-toy programs or get a job. If you only ever try to do these "challenge" programs and not engage in professional programming, then do what you want, it doesn't matter. – n. m. could be an AI Oct 15 '22 at 06:23
  • 1
    _"why do we have to use standard c++ style of typing"_ - You don't. You can code in any "style" you want, but if you want to communicate with other programmers in a common language, then using that language instead of slang will get you further. You will also find that you learn how to program in a way that works _everywhere_, not only on the computer or with the toolchain you are currently using. – Ted Lyngmo Oct 15 '22 at 06:30
  • @n. 1.8e9-where's-my-share m. Sorry if I sounded rude. I am open to learn the right method but I am just confused by my peers. The thing is I don't know what is wrong or right in programming. For example: You said that "using namespace std " is bad habit, but still I don't understand how that is bad because that statement allows you reduce the code length right? My intention of coding right now is to get a job at big mnc. If mnc expect me to code like that I am ready to do it. Just say the right method to learn. – Kharinandan D N Oct 15 '22 at 06:35
  • @KharinandanDN [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) explains it quite well. – Ted Lyngmo Oct 15 '22 at 06:37
  • 1
    @TedLyngmo Thanks once again . Stackoverflow community is phenomenal. – Kharinandan D N Oct 15 '22 at 06:47
  • 1
    "I am just confused by my peers" Your peers *are* confused. Try to find alternative ways of learning. "I don't know what is wrong or right in programming." This site is here to show you. "that statement allows you reduce the code length right?" This is **not** always a good thing. "to get a job at big mnc" Perhaps listen to people who actually have a job at a big mnc. Read [good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) not code competition sites. "If mnc expect me to code like that" Cannot speak for all mncs, but those I have worked for do. – n. m. could be an AI Oct 15 '22 at 06:52
  • -n. 1.8e9-where's-my-share m. Thank you for your suggestions. – Kharinandan D N Oct 15 '22 at 07:10
  • @KharinandanDN C++ **must** be learnt using a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of by solving random online puzzles. These are also available as PDFs for free. – Jason Oct 15 '22 at 08:00