SlideShare a Scribd company logo
2
Most read
1. Write a program to checka givennumberisprime ornot.
Algorithm:
Step1: Start
Step2: Declare variablesn,i,prime.
Step3: Initialize variables
prime←0
i←2
Step4: Readn fromuser.
Step5: Repeatthe stepsuntil i<=(n/2)
5.1 If remainderof n÷i equals0
prime←1
Go to step6
5.2 i←i+1
Step6: If prime=0
Displayn isprime
else
Displayn isnot prime
Step7: Stop
Source Code:
#include<stdio.h>
voidmain()
{inti,n,prime=0;
printf("Enteranynumber:");
scanf("%d",&n);
i=2;
while(i<=n/2)
{if(n%i==0)
{prime=1;
break;
}
i++;
}
if(prime==0)
printf("nItisa prime number");
else
printf("nItisnota prime number");
}
Output:
Discursion:
If the while loop terminates when the test expression of loop i <= n/2 is false, the entered
number is a prime number. The value of prime is equal to 0 in this case.
2. Write a c program to check whether a number is a krishnamurty number or not
Algorithm:
1. Input a number from user to check for strong number. Store this in a variable say num.
Copy it to a temporary variable for calculations purposes, say originalNum = num.
2. Initialize another variable to store sum of factorial of digits, say sum = 0.
3. Find last digit of the given number num. Store the result in a variable say lastDigit =
num % 10.
4. Find factorial of lastDigit. Store factorial in a variable say fact.
5. Add factorial to sum i.e. sum = sum + fact.
6. Remove last digit from num as it is not needed further.
7. Repeat steps 3 to 6 till num > 0.
8. After loop check condition for strong number. If sum == originalNum, then the given
number is Strong number otherwise not.
#include <stdio.h>
voidmain()
{
int i,originalNum,num,lastDigit,sum;
longfact;
printf("Enteranynumbertocheckkrishnamurtynumber:");
scanf("%d",&num);
originalNum=num;
sum = 0;
while(num>0)
{
lastDigit=num %10;
fact= 1;
for(i=1;i<=lastDigit;i++)
{
fact = fact * i;
}
sum= sum+ fact;
num= num/ 10;
}
if(sum== originalNum)
{
printf("%diskrishnamurtyNUMBER",originalNum);
}
else
{
printf("%disNOTkrishnamurtyNUMBER",originalNum);
}
}
3. Fibonacci seriesusingrecursive functioninC
#include<stdio.h>
intFibonacci(int);
intmain()
{
intn, i = 0, c;
printf("nEnterhowmanytermyouwantin Fibonacci series:");
scanf("%d",&n);
printf("nFibonacci series:");
for ( c = 1 ; c <= n ; c++ )
{
printf("%dt",Fibonacci(i));
i++;
}
}
intFibonacci(intn)
{
if ( n == 0 )
return0;
else if ( n == 1 )
return1;
else
return( Fibonacci(n-1) +Fibonacci(n-2) );
}
Discursion:
Fibonacci series is a sequence of following numbers
0 1 1 2 3 5 8 13 ....
It adds previous two numbers value to compute the next number value. In this program
fibonacci series is calculated using recursion, with seed as 0 and 1. Recursion means a
function calling itself, in the below code fibonacci function calls itself with a lesser value
several times. An termination condition is very important to recursion function, i.e n == 0
and n == 1 or the recursive call would be infinite leading to stack overflow error.
4. C Program to print array in reverse
Algorithm:
1. Input size and elements in an array. Store it in some variable
say size and arr respectively.
2. Declare another array that will store reversed array elements of original array with same
size, say reverse[size].
3. Initialize two variables that will keep track of original and reverse array. Here we will
access original array from last and reverse array from first. Hence, initialize arrIndex =
size - 1 and revIndex = 0.
4. Run loop from size - 1 to 0 in decremented style. The loop structure should look
like while(arrIndex >= 0).
5. Inside loop copy original array to reverse array i.e. reverse [revIndex] = arr[arrIndex];.
6. After copy, increment revIndex and decrement arrIndex.
7. Finally after loop print reverse array.
Code:
#include <stdio.h>
voidmain()
{
int arr[50];
int size,i;
printf("Entersize of the array:");
scanf("%d",&size);
printf("Enterelements inarray:");
for(i=0;i<size;i++)
{
scanf("%d",&arr[i]);
}
printf("nArrayinreverseorder:");
for(i = size-1;i>=0; i--)
{
printf("%dt",arr[i]);
}
}
Discursion:
This algorithm in real does not produces a reversed array. Instead it just prints array in
reverse order. If you are looking to reverse the elements then skip to next logic. So here
goes step by step descriptive logic to print array in reverse order.
a. Input size and elements in array from user. Store it in some variable
say size and arr.
b. Run a loop from size - 1 to 0 in decremented style. The loop structure should look
like for(i=size-1; i>=0; i--).
c. Inside loop print current array element i.e. arr[i].
5. C Program to Merge the Elements of 2 Sorted Array
1. Create two arrays of some fixed size and define their elements in sorted fashion.
2. Take two variables i and j, which will be at the 0th position of these two arrays.
3. Elements will be compared one by one using i and j in for loop, and whichever element is smaller
than the other, that element will get inserted to final array and the position(either i or j) will move by
one, whereas the other array’s track position will remain in that same place.
4. Above work will be done till we reach the end of either array. After that, one of the array whose
elements are still to be added, its elements will get straightaway added to the final array.
#include <stdio.h>
void main()
{
int array1[50], array2[50], array3[100], m, n, i, j, k = 0;
printf("n Enter size of array Array 1: ");
scanf("%d", &m);
printf("n Enter sorted elements of array 1: n");
for (i = 0; i < m; i++)
{
scanf("%d", &array1[i]);
}
printf("n Enter size of array 2: ");
scanf("%d", &n);
printf("n Enter sorted elements of array 2: n");
for (i = 0; i < n; i++)
{
scanf("%d", &array2[i]);
}
i = 0;
j = 0;
while (i < m && j < n)
{
if (array1[i] < array2[j])
{
array3[k] = array1[i];
i++;
}
else
{
array3[k] = array2[j];
j++;
}
k++;
}
if (i >= m)
{
while (j < n)
{
array3[k] = array2[j];
j++;
k++;
}
}
if (j >= n)
{
while (i < m)
{
array3[k] = array1[i];
i++;
k++;
}
}
printf("n After merging: n");
for (i = 0; i < m + n; i++)
{
printf("n%d", array3[i]);
}
}
Discursion:
1. Declare 2 1D arrays of some fixed size, then take size of the arrays from user and define all the
elements of the array according to the size in sorted fashion.
2. Take two variables, i and j as iterators which will track the position of elements in arrays.
3. Running a while loop till we reach the end of either array, the element at ith and jth position of two
arrays are compared.
4. The smaller element gets inserted into final array (third array, whose size is the sum of the size of
these two arrays) and the track position gets incremented by 1.
5. This process continues, till we reach the end of either array.
6. After finishing the loop above, one of the array’s tracker(i.e either i or j) will not be at the last
position of the corresponding array, in that case we will have to add all the remaining elements of
that array to the final array as it is one by one
6. C Program to Check if a String is a Palindrome without using the Built-in Function
Algorithm:
a. Take a string as input and store it in the array.
b. Reverse the string and store it in another array.
c. Compare both the arrays.
#include <stdio.h>
void main()
{
char string[25], reverse_string[25] = {'0'};
int i, length = 0, flag = 0;
printf("Enter a string:");
gets(string);
for (i = 0; string[i] != '0'; i++)
{
length++;
}
for (i = length - 1; i >= 0 ; i--)
{
reverse_string[length - i - 1] = string[i];
}
for (flag = 1, i = 0; i < length ; i++)
{
if (reverse_string[i] != string[i])
flag = 0;
}
if (flag == 1)
printf ("n%s is a palindrome", string);
else
printf("n%s is not a palindrome", string);
}
Discursion:
a. Take a string as input and store it in the array string[].
b. Store the same string into the another array reverse_string[] in the reverse fashion.
c. Using for loop compare the elements of both the arrays.
d. If all the elements of the array are same, then it is a palindrome. Otherwise it is not a palindrome.

