I am trying to write a simple code to get the minimum and the maximum of an array. The problem is that if I choose to put this sequence of values 5 2 -13 5 1. the output is Maximum number is 5 minimum number is 1. why the code is ignoring the negative number? the same thing goes if I put a sequence of negative numbers like -2 -4 -123 -4 5 the maximum number is 5 and minimum is -4
I cant understand why!
cout<<"Enter the Value of the Array"<<endl;
cin>>valueOfArray;
cout<<"Enter the Array Elements"<<endl;
for(int i=0; i<valueOfArray;i++)
{
cin>>ArrayOfNumbers[i];
minimum=ArrayOfNumbers[0];
if(ArrayOfNumbers[i]>maximum)
{
maximum=ArrayOfNumbers[i];
}
else if(ArrayOfNumbers[i]<minimum)
{
minimum=ArrayOfNumbers[i];
}
}
cout<<"the Maximum number is "<<maximum<<endl;
cout<<"The Minimum number is "<<minimum<<endl;
There are a few problems, some of which are pointed out in the other answers.
Ultimately, to get proper output, you'll have to initialize your minimum and maximum vars to their polar opposites outside your array.
#include<climits>
long minimum = LONG_MAX;
long maximum = LONG_MIN;
for(int i = 0; i < valueOfArray; i++){
cin>>ArrayOfNumbers[i];
if (ArrayOfNumbers[i] > maximum) {
maximum = ArrayOfNumbers[i];
} else if (ArrayOfNumbers[i] < minimum) {
minimum = ArrayOfNumbers[i];
}
}
This solution will ensure that any number in the range LONG_MIN < n < LONG_MAX will register either as a minimum or maximum, as appropriate.
your looping logic is little wrong.
maybe this can help
minimum=0;
maximum=0;
for(int i=0; i<valueOfArray;i++){
cin>>ArrayOfNumbers[i];
if(ArrayOfNumbers[i]>maximum){
maximum=ArrayOfNumbers[i];
}
else if(ArrayOfNumbers[i]<minimum){
minimum=ArrayOfNumbers[i];
}
}
that happen because everytime you input data, you change your minimum value to your first data.
Related
I was making a program in C Language that determines the most frequently appeared number in an array, and also outputting the smallest most frequently appeared number, however I am encountering a bug and I was not sure which part I did wrong.
Here is the example of the program input
2
8
1 1 2 2 3 4 5 5
8
5 5 4 3 2 2 1 1
The number 2 means to create 2 different arrays, the number 8 determines the size of the array. the number afterwards determine the numbers to be put inside of the array, and the program repeats itself by inputting the size of an array etc.
Here is the expected output :
Case #1: 2
1
Case #2: 2
1
The "Case #1: 2" means that the most frequently appeared number appeared 2 times in the array (number 1 2 and 5, each appeared twice in the array), while it prints number 1 because number 1 is the smallest number in the most frequently appeared. and the same goes on for case #2
However, in my program, when I input the second case, it does not properly print the smallest number, and instead just prints nothing. But weirdly enough, if I input a different number in the second array (instead of just the first array in reverse order) it prints the correct smallest number. Here is the example output that my program creates
Case #1: 2
1
Case #2: 2
Here is the code that I made :
#include <stdio.h>
int main(){
long long t, n;
scanf("%lld",&t); //masukkin berapa kali mau bikin array
for(int x=0;x<t;x++) {
scanf("%lld",&n); // masukkin mau berapa angka per array
long long arr[200000]={0};
long long i, count, freq=0, test=0;
for(i=0; i<n; i++){
scanf("%lld", &count); //masukkin angka ke dalem array
arr[count]++;
}
for(i=0; i<200000; i++){
if(arr[i]>0 && arr[i]>=freq){
freq=arr[i];
}
}
printf("Case #%d: %lld\n",x+1,freq);
int min;
for(i=0; i<200000; i++){
if (arr[i] > min){
min = arr[i];
printf("%lld",i);
test=1;
}
}
printf("\n");
}
return 0;
}
Your problem is here:
int min;
min is not initialized so when you do if (arr[i] > min){ you have no idea what value min has.
So do
int min = INT_MIN;
That said, you don't really need min. The first arr[i] that equals freq will tell you that i is the smallest number.
Further notice that
long long arr[200000]={0};
is a bad idea. Huge arrays should never be defined as local variables as it may lead to stack overflow. Make it a global variable or use dynamic allocation.
And you should change
arr[count]++;
to
if (count >= 200000)
{
// Too big - add error handling
...
}
else
{
arr[count]++;
}
And you don't need an extra loop for finding freq. Find freq when you get the input.
I am doing this problem:
"We have a huge decimal number N. Write a program to determine the followings:
The number of digits in N.
Is N an even number?
The number of zeros in it.
Is N a multiple of 11? Note that we can determine if N is a multiple of 11 by checking the difference between the sum of the odd positioned digits and the sum of the even positioned digits. For example, 82375 is not a multiple of 11 because the sum of the even positioned digits is 2 + 7 = 9, and the sum of the odd positioned digits is 8 + 3 + 5 = 16, and the difference between 9 and 16 is 7, which is not a multiple of 11.
We will give you the number one digit per line. For example, if you get digits ‘1’, ‘2’, ‘3’, ’4’, ‘0’ in order, then the number is 12340. The number will not start with 0.
Input Format
The input has several lines. Each line has a digit. EOF indicates the end of input.
Output Format
Output the four answers above line by line. If the number is even output a 1; otherwise a 0. If the number is a multiple of 11 output a 1; otherwise output a 0.
Subtask
10 points: you can store the decimal number in an integer without overflow
10 points: the number of digits is no more than 32768, so you can store digits in an array
80 points: you will get MLE if you use array"
my code is:
#include <stdio.h>
#include <stdbool.h>
int digit(long n);
int is_even(int n);
int count_zeros(long n);
int is_multiple(long n);
int main() {
int digits = 0;
long x;
scanf("%ld", &x);
digit(x);
int even = is_even(x);
printf("%d\n", even);
printf("%ld\n",count_zeros(x));
printf("%ld\n", is_multiple(x));
}
int digit(long n)
{
int digits = 0;
while (n > 0) {
n /= 10;
digits++;
}
printf("%ld\n", digits);
}
int is_even(int n)
{
if (n % 2 == 0)
return true;
else
return false;
}
int count_zeros(long n)
{
int count = 0;
while (n > 0) {
n /= 10;
if (n %10 == 0)
count++;
}
return count;
}
int is_multiple(long n)
{
if (n % 11 == 0) {
return true;
}
else
return false;
}
Basically i dont know how to meet the problem's requirement, so I made a simpler version of the problem. Any clue on how to do this?
If you comment on this, please be nice, I am a beginner and people was rude in the past,if you have nothing important to say, do not be mean/do not comment.
Well, the first problem with your current version is it only reads one integer. However problem states that each digit is on a separate line. The first approach may be to just replace that scanf with a loop and keeping multiplying by 10 and accumulating until end of file. Then the rest of the program would work fine.
A more advanced approach will be to use an array to store the digits. An integer can hold a very limited number of digits whereas you are only bounded with the size of available memory using array.
So in the reading loop rather than storing digits in an integer, you can store digits in an array (which could be fixed size because an upper limit is given). But for the rest of the program you should change the calculation to use digits in the array instead of the regular integer arithmetic.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
The purpose of this program is to detect the maximum number in a named array. Currently, however it only detects the last digit of the array. If the else if is removed or commented out, then it works correctly detecting all but the last digit.
#include <stdio.h>
int main(){
int c,i,max;
printf("Enter the size of the array.");
scanf("%d",&c);
int array[c];
printf("Enter the integers to fill the array.\n");
for(i=0;i<c;i++){
scanf("%d",&array[i]);
}//end for
int last_element = array[c-1];
for(i=0;i<c;i++){
printf("%d",array[i]);
if(array[i-1] > array[i]) //This if statement detects greatest
{ //index of array for all but last index
max = array[i-1];
}//end if
else if(last_element > array[i-1]) //This else if detects greatest
{ //index of array in last index
max = last_element; //This statement is always eval
}//end if //uating true.
}//end for
printf("\n%d",max);
return 0;
}//end main
largest = array[0]; //consider your 1st element as largest element
for (i = 1; i < size; i++) //
{
if (largest < array[i]) //compare largest element with i'th element
largest = array[i]; //if it is, make i'th element as largest
}
printf("\n largest element present in the given array is : %d", largest);
try this
Going point by point for error corrections :
for(i=1;i<c;i++) i needs to be set to 1. So that when you do array[i-1] , it starts from i = 1 such that, array[1-1] happens.
Otherwise if i is set to 0 then it will turn out to array[0-1]
,i.e, array[-1], since this value is not defined, it could point to
any value in stack memory.
if(array[i-1] > array[i]) This if statment simply checks, if a previous value is greater than its next value, i.e, if an array 1 2 3
4 5 6 7 is there, it would only see. if (array[0]>array[1] ) , then
if(array[1] > array[2] ). In the example array, 1 2 3 4 5 6 7 ,
which is ascending order, it would never enter the if condition.
Since, 1 > 2 is not true. 2 > 3 is not true, and so on. Hence the
correct way of checking it would be, to check the current array index
with the existing max value. i.e,
if(array[i-1] > max) { max = array[i-1] ;} This would keep replacing
the max value if a bigger number is encountered. And then check the
next number with the max.
else if(last_element > array[i-1]) //This else if detects greatest
{ //index of array in last index
max = last_element; //This statement is always eval
}//end if //uating true.
}//end for
Now this would again be a wrong statement. Consider the example array
5 4 3 2 1' .Here the last element is always smaller than
array[i-1]`, that means last element is always smaller than all
previous elements. So this condition would never be entered.
FINALLY, Correct code: declare a variable int max = 0 Such that, if
array[i]>max, then max value is replaced to that array's value. And
then the next array value is checked with the newly declared max.
int max =0;
for(int i=0; i<c; i++){
if(array[i] > max){
max=array[i];
}
}
Please see the C code below i dont understand how is it comparing -32000 to detect maximum value any number from 0 to 99 can be greater than -32000 . Similarly minimum value should be >= to zero , why set it to 32000. ???
/ MaxNumber.cpp : Defines the entry point for the console application.
//
/* Promotes user enter an integer untile it detects 0 */
/* Fills a array buffer , and then finds minimum and maximum within it */
#include "stdafx.h"
#define MAX 100
int array[MAX];
int count = -1 , minimum, maximum, num_entered, temp ;
int main(int argc, char* argv[])
{
puts("Enter integer values one per line ");
puts(" Enter 0 when finished ");
// do while to check the condition
//
do
{
scanf("%d", &temp);
array[++count] = temp;
} while ( count < (MAX-1) && temp != 0);
////////////////////////////////////////
num_entered = count;
//
/* Find maximum and minimum value*/
/* Set maximum to a very small value */
/* Set minimum to a very large value */
maximum = -32000;
minimum = 32000;
for ( count = 0; count <= num_entered && array[count] != 0; count++)
{
if ( array[count] > maximum )
maximum = array[count];
//
// Now minimum
if ( array[count] < minimum )
minimum = array[count];
}
//
// Printing the results
printf("\n Maximum value entered is %d \n", maximum );
//
printf("\n Minimum value entered is %d \n", minimum );
////
return 0;
}
It starts by assuming the biggest value is a very small number. It should be the smallest possible number, but they picked -32000. It stores this value in the variable maximum.
It then iterates over the values stored in the array. When it finds a value bigger than the value stored in maximum, it replace the value stored in maximum by the biggest value. It continues until all values in the array have been examine. In the end maximum contains the biggest value in the array, unless all values in the array are smaller than -32000. In this case this implementation will fail.
A better implementation would initialize maximum and minimum with the first value of the array and examine the remaining elements of the array.
It could also have initialized maximum with the smallest possible value for an int. You have to include limits.h and use INT_MIN.
maximum = INT_MIN;
minimum = INT_MAX;
Whenever writing an algorithm of the kind "find the largest number", you simply loop through all numbers in the data and store the largest one you have found so far. For example
for(int i=0; i<N; i++)
{
if(data[i] > largest)
{
largest = data[i];
}
}
In order to do the above, the variable largestwhere you store the largest one found, has to be properly initialized to the smallest possible value that the data can have.
The correct way to do that would have been to #include <limits.h> and then set
int largest = INT_MIN;
However, whoever wrote your code was too sloppy to do so. Instead they sloppily assumed that int is always 16 bits (which is not true), in which case the smallest possible value would be -32767. But because they were lazy/sloppy, they used the rounded value -32000 instead, don't ask me why.
This means that the code simply won't work correctly for values smaller than -32000 (or greater than 32000). Furthermore, the code is non-portable. The standard Windows/Linux/whatever machine uses 32 bit int.
Please don't look at that code you have as a reference for learning/how to write proper programs. It is very poorly written.
This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Closed 9 years ago.
I was wondering, how can I generate unique random numbers except from a specific one. For example, if I want to generate numbers in range 1 to 10 except from 3, the output should be something like this:
7 6 1 2 4 9 5 8 10
Shuffle the numbers 1 - 10 and remove 3.
It doesn't matter if you remove the 3 before or after shuffling.
Alternatively, shuffle the numbers 1 - 9 and relabel 3 as 10...
For shuffling without bias you can use for example the Fisher-Yates algorithm. http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Generate random number in the range 1..9 and add one if the number is greater than or equal to 3.
Generate a number. Check its value, if the number is 3 generate another one. If it isn't 3 then use it.
EDIT: Thinking before coffee is a terrible plan. If you want to get every number in the range in a random order then I agree with the others talking about shuffling lists. If however you want some random subset of the range I would store a list of forbidden values. Shuffling and only taking the first n numbers would also be suitable if the range isn't very large (e.g. not something like 0<x<INT_MAX).
Every time you generate a number check if the generated number is on the forbidden list and if it is, generate another number. Every time you generate a valid number you add it to the list to ensure generated numbers are unique. The list should also be initialised with your unwanted numbers (3 in the example given).
You may try like this:-
unsigned int
randomnumber(unsigned int min, unsigned int max)
{
double scaled = (double)rand()/RAND_MAX;
return (max - min +1)*scaled + min;
}
then later you can do this:-
x = randomnumber(1,10);
if (x==3)
{ x = x+1;}
or
if (x!=3)
{ printf("%d",x)}
This is my answer - returns random value in [min, max), except "except".
int myrand(int min, int max, int except) {
int rc;
do {
rc = min + rand() % (max - min);
} while(rc == except);
return rc;
}
This code will generate unique random numbers from minimum to maximum of a given range.
#include<stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int max_range, min_range, i = 0, rand_num;
srand((unsigned)time(NULL));
printf("Enter your maximum of range: ");
scanf("%d", &max_range);
printf("Enter your minimum of range: ");
scanf("%d", &min_range);
bool digit_seen[max_range + 1]; // VLAs For C99 only
for (int i = min_range; i <= max_range; i++)
digit_seen[i] = false;
for (;;)
{
rand_num = rand() % max_range + min_range;
if(rand_num !=3)
if(!digit_seen[rand_num])
{
printf("%d ", rand_num);
digit_seen[rand_num] = true;
i++;
}
if( i == (max_range - 1) )
exit(0);
}
return 0;
}