C Program Prime number, Copy a string to another, String concatenation, String Comparision.

Q. 1. Write a 'C' program to find a number is prime or not using function.

#include <stdio.h>

int prime(int);

void main()

{

  int n;

  printf("Enter a positive integer: ");

  scanf("%d", &n);

 prime(n);

 }

  int prime(n)

{

  int i, flag = 0;

    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 n;

}

Q.2. Write a 'C' program to calculate factorial using function.

#include <stdio.h>

int fact(int);

void main()

{

 int no,factorial;

    printf("Enter a number to calculate it's factorial\n");

   scanf("%d",&no);

   factorial=fact(no);

    printf("Factorial of the num(%d) = %d\n",no,factorial);

}

 int fact(int n)

{

    int i,f=1;

    for(i=1;i<=n;i++)

    {

        f=f*i;

    }

    return f;

}


Q. 3. Write a 'C' program to copy one string to another.

#include <stdio.h>

#include <string.h>

char str2[75], str1[75]; ; 

void main()

{

    printf("Enter any string:\n");

    gets(str1);

    strcpy(str2, str1);

    printf("original string s1='%s'\n", str1);

    printf("copied string   s2='%s'", str2);

 }

Q.4. Write a 'C' Program to concatenate two strings.

#include <stdio.h>
#include <string.h>
 
int main()
{
    char str1[75],str2[75];  
    
    printf("Enter  string1: ");
    gets(str1);
    printf("Enter  string2: ");
    gets(str2);
    strcat(str1,str2);
    printf("combined two strings ='%s'\n", str1);
    return 0;
}
Q.5. Write a 'C' Progrma to compare two strings.

#include <stdio.h>
#include <string.h>
 int main()
{
    char str1[75],str2[75];  
    int str;
    printf("Enter  string1: ");
    gets(str1);
    printf("Enter  string2: ");
    gets(str2);
   str= strcmp(str1,str2);
    if(str==0)
    { 
        printf("Both Strings are Same");
    }
    else
    {
        printf("Both Strings are diferent");
    }
    return 0;
}






Post a Comment

0 Comments