Friday, March 16, 2018

C Program to Check Whether a Number is Prime or Not.

#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 nonprime number
        if(n%i==0)
        {
            flag=1;
            break;
        }
    }

    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.

C Program to Display Prime Numbers Between Two Intervals.

#include <stdio.h>
int main()
{
    int low, high, i, flag;
    printf("Enter two numbers(intervals): ");
    scanf("%d %d", &low, &high);

    printf("Prime numbers between %d and %d are: ", low, high);

    while (low < high)
    {
        flag = 0;

        for(i = 2; i <= low/2; ++i)
        {
            if(low % i == 0)
            {
                flag = 1;
                break;
            }
        }

        if (flag == 0)
            printf("%d ", low);

        ++low;
    }

    return 0;
}

Output

Enter two numbers(intervals): 20
50
Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47

C Program to Display its own Source Code as Output.

#include <stdio.h>
int main() {
    FILE *fp;
    char c;
    fp = fopen(__FILE__,"r");
    do {
         c = getc(fp);
         putchar(c);
    }
    while(c != EOF);
    fclose(fp);
    return 0;
}

Program to Display English Alphabets in Uppercase and Lowercase.

#include <stdio.h>
int main()
{
    char c;

    printf("Enter u to display alphabets in uppercase. And enter l to display alphabets in lowercase: ");
    scanf("%c", &c);

    if(c== 'U' || c== 'u')
    {
       for(c = 'A'; c <= 'Z'; ++c)
         printf("%c ", c);
    }
    else if (c == 'L' || c == 'l')
    {
        for(c = 'a'; c <= 'z'; ++c)
         printf("%c ", c);
    }
    else
       printf("Error! You entered invalid character.");
    return 0;
}

Output:-
Enter u to display alphabets in uppercase. And enter l to display alphabets in lowercase: l

a b c d e f g h i j k l m n o p q r s t u v w x y z