else if statement prevents program from detecting greatest index [closed] - c

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];
}
}

Related

program not outputting the correct smallest most frequently appeared number

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.

C++ Array doesn't take negative numbers into account

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.

How do I fix this issue with the if statements inside this for loop?

#define MAX 100000
bool hasPair(int array[], int start, int end, int size, int number)
{
int i, temp;
bool binMap[MAX] = {0}; /*initialize hash map as 0*/
for(i = 0; i < size; i++)
{
temp = number - array[i];
if((temp>=0 && binMap[temp] == 1) && (temp != array[i]) && (array[i]>=start && array[i]<=end))
{
printf("The array contains at least one pair which sums up to %d.\n",number); // problem here
return true;
}
binMap[array[i]] = 1;
if(binMap[temp] == 0 && binMap[array[i]] == 0) //and here
{
printf("The array does not contain any pair which sums up to %d.",number);
return false;
}
}
}
I need to write a function which gets an array,its size,the range of its elements(start and end) and a random number as input and the output must be a statement whether there is a pair of different numbers inside the array that their sum equals that random number that we entered as input.I have a problem with the if statements,
because for example:-
an array of 10 elements and the range of these elements is 0-10 the random number is 18 and the arrays elements are:- 0,5,5,2,9,8,2,7,8,2.There wont be any combination of sum between two different numbers of this array which gives us 18
and it works fine in the functions I wrote.
The problem is that for example if we took the same array and this time we substituted 18 for 10 then there will be two different numbers that their sum will be equal to 10 but in my function if I enter this array with random number as 10 then it wont work and I think there is a problem with my If statement so if you can see it whats the problem here?
Your mistake is in the 2nd if condition. It's redundant. You are always invoking this case after the first iteration, and you don't go on for the next iterations.
You should remove the 2nd if condition entirely, and instead add AFTER the for loop a simple statement: return false;.
The idea is you should let the algorithm keep going to the next iterations, even if one was unseccesful. You only return false when you are done with the loop without finding matching elements during it - and only now you can tell no such elements exist.

How to correctly compare and print out matching elements in this array in C?

I have this simple problem to which I am trying to write a solution, in C.
If an array arr contains n elements, then write a program to check
if arr[0] = arr[n-1], arr[1] = arr[n-2] and so on.
And my code looks like this-
#include<stdio.h>
int main()
{
int arr[10],i=0,j;
int k=0;
printf("\n Enter 10 positive integers: \n");
for(k=0;k<=9;k++)
scanf("%d",&arr[k]);
while(i<=9)
{
for(j=9;j>=0;j--)
{
if(arr[i]==arr[j])
{
printf("\n The array element %d is equal to array element %d\n", arr[i],arr[j]);
}
i++;
continue;
}
}
return 0;
}
On entering this input-
Enter 10 positive integers:
10
20
30
40
50
60
40
80
20
90
The output I get is-
The array element 20 is equal to array element 20
The array element 40 is equal to array element 40
The array element 40 is equal to array element 40
The array element 20 is equal to array element 20
Now, there are two problems with this code-
As you can see, the program prints out matching array elements twice. This is because, the way I've structured the program, once the variable i loops through the array from the first to last element, and then j loops through from the last to first element. So each prints out the matching array element once, leading to two sets of values.
My second question is- In my code, I've hard-coded the length of the array in the for loops(0 to 9 for an array of 10 elements). What change can be done so that the length of the array, as entered by the user, can directly be used in the for loops?
I've read that, in C, array dimensions(when declaring) cannot be a variable. So, a declaration like this(which was my first thought) wouldn't work-
int n; // n is no. of elements entered by the user
int arr[n];
I'm a newbie to programming, so my apologies if the question sounds/is too simple, low-quality.
Thank You.
1)You can traverse the array for half times for getting the prints only once. Instead of for(j=9;j>=0;j--) you can use for(j=9;j>=9/2;j--).
2)
int n;
int arr[n].
Recent Compilers support this statement. If you don't like to use this, you can go for dynamic memory allocation for the array.
My second question is- In my code, I've hard-coded the length of the array in the for loops(0 to 9 for an array of 10 elements). What change can be done so that the length of the array, as entered by the user, can directly be used in the for loops?
Use dynamic memory allocation. Use malloc().
So code will be
{
int num_elements;
int* arr;
printf("Enter number of elements\n");
scanf("%d", &num_elements);
arr = (int *) malloc(num_elements * sizeof(int)); // Use this 'arr' for holding input data from user
// Your remaining code comes here
free(arr); // Free the pointer in the end of program
}
the variable length creation works for me:
#include<stdio.h>
int main(){
int a, i;
scanf("%i", &a);
int blah[a];
for (i = 0; i < a; i++){
printf("/n%i", blah[a]);
}
}
The other way would be to create the maximum length array and than simply use first n elements.
As the previous answer states it is up to you to make sure you are checking each element only once therefore stopping at the element n/2. It is probably important that n/2 is rounded to the closest smaller integer, so at first glance odd numbers of arguments may be differently handled. But as it is omitting only the middle element it is identical to itself.
For your first query
for(i=0;i<n/2;i++)
{
if(a[i]==a[n-(i+1)])
{
printf("\n The array element %d is equal to array element %d\n",a[i],a[n-(i+1)]);
}
}
For your second query you can use condition i<(n/2) (which runs the loop (n/2)-1 times) For your case where n = 10 it will run from 0 to 4.
If you want to loop from 0 to 9 you can use
for(i=0;i<n;i++)
For making array of n elements where n is a variable either make an array of elements that is always greater than n or do it by making a dynamic array.
http://www.cs.swarthmore.edu/~newhall/unixhelp/C_arrays.html
corrected:
#include<stdio.h>
int main()
{
int i=0, size; // size of array
int k=0; // counter
printf("enter size of array\n");
scanf("%d", &size); // ask user for desired size
int *arr = malloc(size * sizeof(int)); // allocate memory for array
printf("\n Enter 10 positive integers: \n"); // fill your array of size size
for(k=0;k<size;k++)
scanf("%d",&arr[k]);
k = 0; // reset this counter
for(i=0; i<size/2; i++) // check only for half of it
{
if(arr[i] == arr[size-i-1]) // try it with paper and pincil
{
printf("match arr[%d]=arr[%d]=%d\n", i,size-i-1, arr[i]);
k++;
}
}
if(k==0) printf("No matching");
return 0;
}