More Related Content

PPS
Selection sort
PDF
Matlab integration
PPTX
Strings in C
PPTX
Open addressiing &amp;rehashing,extendiblevhashing
PDF
The solution manual of programming in ansi by Robin
PDF
NME UNIT I & II MATERIAL.pdf
PPT
What is Compiler?
PPTX
Laplace transform
Selection sort
Matlab integration
Strings in C
Open addressiing &amp;rehashing,extendiblevhashing
The solution manual of programming in ansi by Robin
NME UNIT I & II MATERIAL.pdf
What is Compiler?
Laplace transform

What's hot (12)

PDF
Loops and conditional statements
PPTX
Tail Recursion in data structure
PPT
Lec 14. Call by Reference
PPT
File handling in c
PPTX
Decision control structures
PPT
One dimensional 2
RTF
PPTX
Homogeneous Linear Differential Equations
PPTX
3. Syntax Analyzer.pptx
PDF
The Lambda Calculus and The JavaScript
PPTX
Exact Differential Equations
PPTX
Translators(Compiler, Assembler) and interpreter
Loops and conditional statements
Tail Recursion in data structure
Lec 14. Call by Reference
File handling in c
Decision control structures
One dimensional 2
Homogeneous Linear Differential Equations
3. Syntax Analyzer.pptx
The Lambda Calculus and The JavaScript
Exact Differential Equations
Translators(Compiler, Assembler) and interpreter
Ad

