Max and Min value in array - c

My program is giving me two minimum values and no maximum values. My program is supposed to print max value if opcode is 1 and min value if opcode is 0. Help please
#include <stdio.h>
int minmax(int array[], int array_size, int opcode);
int main(void)
{
int array[]= {99,4,95,2,98}; //array size
int array_size = 5;
int i;
int opcode;
array_size = 5;
for (i = 0; i < array_size; i++)
{
printf("array[%d] = %d\n", i , array[i]);
}
printf("Enter an opcode 0 or 1: ");
scanf("%d", &opcode);
minmax(array, array_size, opcode);
}
int minmax(int array[], int array_size, int opcode)
{
int i;
int max = array[0];
int min = array[0];
for (i = 0; i < array_size; i++)
{
if (opcode == 1 && array[i] > max)
{
max = array[i];
printf("The max value is: %d\n", max);
}
else if (opcode == 0 && array[i] < min)
{
min = array[i];
printf("The min value is: %d\n", min);
}
}
return 0;
}

It does not print the maximum because the first element itself is the maximum.
That is,
if (opcode == 1 && array[i] > max)
{
max = array[i];
printf("The max value is: %d\n", max);
}
never executes in this code.
The remedy to be output the minimum or maximum at the end of the minmax() function.
Your code should look like:
int minmax(int array[], int array_size, int opcode)
{
int i;
int max = array[0];
int min = array[0];
for (i = 0; i < array_size; i++)
{
if (opcode == 1 && array[i] > max)
{
max = array[i];
printf("The max value is: %d\n", max);
}
else if (opcode == 0 && array[i] < min)
{
min = array[i];
printf("The min value is: %d\n", min);
}
}
//The below code prints the final max / min (as determined by opcode)
if (opcode == 1) printf("The final maximum is %d\n",max);
else printf("The final minimum is %d\n",min);
return 0;
}

Related

I want to get the sum of digits of minimum element in the array and check if the sum is even or odd in c

