C Finding Maximum and Minimum value? [closed] - c

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.

Related

Array made with malloc function goes beyond desired size [duplicate]

This question already has an answer here:
Why the size of pointer to array is always 8 in C? [duplicate]
(1 answer)
Closed 3 years ago.
I'm making a program capable to use some statistics functions. For that, I used malloc for the array that the numbers of the sample to operate on, as I want it's size to be based on users' input. It's not the first time I do this, and it worked fine, but this time I can't set the size as needed and I can't find the flaw.
Below is the necessary code for the creation and printing of the array, skipping main() as it only runs the functions.
int *sample;
int MakeSample()
{
int sampleSize;
int valueN;
printf("Enter size of your sample: ");
scanf("%d", &sampleSize);
sample = malloc(sampleSize * sizeof(int));
for (int i = 1; i <= sampleSize; i++)
{
printf("Enter value #%d: ", i);
scanf("%d", &valueN);
sample[i - 1] = valueN;
}
}
int PrintSample()
{
for (int k = 1; k <= sizeof(sample); k++)
{
printf("Value #%d: %d\n", k, sample[k - 1]);
}
}
If I enter size 1 for the array, that should be the amount off values asked for and printed, instead I got this:
Value #1: 1
Value #2: 0
Value #3: 0
Value #4: 0
Value #5: 0
Value #6: 0
Value #7: 133057
Value #8: 0
sample is an int pointer; sizeof(sample) is always 8. You need to store the sampleSize variable somewhere and use that instead - there's no way for your program to know how big your array is otherwise, since it's not really an "array", it's a pointer to memory that happens to hold an array.

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

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

Compare a single integer against an array of integers in C? [closed]

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 6 years ago.
Improve this question
How does one compare a single integer to an array of ten integers to find if the single integer is contained within the array using C language? My apologies if original question was unclear, while swipe is equal to any number within the array I want to output PORTD=0b10000000. Thank you!
short a[10]={10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; //Array of accepted passwords.
short array[10];
int i;
for(i=0; i<10; i++){
array[i]=a[i];
}
srand(clock());
while(1){
int swipe=rand() % 20; /* Simulated code read from card swipe, in this
* instance we used a random number between
* 1 and 20.*/
for(i=0; i<10; i++){
if(swipe == array[i]) {
PORTD=0b10000000;
} else {
PORTD=0b00001000;
} //If swiped code evaluates as one of the approved codes then set PORTD RD7 as high.
}
char Master=PORTDbits.RD7;
This seems to have solved it...thanks for all of your help!
for(i=0; i<10; i++){
if(swipe == array[i]) {
PORTD=0b10000000;
break;
} else {
PORTD=0b00001000;
}
}
You need to test your swipe value against ALL ten values in your array of accepted passwords.
e.g. like below
for(i=0; i<10; i++)
if(swipe == array[i]) {
set a true flag (and maybe exit the for loop)
}
Depending on the flag, set the output
In addition to #kaylum's answer...
Because you are calling rand() in a loop, you need to call srand() first before entering the loop,
srand(clock());//for example
while(1){
LATD=0x00;
int swipe=rand() % 20;
...
If you do not, the random numbers you get will be the same sequence of values every time you execute.
Additionally, if i is not reinitialized before being used to compare, it is == 10. It needs to be reset before using as your array index...
Also, in your code, it appears you want to check the latest random number against the 10 accepted passwords. If that is correct, you must compare all 10 of them:
int main(void)
{
srand(clock());//for example
j = 0;
while(1)
{
int swipe=rand() % 20;
PORTD=0b00000000;
for(i=0;i<10;i++)
{
j++;
if(swipe == array[i])
{
PORTD=0b10000000;
break;
}
}
//to show ratio of legal to illegal passcodes...
printf("times through: %d Value of PORTD %d\n", j, PORTD);
}
}
if(swipe == a[i]). That invokes Undefined Behaviour as i is 10 and 10 is an out of bounds index. The valid indexes are from 0 to 9.
You are trying to simulate random card-reading actions & get both Pass/Fail at different instances. With swipe values between 1 to 20 and passwords only in the range 10, 19, you'd like to see if some instances fail. Is that correct?
If so, considering your rand() function returns only integer, set a breakpoint and probe for value of swipe. It seems to always has same value. Make rand() function better for wider statistical distribution. There are many sources to generate random integers like Linear Congruential Method etc.
Also that comparison should be looped for every value of array.

My C program outputs undesired array values [closed]

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 7 years ago.
Improve this question
I've been tasked to code a program that processes a simple 1D array to return its element values, but the compiler has been behaving strangely; outputting more values than I have array elements.. It's also not being fully compliant with one of my statements (one that prints a new line character every 8 elements) and not assigning the largest value to my variable. I think that the other two problems will go away once the first problem is fixed, however.
Here is my brief:
Design, code and test a program that:
Fills a 20 element array (marks) with random numbers between 0 and 100.
Prints the numbers out 8 to a line
Prints out the biggest number, the smallest number and the average of the numbers
And here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
srand(time(NULL));
int marks[20];
int i = 0;
int sum = 0;
int min;
int max;
for(i;i<=sizeof(marks);i ++){
marks[i] = rand() % 100;
sum += marks[i];
if(i % 8 == 0){
printf("\n");
}
printf("%d ", marks[i]);
if(marks[i]>max){
max = marks[i];
}
else if(marks[i]<min){
min = marks[i];
}
}
printf("\n\nThe minimum value is: %d", min);
printf("\nThe maximum value is: %d", max);
printf("\n\nThe average value is: %d", sum / sizeof(marks));
return 0;
}
Please can someone help me get the correct output?
sizeof() function returns the byte length of the array, so this code "thinks" your array is 20 * whatever byte size ints are on your machine. You will want to just use i < 20 in the loop or go
for (i;i<sizeof(marks)/sizeof(int); i ++) { ...
Note that you probably do not want the <= operator in the for loop, since arrays are 0 indexed, thus marks[20] is actually one beyond the array.
There are two problem I can see that will invoke undefined behavior in your code.
By saying for(i;i<=sizeof(marks);i ++), you're out of bounds.
int min; int max; are not initialized and you're attempting to use it.
to solve this.
Change the for loop condition to for(i; i< 20; i++). Better to use a preprocessor construct like #define SIZ 20 and then make use of it accross your code to make it consistent and robust.
Initialize your local variables. max should be INT_MIN, and min can be INT_MAX. (see limits.h for reference).
To clarify more on point 2, max and min are automatic local variables, and in case not initialized explicitly, it contains indeterminate values.
C11, chapter §6.7.9,
If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate.
and then, directly from the Aneex J, §J.2, Undefined behaviour,
The value of an object with automatic storage duration is used while it is
indeterminate.
if(marks[i]>max){
max = marks[i];
}
else if(marks[i]<min){
min = marks[i];
}
min and max are not initialized here. Make sure to set your compiler warnings at the highest level, so you get a warning message when you forget to initialize variables.
for(i;i<=sizeof(marks);i ++){
This doesn't make sense. Replace sizeof(marks) with the number of times you want to loop, and use < instead of <=.
For example:
const int num_marks = 20; // or use #define
int marks[num_marks];
for(i = 0; i < num_marks; i++) {}

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

Resources