C Finding Maximum and Minimum value? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In Case of Finding Maximum and minimum Value in Array. We intialize max =0 or max=temp[0];
But in case of Minimum value we doesn't require to initialize min =0 or min=temp[0]... Why?
max = temp[0] acts as reference point. You start comparing each element with this and if any element is greater than this, max value will be updated to that one. similarly min = temp[0] is also valid, but now algorithm will be changed and you need to compare each element if anyone is smaller than this if yes then min will be updated to that.
You always need to initialise variables in C before accessing them; it's undefined behaviour not to. The best thing to do, is, having checked the array length is not zero, is to initialise min / max to the zeroth element. Then loop from the first element.
First, you shouldn't initialize max with 0 in any case (for example, when finding maximum of array which contains all negative values if you initialize max with 0, result will always be 0).
Since for finding maximum (and minimum) you need to compare variable max (or min) with some other value, you need to initialize to temp[0] in any case to avoid comparing array elements with uninitialized variable.
I found the part of your code in another comment:
#include<stdio.h>
int main() {
int arr[3];
int i,max,min; max=min=0;
printf("Enter the value in Array \n");
for(i=1;i<=3;i++) {
scanf("%d",&arr[i]);
}
printf("\n Value of array \n");
for(i=1;i<=3;i++) { printf("%d \n",arr[i]); }
printf("\n Finding Maximum and minimum value \n");
for(i=1;i<=3;i++) {
if(arr[i]>max) max=arr[i];
if(arr[i]<min) min=arr[i];
}
printf("Max = %d \n Min = %d \n ",max,min);
getch();
}
There are few things that doesn't work:
for(i=1;i<=3;i++)
In C, indexing starts from 0, so the valid array elements are arr[0], arr[1] and arr[2], so that for loop should be
for(i = 0; i < 3; i++)
Ok, now imagine that you have in your array elements 10, 5 and 7.
You're setting min value to 0:
max=min=0;
And now you are iterating over this loop:
for(i=0;i<3;i++) {
//...
if(arr[i]<min) min=arr[i];
}
Is 10 < 0? No, it's not.
Is 5 < 0? No, it's not.
Is 7 < 0? No, it's not.
So you see, the min will never change.
To avoid this, just set it to the first element after reading the array:
for(i= 0;i < 3;i++) {
scanf("%d",&arr[i]);
}
min = max = arr[0];
Now, let's repeat our loop:
for(i=0;i<3;i++) {
//...
if(arr[i]<min) min=arr[i];
}
Is 10 < 10? No, it's not.
Is 5 < 10? Yes, it is! Set the min to the 5
Is 7 < 5? No, it's not.
Now the min is 5.
Same issue you have in your existing code with max. Imagine you enter -4, -55 and -20 for elements - max would always stay 0.

Resources