I have written this code-
#include<stdio.h>
int getSum(int);
int getDigitSum(int *arr, int len)
{
int result;
int min;
for (int i = 0, min = arr[0]; i<len; i++)
{
if (arr[i]<min) {
min = arr[i];
printf("min=%d\n", min);
}
}
printf("minimum=%d\n", min);
result = getSum(min);
if (result % 2 == 0)
return 1;
else
return 0;
}
int getSum(int num)
{
int rem, sum = 0;
while (num)
{
rem = num % 10;
sum += rem;
num /= 10;
}
return sum;
}
void main() {
int arr[5] = { 211,612,111,129,156 };
for (int i = 0; i<5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
int i = getDigitSum(arr, 5);
if (i == 1)
printf("Even");
else
printf("Odd");
}
But the min value in the getDigitSum() is getting changed outside for loop even after declaring it before the loop starts.
Here is the output-
211 612 111 129 156
min=111
minimum=-2
Even
Please tell me why the value is changing like this?
The problem is in for(int i = 0, min = arr[0]; ...) this statement is interpreted as a declaration and initialization of a min value inside the for-block when the for ends, the new min variable is removed too.
Try to initialize the variable with the declaration
//...
int min = arr[0];
for(int i=0;i<len;i++)
//...

Generate random numbers in array and count the average, max, min, sum

This code is supposed to generate 30 random numbers, 0-100, and print the average, max value, and the min value. But it has logical errors and I cant help but think I've made a stupid mistake.
****code is supposed to generate 30 numbers from 0-100, and display mean, max, and min****
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 30
int generateRandom(void);
int main(void)
{
int points[SIZE], i, sum, max, min, num;
double average;
srand(time(NULL)); /*Seed random number generator*/
num = generateRandom(); /*Genrate the random numbers*/
printf("num = %d\n", num); /*Print the random numbers*/
sum = 0;
for ( i = 0; i < SIZE; i++) /*Find the average*/
{
sum += points[i];
average = sum / SIZE;
}
printf("Average = %f", average); /*Print the average*/
max = points[0]; /*initialize the max to 0*/
for ( i = 0; i < SIZE; i++) /*find the min*/
{
if (points[i] > max)
{
max = points[i];
}
}
printf("Maximum = %d\n", max); /*print the maximum number*/
min = points[0]; /*initialize the min*/
for ( i = 0; i < SIZE; i++) /*Find the min*/
{
if (points[i] < min)
{
min = points[i];
}
}
printf("Minimum = %d\n", min); /*Print the minimum number*/
return 0;
}
int generateRandom(void)
{
int random;
random = rand() % 101;
return random;
}
You generate just one random number, which you store in num. Then your code behaves as if it had 30 random numbers stored in points. But it never makes this happen.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 30
int generateRandom(void);
int main(void)
{
int points[SIZE],i,sum,max,min,num;
double average;
srand(time(NULL));
for(i = 0; i < SIZE; i++){
points[i] = generateRandom();
}
sum = 0;
for(i = 0; i < SIZE; i++)
{
sum += points[i];
}
average = (sum * 1.0) / SIZE; /*you need double here*/
printf("Average = %f\n",average);
max = points[0];
for(i = 1; i < SIZE; i++)
{
if(points[i] > max)
{
max = points[i];
}
}
printf("Maximum = %d\n",max);
min = points[0];
for(i = 1; i < SIZE; i++)
{
if(points[i] < min)
{
min = points[i];
}
}
printf("Minimum = %d\n",min);
return 0;
}
int generateRandom(void)
{
int random;
random = rand() % 101;
return random;
}

Swapping largest and smallest numbers in C

I want to write a program that reads 10 int values from the user and swaps the largest and smallest numbers on the first and second values, then the rest of the numbers should be in the order.
Please check the code and help me what the wrong is.
For instance:
1
9
4
5
6
7
8
2
4
5
New order should be 9 1 4 5 6 7 8 2 4 5
#include <stdio.h>
int main() {
int a[10],i,min,max=0,pos=0;
printf("Please enter 10 int values :\n");
do{
scanf("%d", &a[pos++]);
} while (pos<10);
for (i=0; i<10;i++) {
printf("%i\n",a[i]);
if (max<a[i])
{
max=a[i];
}
if (min>a[i])
{
min=a[i];
}
for (i=0;i<10;i++) {
if (a[i]==max)
a[i]=max;
if (a[i] == min) a[i] = min;
}
printf("The new order is : %d %d %d ", max, min, ...);
return 0;
}
EDIT:
It is the new form
#include <stdio.h>
int main() {
int a[10],i,pos,temp,min = 0,max = 0;
printf("Please enter 10 int values :\n");
do {
scanf("%d", &a[pos++]);
} while (pos < 10);
for ( =1; i<10;i++) {
if (a[i]>a[max])
{
max=i;
}
if (a[i]<a[min])
{
min=i;
}
}
temp=a[max];
a[max]=a[min];
a[min]=temp;
printf("%d %d",a[max],a[min]);
for (i=0;i<10;i++){
if ((i != min) && (i != max)) {
printf("%d ", a[i]);
}
}
printf("\n");
return 0;
}
As others have noted, your code does not properly identify the maximum and minimum values in the array because you are writing min and max back into the array instead of the other way around.
Since you want to swap these values, what you actually want are the indices of the min and max values of the array, and swap those.
It is best to break this code into functions instead of having everything in main. Here is a solution that will do what you want:
#include <stdio.h>
int indexofmax(int *data, int len)
{
int max = 0;
int i;
for(i = 0; i < len; i++)
{
if(data[i]>data[max]) max = i;
}
return max;
}
int indexofmin(int *data, int len)
{
int min = 0;
int i;
for(i = 0; i < len; i++)
{
if(data[i]<data[min]) min = i;
}
return min;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
// user enters in 10 ints...
int max = indexofmax(a, 10);
int min = indexofmin(a, 10);
int i;
swap(&a[min], &a[max]);
for(i = 0; i < 10; i++)
{
printf("%d ", a[i]);
}
return 0;
}
This initialization min=0,max=0 is not right.
Instead have min = INT_MAX and max = INT_MIN.
By setting min=0, you would never get the lowest number in the array if it is greater than 0.
Similarly by setting max=0, you would never get the greatest number in the array if it is lower than 0.
You are gaining nothing by this code:
for(i=0;i<10;i++)
{ if(a[i]==max) a[i]=max;
if(a[i]==min) a[i]=min; }
It is evident that this loop
for(i=0;i<10;i++)
{ if(a[i]==max) a[i]=max;
if(a[i]==min) a[i]=min; }
does not make sense.
Moreover variable min is not initialized while variable max is initialized incorrectly.
int a[10],i,min,max=0,pos=0;
For example the array can contain all negative elements. In this case you will get incorrect value of the maximum equal to 0.
And I do not see where the elements are moved to the right to place the maximum and the minimum to the first two positions of the array.
If I have understood correctly then what you need is something like the following. To move the elements you could use standard function memmove declared in header <string.h>. However it seems you are learning loops.
#include <stdio.h>
#define N 10
int main( void )
{
int a[N] = { 4, 5, 9, 6, 7, 1, 8, 2, 4, 5 };
for (size_t i = 0; i < N; i++) printf("%d ", a[i]);
printf("\n");
size_t min = 0;
size_t max = 0;
for (size_t i = 1; i < N; i++)
{
if (a[max] < a[i])
{
max = i;
}
else if (a[i] < a[min])
{
min = i;
}
}
if (max != min)
{
int min_value = a[min];
int max_value = a[max];
size_t j = N;
for (size_t i = N; i != 0; --i)
{
if (i - 1 != min && i - 1 != max)
{
if (i != j)
{
a[j - 1] = a[i - 1];
}
--j;
}
}
a[--j] = min_value;
a[--j] = max_value;
}
for (size_t i = 0; i < N; i++) printf("%d ", a[i]);
printf("\n");
}
The program output is
4 5 9 6 7 1 8 2 4 5
9 1 4 5 6 7 8 2 4 5
You're not actually altering the array.
In the second loop, you say "if the current element is the max, set it to the max". In other words, set it to its current value. Similarly for the min.
What you want is to swap those assignments.
if(a[i]==max) a[i]=min;
if(a[i]==min) a[i]=max;
Also, your initial values for min and max are no good. min is unitialized, so its initial value is undefined. You should initialize min to a very large value, and similarly max should be initialized to a very small (i.e. large negative) value.
A better way to do this would be to keep track of the index of the largest and smallest values. These you can initialize to 0. Then you can check a[i] > a[max] and a[i] < a[min]. Then you print the values at indexes min and max, then loop through the list and print the others.
int i, temp, min=0, max=0;
for (i=1; i<10; i++) {
if (a[i] > a[max]) max = i;
if (a[i] < a[min]) min = i;
}
printf("%d %d ", a[max], a[min]);
for (i=0; i<10; i++) {
if ((i != min) && (i != max)) {
printf("%d ", a[i]);
}
}
printf("\n");
Just keep it nice and simple, like this:
#include <stdio.h>
#include <stdlib.h>
#define MAXNUM 10
int find_biggest(int A[], size_t n);
int find_smallest(int A[], size_t n);
void print_array(int A[], size_t n);
void int_swap(int *a, int *b);
int
main(void) {
int array[MAXNUM], i, smallest, biggest;
printf("Please enter 10 int values:\n");
for (i = 0; i < MAXNUM; i++) {
if (scanf("%d", &array[i]) != 1) {
printf("invalid input\n");
exit(EXIT_FAILURE);
}
}
printf("Before: ");
print_array(array, MAXNUM);
smallest = find_smallest(array, MAXNUM);
biggest = find_biggest(array, MAXNUM);
int_swap(&array[smallest], &array[biggest]);
printf("After: ");
print_array(array, MAXNUM);
return 0;
}
int
find_biggest(int A[], size_t n) {
int biggest, i, idx_loc;
biggest = A[0];
idx_loc = 0;
for (i = 1; i < n; i++) {
if (A[i] > biggest) {
biggest = A[i];
idx_loc = i;
}
}
return idx_loc;
}
int
find_smallest(int A[], size_t n) {
int smallest, i, idx_loc;
smallest = A[0];
idx_loc = 0;
for (i = 1; i < n; i++) {
if (A[i] < smallest) {
smallest = A[i];
idx_loc = i;
}
}
return idx_loc;
}
void
print_array(int A[], size_t n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", A[i]);
}
printf("\n");
}
void
int_swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}

