GoogleTag

Google Search

[Programming] Question 3: Find the largest element in an array in C?

Learn how to write a C program to find the largest element in an array. This tutorial demonstrates how to traverse an array, compare its elements, and identify the largest one. Ideal for those new to C programming and looking to enhance their skills in array handling and basic algorithms.

#include <stdio.h>

int main() {
	int arr[] = {10, 20, 30, 40, 50};
	int max = arr[0];
	int i;

	for (i = 1; i < sizeof(arr)/sizeof(arr[0]); i++) {
		if (arr[i] > max)
			max = arr[i];
	}

	printf("Largest element in array: %d\n", max);

	return 0;
} 
Explanation:

Inside the main() function:

- An integer array arr is declared and initialized with values.

- An integer variable max is initialized to the first element of the array.

- A for loop is used to iterate through each element of the array, starting from the second element.

- Within the loop, if the current element is greater than the current maximum, update max to the current element.

- Finally, the largest element in the array is printed to the console.

 

Featured Posts

SQL Interview Questions Topics

 SQL Topics to prepare for interviews,   SQL Basics: Introduction to SQL SQL Data Types DDL (Data Definition Language): C...

Popular Posts