I was having a trouble regarding to printing out the largest number in array in c language and i don't know how to do it while using loop. Please help me thanks
here is my code
#include<stdio.h>
void main(){
int Lnum, size;
printf("Enter the size: ");
scanf("%d", &size);
int nums[size];
for(int i=0; i<size; i ){
scanf("%d", &nums[i]);
}
printf("\nReversed = ");
for(int i=size-1; i>=0; i--){
printf("%d ", nums[i]);
}
for(int a=0; a<size; a ){
for(int i=0; i<size; i ){
if(nums[a]>nums[i]){
Lnum = nums[a];
}
}
}
printf("\nLargest element = %d", Lnum);
}
CodePudding user response:
The algorithm for determining the largest element in an array goes as follows.
- Use the value of the first array element as a start value for the biggest number.
- Go over the rest of the array and check for each element if it is a bigger number.
- When a bigger number is found use the bigger number for further comparisons.
#include<stdio.h>
void main(){
int Lnum, size;
printf("Enter the size: ");
scanf("%d", &size);
int nums[size];
for(int i=0; i<size; i ){
scanf("%d", &nums[i]);
}
printf("\nReversed = ");
for(int i=size-1; i>=0; i--){
printf("%d ", nums[i]);
}
Lnum = nums[0]; // Assume first element to be the largest element
for(int a=1; a<size; a ){ // start loop with second element
if(Lnum < nums[a]) { // check if current element is larger
Lnum = nums[a]; // found larger element, it is now the largest element of all inspected element
}
}
printf("\nLargest element = %d", Lnum);
}
Output:
Enter the size: 3
1 2 3
Reversed = 3 2 1
Largest element = 3
...Program finished with exit code 0
CodePudding user response:
What you can do is declare a int with val = 0; and store the array element in that var after comparing the element of the array contiguously with declared int variable, you will get the biggest integer at end.
#include <stdio.h>
void main()
{
int Lnum, size, temp, temp1 = 0;
printf("Enter the size: ");
scanf("%d", &size);
int nums[size];
for (int i = 0; i < size; i ) {
scanf("%d", &nums[i]);
}
printf("\nReversed = ");
for (int i = size - 1; i >= 0; i--) {
printf("%d ", nums[i]);
}
for (int i = 0; i < size; i ) {
temp = nums[0];
if (temp1 <= nums[i]) {
temp1 = nums[i];
}
}
printf("\nLargest element = %d", temp1);
}