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 ...

Check Whether a Number is Prime or Not in C

 

Check Whether a Number is Prime or Not in C

In this example, you will learn to check whether an integer entered by the user is a prime number or not.

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

  • C if...else Statement
  • C for Loop
  • C break and continue

A prime number is a positive integer that is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13, 17


Program to Check Prime Number

#include <stdio.h>
int main() {
    int n, i, flag = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &n);

    for (i = 2; i <= n / 2; ++i) {

        // condition for non-prime
        if (n % i == 0) {
            flag = 1;
            break;
        }
    }

    if (n == 1) {
        printf("1 is neither prime nor composite.");
    }
    else {
        if (flag == 0)
            printf("%d is a prime number.", n);
        else
            printf("%d is not a prime number.", n);
    }

    return 0;
}

Output

Enter a positive integer: 29
29 is a prime number.

In the program, a for loop is iterated from i = 2 to i < n/2.

In each iteration, whether n is perfectly divisible by i is checked using:

if (n % i == 0) {
   
}

If n is perfectly divisible by in is not a prime number. In this case, flag is set to 1, and the loop is terminated using the break statement.

After the loop, if n is a prime number, flag will still be 0. However, if n is a non-prime number, flag will be 1.

Visit this page to learn how you can print all the prime numbers between two intervals.

Comments

Popular posts from this blog

C Program to Print an Integer (Entered by the User)

Simple Calculator Using switch case in C

Add Two Integers in C language