Similar to Write a program to check a given number is prime or not (20)

DOC
Basic c programs updated on 31.8.2020
DOCX
DOCX
Chapter 8 c solution
PPT
All important c programby makhan kumbhkar
DOCX
PPS 7.7 RECURSION, AS A DIFFERENT WAY OF SOLVING PROBLEMS. EXAMPLE PROGRAMS
PDF
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
PPTX
LectureSlidData_sturcture_algorithm_v2.pptx
DOCX
ADA FILE
PDF
C Programming Interview Questions
PDF
DSC program.pdf
PDF
Data Structure using C
PDF
PCA-2 Programming and Solving 2nd Sem.pdf
DOCX
PCA-2 Programming and Solving 2nd Sem.docx
DOC
C important questions
PDF
Programming in C Lab
DOCX
Data structure and algorithm lab spiral (1) (4) (1).docx
PDF
C faq pdf
DOCX
B.Com 1year Lab programs
Basic c programs updated on 31.8.2020
Chapter 8 c solution
All important c programby makhan kumbhkar
PPS 7.7 RECURSION, AS A DIFFERENT WAY OF SOLVING PROBLEMS. EXAMPLE PROGRAMS
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
LectureSlidData_sturcture_algorithm_v2.pptx
ADA FILE
C Programming Interview Questions
DSC program.pdf
Data Structure using C
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.docx
C important questions
Programming in C Lab
Data structure and algorithm lab spiral (1) (4) (1).docx
C faq pdf
B.Com 1year Lab programs
Ad

Recently uploaded (20)

PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
Construction Project Organization Group 2.pptx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
web development for engineering and engineering
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
additive manufacturing of ss316l using mig welding
PDF
Structs to JSON How Go Powers REST APIs.pdf
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
Sustainable Sites - Green Building Construction
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Lecture Notes Electrical Wiring System Components
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Construction Project Organization Group 2.pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Operating System & Kernel Study Guide-1 - converted.pdf
Lesson 3_Tessellation.pptx finite Mathematics
Internet of Things (IOT) - A guide to understanding
CH1 Production IntroductoryConcepts.pptx
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
web development for engineering and engineering
Arduino robotics embedded978-1-4302-3184-4.pdf
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
additive manufacturing of ss316l using mig welding
Structs to JSON How Go Powers REST APIs.pdf
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Sustainable Sites - Green Building Construction
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
CYBER-CRIMES AND SECURITY A guide to understanding

