Swap Two Numbers in C

  Swap Two Numbers in C In this example, you will learn to swap two numbers in C programming using two different techniques. To understand this example, you should have the knowledge of the following C programming topics: C Data Types C Programming Operators C Input Output (I/O) Swap Numbers Using Temporary Variable # include <stdio.h> int main () { double first, second, temp; printf ( "Enter first number: " ); scanf ( "%lf" , &first); printf ( "Enter second number: " ); scanf ( "%lf" , &second); // Value of first is assigned to temp temp = first; // Value of second is assigned to first first = second; // Value of temp (initial value of first) is assigned to second second = temp; printf ( "\nAfter swapping, firstNumber = %.2lf\n" , first); printf ( "After swapping, secondNumber = %.2lf" , second); return 0 ; } Output ...

Find Largest Number Using Dynamic Memory Allocation in C

 

C Program to Find Largest Number Using Dynamic Memory Allocation

In this example, you will learn to find the largest number entered by the user in a dynamically allocated memory.

To understand this example, you should have the knowledge of the following C programming topics:

  • C Pointers
  • C Dynamic Memory Allocation
  • C for Loop

Find the Largest Element in a Dynamically Allocated Memory in C

#include <stdio.h>
#include <stdlib.h>
int main() {
    int num;
    float *data;
    printf("Enter the total number of elements: ");
    scanf("%d", &num);

    // Allocating memory for num elements
    data = (float *)calloc(num, sizeof(float));
    if (data == NULL) {
        printf("Error!!! memory not allocated.");
        exit(0);
    }

    // Storing numbers entered by the user.
    for (int i = 0; i < num; ++i) {
        printf("Enter Number %d: ", i + 1);
        scanf("%f", data + i);
    }

    // Finding the largest number
    for (int i = 1; i < num; ++i) {
        if (*data < *(data + i))
            *data = *(data + i);
    }
    printf("Largest number = %.2f", 
    *data);

    return 0;
}

Output

Enter the total number of elements: 5
Enter Number 1: 3.4
Enter Number 2: 2.4
Enter Number 3: -5
Enter Number 4: 24.2
Enter Number 5: 6.7
Largest number = 24.20

In the program, the user is asked to enter the number of elements, which is stored in variable num. We will allocate memory for num number of float values.

Then, the user is asked to enter num numbers. These numbers are stored in the dynamically allocated memory.

Finally, the largest number among these numbers is determined and printed on the screen.

Comments

Popular posts from this blog

Add Two Integers in C language

Find G.C.D Using Recursion in C