Finding Max value and Average Of All elemements in 2D array in C

EDIT II
I'm finally getting somewhere, now i get my random values with a return from the maxavg() function.
My only question now is, when i run the program i always get:
average: 0
maximum: 33
why? it does not make much sense.
Here is the new code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
int GetRand(int min, int max);
struct maxavg;
int main ()
{
int a[21][21], i , j, average, maximum, ret;
for (i = 0; i < 21; i++)
{
for ( j = 0; j < 21; j++)
{
a[i][j] = GetRand(0, 100);
printf("%3d" , a[i][j]);
}
a[2][15] = -1;
a[10][6] = -1;
a[13][5] = -1;
a[15][17] = -1;
a[17][17] = -1;
a[19][6] = -1;
printf("\n");
}
printf("average = %d \n maximum = %d", average, maximum);
return 0;
}
// random seed
int GetRand(int min, int max);
int get ()
{
int i, r;
for (i = 0; i < 21; i++)
{
r = GetRand(0, 100);
printf("Your number is %d \n", r);
}
return(0);
}
int GetRand(int min, int max)
{
static int Init = 0;
int rc;
if (Init == 0)
{
srand(time(NULL));
Init = 1;
}
rc = (rand() % (max - min +1) +min);
return (rc);
}
struct pair
{
int max;
int avg;
};
// max and average
struct pair maxavg()
{
struct pair p;
int max=INT_MIN, sum=0, count=0, avg, i, j, current;
for(i = 0; i < 21; i++){
for(j =0; j < 21; j++){
if(current > -1){
sum = sum + current;
count = count + 1
;if(current > max){
max = current;
}
}
}
}
avg = sum/count;
printf("Max is %d \n", max);
printf("Average is %d \n", avg);
p.max = max;
p.avg = avg;
return p;
}
EDIT:
So here is what i'm doing, i get error messages:
Average:
// Average Code
value = a[i][j];
int actualvalue, suma = 0, quant;
for(i=0; i<21; i++){
for(j=0; j<21; j++){
if (actualvalue > -1){
a[i][j] = actualvalue;
suma = suma + actualvalue;
// sum actual value + nextvalue (sum of all > -1) //
}
else if {
quant = quant + 1;
//(sum the quantity of times a value has been greater than -1)//
}
}
}
printf("The average value is:", suma/quant); ///(sun of all values > -1)/(sum of quantity value was > -1)/
Find Maximum:
// Max
int variableP = a[0][0];
value = a[i][j];
int variableP = a[i][j]
for(i=0; i<21; i++){
for(j=0; j<21; j++){
if(variableP < newvalue){
variableP = newvalue
}
}
}
printf("The max value of the 2D array is", %d);
Average and Maximum:
// max and average
int maxvg();
int max=INT_MIN, sum=0, count=0, avg;
for(i = 0; i < 21; i++){
for(j =0; j < 21; j++){
if(current > -1){
sum = sum + current;
count = count + 1
if(current > max){
max = current;
}
}
}
}
avg = sum/count;
printf("Max is %d \n", max);
printf("Average is %d \n", avg);
So how right or wrong is this? what am i missing.
i mostly get:
[Error] expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
[Warning] data definition has no type or storage class
[Error] initializer element is not constant
[Error] expected declaration specifiers or '...' before string constant
Am i at least close to it?
Thanks in advance.
END OF EDIT
I created a 2D array with random numbers from 0 to 100 (and a couple of -1) values with this code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int a[21][21], i, j;
for (i = 0; i < 21; i++) {
for (j = 0; j < 21; j++) {
a[i][j] = GetRand (0, 100);
a[7][15] = -1;
a[10][6] = -1;
a[13][5] = -1;
a[15][17] = -1;
a[17][17] = -1;
a[19][6] = -1;
printf ("%3d", a[i][j]);
}
printf ("\n");
}
return 0;
}
// random seed
int GetRand (int min, int max);
int get ()
{
int i, r;
for (i = 0; i < 21; i++) {
r = GetRand (0, 100);
printf ("Your number is %d \n", r);
}
return (0);
}
int GetRand (int min, int max)
{
static int Init = 0;
int rc;
if (Init == 0) {
srand (time (NULL));
Init = 1;
}
rc = (rand () % (max - min + 1) + min);
return (rc);
}
This prints the array created. Now I want to calculate the maximum value of all values inside the array and the total average of all values in the array, all while ignoring all -1 values, so only from 0 to 100. Since I'm a total beginner I'm having problems creating these functions. So here are my ideas.
//For the average
for(i=0; i<1; i++){
for(j=0; j<21; j++){
if (actualvalue > -1){
//sum actualvalue + nextvalue (sum of all the values greater than -1)//
}
else if (actualvalue > -1){
//(sum the quantity of times a value has been greater than -1)//
}
}
}
}
printf("The average value is", //(sum of all values>-1)/(sum of quantity value was >-1) //);
I'm representing the thing i don't know how to write in code in words so you get my idea.
Now for finding the maximum: what i think i should do is initialize the array and make a variable adopt the first value it finds that's > -1, then rewind and initialize again, if the actualvalue < newvalue then make variableP adopt the newvalue:
//max
int variableP = a[i][j]
for(i=0; i<21; i++){
for(j=0;j<21;j++){
if(variableP < newvalue){
variableP = newvalue
}
printf("The max value of the 2D array is", %d);
}
I know it's evident i'm not sure what i'm writing here, but i think my idea of it is correct, i hope i'm explaining it well enough.
Sum is as you say.
Average requires you count number of >-1 values.
Max looks right lines. Finish off your ideas and ask again if it doesn't work
You can do both max and avg in one loop.
Declare three variables: max=-999999, sum=0, count=0.
Each time when current cell is not -1 increase sum by it's value and count by 1.
Each time check if current value is bigger than max, then set max to current value.
After the loop is done, avg = sum/count.
Consider you are doing all your arithmetic using integers, and integer division is integer. Perhaps you have better to do a double result with:
/* you don't actually need to cast to double in both operators, as the
* one not casted will be automagically casted to double to operate on.
*/
double average = (double) sum_of_samples / (double) number_of_samples;
You have to cast at least one of the operators, because if you don't you'll get the result as before (a 0 integer result) converted to double to assign to the variable.

printing * in respective number using printf in C

I'm trying to work on this assignment that prints "*" in their respective number. Also, if you see the picture I need to display the min and the max number, how can I do this? I was thinking about doing it with an array storing those numbers there but when I created the array and tried to pass them I got an error.
Here's the picture:
#include <stdio.h>
#include <limits.h>
#include <math.h>
int f(int);
int main(void){
int i, t, funval,tempL,tempH;
int a;
// Make sure to change low and high when testing your program
int low=-3, high=11;
for (t=low; t<=high;t++){
printf("f(%2d)=%3d\n",t,f(t));
}
printf("\n");
printf(" ");
for (i=1; i<=31; i+=5)
printf("%3d ", i);
printf("\n");
printf(" ");
for (i=1; i<=31; i+=5)
printf(" | ");
printf("\n");
for (t=low; t<=high;t++){
printf("t=%2d\n",t);
}
printf("\n");
for(i=0;i<=sizeof(nums)/sizeof(int);i++){
if (nums[i] > max)
{
max = nums[i];
}
if (nums[i] < min)
{
min = nums[i];
}
}
printf("Min: %d\n", min);
printf("Max: %d\n", max);
printf("\n");
printf(" ");
for (i=min; i<=max; i+=5)
printf("%3d ", i);
printf("\n");
printf(" ");
for (i=min; i<=max; i+=5)
printf(" | ");
printf("\n");
for (t=low; t<=high;t++){
printf("t=%2d\n",t);
}
// Your code here...
return 0;
}
int f(int t){
// example 1
return (t*t-4*t+5);
// example 2
// return (-t*t+4*t-1);
// example 3
// return (sin(t)*10);
// example 4
// if (t>0)
// return t*2;
// else
// return t*8;
}
#include <stdio.h>
#include <stdlib.h>
int parabola1(int);
int *calc(int low, int high, int (*f)(int), int *size, int *min, int *max){
/*
#input
low, high : range {x| low <= x <= high}
f : function
#output
*size : Size of array
*min : Minimum value of f(x)
*max : Maximum value
return : pointer to first element of int num[*size]
NULL if this can not be ensured.
*/
int i, x, *nums;
*size = high - low + 1;
*max = *min = f(low);//value of the provisional
if(NULL==(nums=malloc(*size*sizeof(*nums)))){
return NULL;//max and min are unavailable
}
for(i = 0, x = low; x <= high; ++x, ++i){
nums[i] = f(x);
if(nums[i] > *max)
*max = nums[i];
if(nums[i] < *min)
*min = nums[i];
}
return nums;
}
int main(void){
int i, t;
int *nums, size;
int low=-3, high=9, min, max;
nums = calc(low, high, parabola1, &size, &min, &max);
for (i=0; i<size;i++){
printf("f(%2d)=%3d\n", low+i, nums[i]);
}
printf("--\n");
printf("min=%3d\n", min);
printf("max=%3d\n", max);
printf("--\n");
t = -2;
printf("t=%2d%*s%c\n", t, nums[t-low]-min, "", '*');
free(nums);
return 0;
}
int parabola1(int t){
return t*(t-4)+5;
}

Resources