C exercises and solutions: C pointer find max


C pointer: find max exercise

Write a C program to find the max of an integral data set. The program will ask the user to input the number of data values in the set and each value. Then your program will show the max of the data set. See example below.  Your C program will use a function that accepts the array of data values and its size. The return from the function is the pointer that points to the max value.

  Enter number of data values: 3
  Enter value 1: 21
  Enter value 2: 12
  Enter value 3: 4
  The max is 21. 
  Result: 2/9 
 
Solution:
#include<stdio.h>
#include<conio.h>
int *findMax(int arr[],int n);
int main(){
    int n,i,*p;
    printf("Enter number of data values");
    scanf("%d",&n);
    int arr[n];
   
    for(i=0;i<n;i++)
    {
      printf("Enter value %d:",i+1);
      scanf("%d",&arr[i]);
     
      }
     
    p=findMax(arr,n);
    printf("The max value is: %d",*p);
    getch();
    return 0;
}
 
int *findMax(int data[],int n){
    int *max=data;
    int i;
    for(i=1;i<n;i++){
           if(*max<*(max+i)) *max=*(max+i);        
                     }
    return max;
}


Comments

Nemanja comment

 Nemanja

#include <stdio.h>

int max=0;

int maxValueReturn (int array[], int length){
int i;
for (i=0;i<length;i++){
if (array[i]>max)
max=array[i];
}
return &max;
}
main() {
int length, i, *pmax;
printf("Enter the size of an array: ");
scanf("%i", &length);
int array[length];
for (i=0;i<length;i++){
printf("\nEnter the %i'st member of an array: ", i+1);
scanf("%i", &array[i]);
}
pmax=maxValueReturn(array, length);
printf("Maximum value of array is: %i\n", *pmax);
return 0;
}


2017-03-30



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.