I tried to run this but it keeps give me zero value. What is wrong in this code?
#include<stdio.h>
main(){
int i,min,max,arr[3]={10,20,40};
int *ptr_arr;
ptr_arr=&arr[3];
for(i=0;i<3;i++){
if(max>*ptr_arr)
max=*ptr_arr;
if(min>*ptr_arr)
min=*ptr_arr;
}
printf("The Maximum Number Is %d\n ",max);
printf("The Minimum Number Is %d ",min);
}
ptr_arr=&arr[3]; // points to index which is beyond no. of index of array
As declaration of arr is arr[3]={10,20,40};so it's valid indexes are 0,1 and 2 .So there is no index 3(array indexing starts with 0).
Also min and max what value does they have ? Uninitialized , so how can your code give correct output.
Make the following changes -
int min=arr[0],max=0;
...
ptr_arr=arr; // points to address of array's first element
And in for loop see condition and increment pointer-
if(max>*ptr_arr) // change condition to max<=*ptr_arr
...
ptr_arr++;
See worning example here-https://ideone.com/r3nv8R
The code misses to initialise min and max to meaningful values.
Do
int min = INT_MAX;
int max = -INT_MAX;
to have the macro above available #include <limits.h>.
ptr_arr gets initialised wrongly to point beyond the array.
Do
int * ptr_arr = arr; /* Here the array "decays" to address of its 1st element. */
or
int * ptr_arr = &arr[0]; /* Explicitly use the address of the array 1st element. */
The code misses to increase ptr_arr to successively access all array's element while looping.
Add
++ptr_arr;
as last statement to the loop.
Also read your code closely to find a nasty typo in comparing.
main() should at least read int main(void).
Just few notes on your code:
you should give min and max an initial value(a value from the array), why? because the initial garbage value might be beyond your array values(say 9999 for example) which yields a wrong result, because your array doesn't have such a value.
Also, im not sure why you need ptr_arr ?
Here is a modified version of your code:
#include<stdio.h>
int main(){
int i,min,max,arr[3]={10,20,40};
max = arr[0]; //initialize 'max' to be the first element of the array
min = arr[0]; //initialize 'min' to be the first element of the array
for(i=0;i<3;i++){
if(arr[i] >= max)
max = arr[i];
if(arr[i] <= min)
min = arr[i];
}
printf("The Maximum Number Is %d\n ",max);
printf("The Minimum Number Is %d ",min);
return 0;
}
Notice also in the if statement i added <= and >=.
Tested and working:
#include <stdio.h>
int main(void) {
int i = 0,min ,max,arr[3]={20,40,10};
int *ptr_arr;
ptr_arr=&arr[0];
min = max = arr[0];
for(i=0;i<3;i++){
if(max < ptr_arr[i]) {
max=ptr_arr[i];
}
if(min>ptr_arr[i]){
min=ptr_arr[i];
}
}
printf("The Maximum Number Is %d\n ",max);
printf("The Minimum Number Is %d ",min);
}
OUTPUT:
The Maximum Number Is 40
The Minimum Number Is 10
Related
I just started learning how to code in C.
I tried creating a program that finds the maximum of three integers using arrays, but I don't really understand why does it work.
Can anybody more experienced help explain to me; why do I need to let max = 0 in order for the program to function?
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int size, max;
int arr[3];
for (int i = 0; i < 3; i++) {
printf("Please enter your integer:\n");
scanf("%d", &arr[i]);
}
max = 0;
for (int i = 0; arr[i] >= max; i++) {
max = arr[i];
}
printf("This is the max number: %d", max);
return 0;
}
Thanks for the help everyone.
The proper loop would be:
int max= INT_MIN;
for (int i = 0; i<3; i++)
if (arr[i]> max) max= arr[i];
First of all, your code won't find the right answer in all test cases, and that's because of how you wrote your second for loop. For example if you have an input like 3, 2, 4, after the first for iteration you'll have max = 3 and the for loop will stop because the next element (2) is less than the current max (3). But the max value of this array is 4, not 3. You should change the second for loop like this:
for (int i=0;i<3;i++) {
(if array[i]>max) max = array[i];
}
Also, take note that you can initialize max to 0 only if you don't have negative numbers in the array, otherwise you might have incorrect results. So, if you can't make assumptions about your input values I would suggest you to simply initialize max with the first element of the array and do a loop starting from the second one to the end (for(i=1;i<3;i++).
A variable must be initialized before it can be used. The first use of max is:
for (int i = 0; arr[i] >= max; i++) {
... ^^^^^^^^^^^^^
}
The boundary condition in a for loop (i.e. arr[i] >= max) is evaluated before every iteration of the loop. A value for max is therefore required before the body of the loop is ever executed.
Thus, you must assign some value to max outside the loop, and, as you discovered, max = 0 is a suitable initial value for some inputs.
However as mentioned by Paul in the comments, this is not a suitable boundary condition for the result you’re trying to achieve. You should instead iterate over the entire array, setting the max value only if each array element is greater than the existing max value:
max = 0;
for (int i = 0; i < 3; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
If it's just for three:
#define MAX_SIMPLE(a, b) (((a) > (b)) ?(a) :(b))
int a[3] = {3, 2, 1};
printf("max is: %d\n", MAX_SIMPLE(a[0], MAX_SIMPLE(a[1], a[2])));
May i know why is int count, biggest = -12000;? Why must it be -12000 and I do not understand this statement biggest = -12000
If I put biggest = 10000, it can still compile. Appreciate your advise as I am currently learning c programming. Can you please understand as clearly as possible? Thanks in advance!
#include <stdio.h>
#define MAX 10
int array[MAX], count;
int largest(int x[], int y);
int main()
{
/* Input MAX values from the keyboard. */
for (count = 0; count < MAX; count++)
{
printf("\nEnter an integer value:\n ");
scanf_s("&d", &array[count]);
}
/* Call the function and display the return value. */
printf("\n\nLargest value = %d\n", largest(array, MAX));
return 0;
}
/* Function largest() returns the largest value in an integer array */
int largest(int x[], int y)
{
int count, biggest = -12000;
for (count = 0; count < y; count++)
{
if (x[count] > biggest)
biggest = x[count];
}
getchar();
return biggest;
}
If you want to find the largest number in an array you compare all elements against the currently 'biggest' value. Whenever you find a value that's larger you put it in biggest.
To make sure that you find the proper value you must initialize biggest to a sensible value.
Your code initializes biggest to -12000, and therefore it will fail if all elements in the array have values lower than -12000 (unless you know something about the values in the array, but then that should be mentioned in a comment, to explain the unusual initialization value).
Sure it will compile, but that does not mean it will work correctly.
You could initialize biggest to the lowest integer value possible (INT_MIN),
int largest(int x[], int y)
{
int count, biggest = INT_MIN; // lowest integer value possible
for (count = 0; count < y; count++)
{
but a smart trick is to initialize it to the first value in your array.
int largest(int x[], int y)
{
int count, biggest = x[0]; // first value in your array
for (count = 1; count < y; count++) // starting with 2nd element
{
You can work this all out on a piece of paper with e.g. 3 array values, or step through your debugger and see what values the respective variables get.
Instead of assigning the value in starting to biggest, you can compare two elements of the array and after comparing it store maximum value in biggest and after it swap the numbers if greater it would be good approach.
if you use like:
if(x[count]>x[count+1])
biggest=x[count];
x[count]=x[count+1];
x[count+1]=biggest;
code above line in loop.
What you tried assigned a very high value to biggest. It's not a worthy idea.
I have the following code:
void generate_random_array(int8_t array[], int array_size){
srand(time(NULL));
for(int i = 0; i < array_size + 1; i++){
array[i] = rand() % 21 + (-10);
printf("%d, %d\n", array[i], i);
}
}
int main(){
int8_t some_array[100];
generate_random_array(some_array, 100);
for(int i = 0; i < 101; i++){
printf("%d %d\n", some_array[i], i);
}
return 0;
}
The program generates random elements of a given array in the range from -10 to 10 and then it displays them. The problem is that the last element of an array changes to 100 when I print elements the second time. I would like to know why.
Indexing of an array starts at zero.
int array[3];// an int array with 3 elements
array[0]; //first element
array[1]; //second element
array[2]; //third element
array[3]; //undefined because it is beyond the end of the array
In your function generate_random_array you are iterating the i upto array_size + 1. And you have declared an array of size 100; int8_t some_array[100]; OS will reserve the 100*sizeof(int8_t) bytes memory for you.
Indexes of your array would be lying in range [0,100) ie. excluding the 100th location.
Now, what you are doing is that you modifying the some_array[100] which you have not claimed in your declaration. Its being possible because C doesn't do any out-of-bound access checking.
But key point to note is that you are trying to modifying/reading the unclaimed memory. So this is undetermined behavior. It might be possible that you might get different value other than 100, sometimes.
But all story short, this behavior is undetermined because you are accessing the out-of-bound index of array.
I have been attempting to code for a program that stores input into an array and then allows me to print it out. It also lets me know which number is the largest. What I am trying to figure out is how can I get my program to tell me the amount of times (occurrences) the largest number in array is input. Here is my code so far. As of now, this code outputs the numbers I enter to the array, the largest element in the array, and the occurrence of every number I input( The occurrences of the numbers are incorrect). In all the the amount of occurrences for every number turns out to be 0. Which is obviously incorrect. Again, I need my program to display the largest number (which it does) and the occurrences of ONLY the largest number. All advice, tips, or thoughts are welcome. Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
int main()
{
int arrayNum[15];
int a;
int max=0;
int location;
for( a=0; a < 15; a++)
{
printf("Enter element %d:", a);
scanf("%d",&arrayNum[a]);
}
for(a=0; a < 15; a++)
{
printf("%d\n", arrayNum[a]);
}
for (a = 1; a < 15; a++)
{
if (arrayNum[a] > max)
{
max = arrayNum[a];
location = a+1;
}
}
printf("Max element in the array in the location %d and its value %d\n", location, max);
for(a=0; a<15; a++)
{
if(arrayNum[a+1] == arrayNum[a])
continue;
else
printf("Number %d: %d occurences\n", arrayNum[a]);
}
return 0;
}
I spot some problems in your code. First, the third for loop starts at 1, but it does not update the max as the value of arrayNum[0].
Then, for the problem at hand, I would have two variables:
int max; // The maximum value
int max_count; // The count of the maximum value
Then, the logic to find the greatest, and the count, is the following:
For each element, compare it with the maximum seen. If it is equal, increment max_count. If it is bigger, update max with the value, and set the max_count to 1. If it is smaller, ignore it. Something like:
max = arrayNum[0];
max_count = 1;
for (int a = 1; a < 15; ++a)
{
if (arrayNum[a] == max)
max_count++;
else if (arrayNum[a] > max)
{
max_count = 1;
max = arrayNum[a];
}
}
All you need to do is introduce a new variable to keep track of the number of occurrences of max. When a new value of max is found, set that count to zero. When a subsequent value is found equal to the max, increment the counter.
Incidentally, your code doesn't properly find the maximum in its current form. Try one test case where your array elements are all negative. Try another test case in which all the values are positive, and the first value entered (arrayNum[0]) is the maximum. You will find, in both cases, that your function will not actually find the maximum.
Just before you begin the below loop max is still 0 make
max = a[0];
for (a = 1; a < 15; a++)
{
if (arrayNum[a] > max)
{
max = arrayNum[a];
location = a+1;
}
}
Later
int n=0;
for(i=0;i<15;i++)
{
if(max == a[i])
n++;
}
printf("Number of times max appears in the array is %d\n",n);
Replace last for loop with below code
NoOfOccurances = 0;
for(a=0; a<15; a++)
{
if(max == arrayNum[a])
{
NoOfOccurances++;
}
}
printf("Number %d: %d occurences\n", max,NoOfOccurances);
For your third for-loop, the one where you find out the largest number in your array, I would suggest to set max to arrayNum[0], that way it will work even with negative numbers.
Then, to know how many occurrence of the highest number there is, you need a count variable that you increment (count++) each time a number of the array is equal to max. To do that you need another for-loop.
Good luck.
You can do what you want in just one loop iteration:
int count = 1;
int position = 0;
int max = arrayNum[0];
int N = 15;
int p;
for (p = 1; p < N; ++p)
{
if (arrayNum[p] > max) // Find a bigger number
{
max = arrayNum[p];
pos = p;
count = 1;
}
else if ( arrayNum[p] == max) // Another occurrences of the same number
count++;
}
A simple solution with time complexity of O(n)
int maxoccurence(int a[],int ar_size)
{
int max=a[0],count=0,i;
for(i=0;i<ar_size;i++)
{
if(a[i]==max)//counting the occurrence of maximum element
count++;
if(a[i]>max)//finding maximum number
{
max=a[i];
count=1;
}
}
printf("Maximum element in the array is %d\n",max);
return count;
}
I wrote a program to find the largest number in an array. The problem is that every time the find_largest function is called recursively, the largest variable seems to be filled with garbage from somewhere else in memory. I've stepped through it with a debugger and it seems to be working fine until the recursive call. The pointers for the array and the update to largest, if applicable, show expected values.
/*This program will find the largest integer in an array. It was written to practice
using recursion.*/
#include <stdio.h>
void find_largest(int *a, int n);
int main() {
int a[] = {10, 27, 101, -8, 16, 93};
int n = 6, i = 0;
printf("Current array: ");
while(i < n) {//print array
printf("%d ", a[i]);
i++;
}
find_largest(a, n);
return 0;
}//end main
//This function will start at the last element, and then step through the array
//in reverse order using pointers.
void find_largest(int *a, int n) { //formulate the size-n problem.
int largest = 0;
if(n == 0) { //find the stopping condition and the corresponding return
printf("\nThe largest number is: %d \n", largest);
}
else { //formulate the size-m problem.
n--; //decrement so that the proper number is added to pointer reference
if(largest <= *(a + n)) //check if element is larger
largest = *(a + n); //if larger, assign to largest
find_largest(a, n); //recursive call
}
}
The program returns zero as the largest integer. Any ideas?
largest isn't shared by all of your recursive calls, each gets its own copy. That means in the base case, you execute this code:
int largest = 0;
if (n == 0) {
printf("\nThe largest number is: %d \n", largest);
}
Where largest will always be 0.
You can make largest static and it will work, though it's a bit of a strange way to go about it. I'd prefer to do something like this:
int find_largest(int *a, int n)
{
int subproblem;
// base case - single element array, just return that element
if (n == 1)
{
return *a;
}
// recursion - find the largest number in the rest of the array (increase
// array pointer by one, decrease length by one)
subproblem = find_largest(a + 1, n - 1);
// if the current element is greater than the result of the subproblem,
// the current element is the largest we've found so far - return it.
if (*a > subproblem)
return *a;
// otherwise, return the result of the subproblem
else
return subproblem;
}
largest is initialized to 0 in each separate function call, here's a quick fix:
int find_largest(int *a, int n) { //formulate the size-n problem.
static int largest = 0;
if(!n) { //find the stopping condition and the corresponding return
int answer = largest;
largest = 0;
return answer;
}
else { //formulate the size-m problem.
n--; //decrement so that the proper number is added to pointer reference
if(largest <= *(a + n)) //check if element is larger
largest = *(a + n); //if larger, assign to largest
find_largest(a, n); //recursive call
}
}
The static attribute tells the compiler that you only want to initialize the variable once, and afterwards it should retain it's data. This will fix your problem because after each recursive call, largest wont be reset to zero. Instead, it will contain the value of the last call (in this case, the calling function).
At the end of the function, you should reset largest to 0 so that in the next call, it doesn't still contain the value of the call previous. This is also why a temporary variable is made - so that it can return its value before it's set to 0.
Each time you call find_largest(), you're creating a local variable int largest and assigning it the value of zero. So when n finally reaches zero, it doesn't really care what the past 5 recursive calls have done, it simply returns the zero to which you just set largest. Either make largest global, or pass it as a parameter to the function (probably better practice).
make the int largest=0; into static int largest=0; it may help.By adding static the variable largest will be initialized only once throughout your recursion.