Write a program to check a given number is prime or not

  • 1. 1. Write a program to checka givennumberisprime ornot. Algorithm: Step1: Start Step2: Declare variablesn,i,prime. Step3: Initialize variables prime←0 i←2 Step4: Readn fromuser. Step5: Repeatthe stepsuntil i<=(n/2) 5.1 If remainderof n÷i equals0 prime←1 Go to step6 5.2 i←i+1 Step6: If prime=0 Displayn isprime else Displayn isnot prime Step7: Stop Source Code: #include<stdio.h> voidmain() {inti,n,prime=0; printf("Enteranynumber:"); scanf("%d",&n); i=2; while(i<=n/2) {if(n%i==0) {prime=1; break; } i++; } if(prime==0) printf("nItisa prime number"); else printf("nItisnota prime number"); }
  • 2. Output: Discursion: If the while loop terminates when the test expression of loop i <= n/2 is false, the entered number is a prime number. The value of prime is equal to 0 in this case. 2. Write a c program to check whether a number is a krishnamurty number or not Algorithm: 1. Input a number from user to check for strong number. Store this in a variable say num. Copy it to a temporary variable for calculations purposes, say originalNum = num. 2. Initialize another variable to store sum of factorial of digits, say sum = 0. 3. Find last digit of the given number num. Store the result in a variable say lastDigit = num % 10. 4. Find factorial of lastDigit. Store factorial in a variable say fact. 5. Add factorial to sum i.e. sum = sum + fact. 6. Remove last digit from num as it is not needed further. 7. Repeat steps 3 to 6 till num > 0. 8. After loop check condition for strong number. If sum == originalNum, then the given number is Strong number otherwise not. #include <stdio.h> voidmain() { int i,originalNum,num,lastDigit,sum; longfact; printf("Enteranynumbertocheckkrishnamurtynumber:"); scanf("%d",&num);
  • 3. originalNum=num; sum = 0; while(num>0) { lastDigit=num %10; fact= 1; for(i=1;i<=lastDigit;i++) { fact = fact * i; } sum= sum+ fact; num= num/ 10; } if(sum== originalNum) { printf("%diskrishnamurtyNUMBER",originalNum); } else { printf("%disNOTkrishnamurtyNUMBER",originalNum); } } 3. Fibonacci seriesusingrecursive functioninC #include<stdio.h> intFibonacci(int); intmain() { intn, i = 0, c; printf("nEnterhowmanytermyouwantin Fibonacci series:"); scanf("%d",&n);
  • 4. printf("nFibonacci series:"); for ( c = 1 ; c <= n ; c++ ) { printf("%dt",Fibonacci(i)); i++; } } intFibonacci(intn) { if ( n == 0 ) return0; else if ( n == 1 ) return1; else return( Fibonacci(n-1) +Fibonacci(n-2) ); } Discursion: Fibonacci series is a sequence of following numbers 0 1 1 2 3 5 8 13 .... It adds previous two numbers value to compute the next number value. In this program fibonacci series is calculated using recursion, with seed as 0 and 1. Recursion means a function calling itself, in the below code fibonacci function calls itself with a lesser value several times. An termination condition is very important to recursion function, i.e n == 0 and n == 1 or the recursive call would be infinite leading to stack overflow error. 4. C Program to print array in reverse Algorithm:
  • 5. 1. Input size and elements in an array. Store it in some variable say size and arr respectively. 2. Declare another array that will store reversed array elements of original array with same size, say reverse[size]. 3. Initialize two variables that will keep track of original and reverse array. Here we will access original array from last and reverse array from first. Hence, initialize arrIndex = size - 1 and revIndex = 0. 4. Run loop from size - 1 to 0 in decremented style. The loop structure should look like while(arrIndex >= 0). 5. Inside loop copy original array to reverse array i.e. reverse [revIndex] = arr[arrIndex];. 6. After copy, increment revIndex and decrement arrIndex. 7. Finally after loop print reverse array. Code: #include <stdio.h> voidmain() { int arr[50]; int size,i; printf("Entersize of the array:"); scanf("%d",&size); printf("Enterelements inarray:"); for(i=0;i<size;i++) { scanf("%d",&arr[i]); } printf("nArrayinreverseorder:"); for(i = size-1;i>=0; i--) { printf("%dt",arr[i]); } } Discursion:
  • 6. This algorithm in real does not produces a reversed array. Instead it just prints array in reverse order. If you are looking to reverse the elements then skip to next logic. So here goes step by step descriptive logic to print array in reverse order. a. Input size and elements in array from user. Store it in some variable say size and arr. b. Run a loop from size - 1 to 0 in decremented style. The loop structure should look like for(i=size-1; i>=0; i--). c. Inside loop print current array element i.e. arr[i]. 5. C Program to Merge the Elements of 2 Sorted Array 1. Create two arrays of some fixed size and define their elements in sorted fashion. 2. Take two variables i and j, which will be at the 0th position of these two arrays. 3. Elements will be compared one by one using i and j in for loop, and whichever element is smaller than the other, that element will get inserted to final array and the position(either i or j) will move by one, whereas the other array’s track position will remain in that same place. 4. Above work will be done till we reach the end of either array. After that, one of the array whose elements are still to be added, its elements will get straightaway added to the final array. #include <stdio.h> void main() { int array1[50], array2[50], array3[100], m, n, i, j, k = 0; printf("n Enter size of array Array 1: "); scanf("%d", &m); printf("n Enter sorted elements of array 1: n"); for (i = 0; i < m; i++) { scanf("%d", &array1[i]); } printf("n Enter size of array 2: "); scanf("%d", &n); printf("n Enter sorted elements of array 2: n"); for (i = 0; i < n; i++) { scanf("%d", &array2[i]); } i = 0; j = 0; while (i < m && j < n) { if (array1[i] < array2[j]) { array3[k] = array1[i]; i++;
  • 7. } else { array3[k] = array2[j]; j++; } k++; } if (i >= m) { while (j < n) { array3[k] = array2[j]; j++; k++; } } if (j >= n) { while (i < m) { array3[k] = array1[i]; i++; k++; } } printf("n After merging: n"); for (i = 0; i < m + n; i++) { printf("n%d", array3[i]); } }
  • 8. Discursion: 1. Declare 2 1D arrays of some fixed size, then take size of the arrays from user and define all the elements of the array according to the size in sorted fashion. 2. Take two variables, i and j as iterators which will track the position of elements in arrays. 3. Running a while loop till we reach the end of either array, the element at ith and jth position of two arrays are compared. 4. The smaller element gets inserted into final array (third array, whose size is the sum of the size of these two arrays) and the track position gets incremented by 1. 5. This process continues, till we reach the end of either array. 6. After finishing the loop above, one of the array’s tracker(i.e either i or j) will not be at the last position of the corresponding array, in that case we will have to add all the remaining elements of that array to the final array as it is one by one 6. C Program to Check if a String is a Palindrome without using the Built-in Function Algorithm: a. Take a string as input and store it in the array. b. Reverse the string and store it in another array. c. Compare both the arrays. #include <stdio.h> void main() { char string[25], reverse_string[25] = {'0'};
  • 9. int i, length = 0, flag = 0; printf("Enter a string:"); gets(string); for (i = 0; string[i] != '0'; i++) { length++; } for (i = length - 1; i >= 0 ; i--) { reverse_string[length - i - 1] = string[i]; } for (flag = 1, i = 0; i < length ; i++) { if (reverse_string[i] != string[i]) flag = 0; } if (flag == 1) printf ("n%s is a palindrome", string); else printf("n%s is not a palindrome", string); } Discursion: a. Take a string as input and store it in the array string[]. b. Store the same string into the another array reverse_string[] in the reverse fashion. c. Using for loop compare the elements of both the arrays. d. If all the elements of the array are same, then it is a palindrome. Otherwise it is not a palindrome.