Home > Software design >  How I can consider number as a value 1 in C language?
How I can consider number as a value 1 in C language?

Time:10-19

I have a problem in my C program. I need to write a histogram of numbers. If the number on the input will be outside the interval [1, 9], consider such a number as the value 1. I don't understand why it doesn't work.

#include <stdio.h>
#include <stdlib.h>

void printHistogram_vertical(int *hist, int n);

int main()
{
int i, j;
int inputValue;

scanf("%d", &inputValue);
int hist[inputValue];

for (i = 0; i < inputValue;   i)
{
  scanf("%d", &hist[i]);
}

int results[10] = {0};

for (i = 0; i < 10;   i)
{
  for (j = 0; j < inputValue;   j)
  {
     if (hist[j] >= 10 && hist[j] < 1)
     {
        results[j] == 1;
     }
     if (hist[j] == i)
     {
        results[i]  ;
     }
  }
}

return 0;
}

 void printHistogram_vertical(int *hist, int n)
{
int i, j;
for (i = 1; i < n; i  )
{
  printf(" %d ", i);
  for (j = 0; j < hist[i];   j)
  {
     printf("#");
  }

  printf("\n");
  }
  }

Input:

9
3 3 2 3 7 1 1 4 10

My Output:

 1 ##
 2 #
 3 ###
 4 #
 5 
 6 
 7 #
 8 
 9 

The correct output:

1 ###
2 #
3 ###
4 #
5
6
7 #
8
9

If the number is bigger than 10 and smaller than 1 it should count this number as 1. I write this function:

for (i = 0; i < 10;   i)
{
  for (j = 0; j < inputValue;   j)
  {
     if (hist[j] >= 10 && hist[j] < 1)
     {
        results[j] == 1;
     }
     if (hist[j] == i)
     {
        results[i]  ;
     }
  }
}

CodePudding user response:

There are 2 problems with following condition:

 if (hist[j] >= 10 && hist[j] < 1)
 {
    results[j] == 1;
 }
  1. The comparison is broken. Value cannot be above 9 AND below 1 at the same time. It should be OR instead.
  2. What should be increment of index 1, is actually comparison == of wrong index.

Replacement:

 if (hist[j] >= 10 || hist[j] < 1)
 {
     results[1]  ;
 }

But double for loop construction is more complicated than it needs to be. It could be replaced with single for loop:

for (j = 0; j < inputValue;   j) {
    int value = hist[j];
    if(value >= 1 && value <= 9) {
       results[value]  ;
    }
    else {
       results[1]  ;
    }
}
  •  Tags:  
  • c
  • Related