SlideShare ist ein Scribd-Unternehmen logo
1 von 98
Downloaden Sie, um offline zu lesen
1. Write a c program to reverse a given number
2. #include<stdio.h>
3. int main(){
4. int num,r,reverse=0;
5.
6. printf("Enter any number: ");
7. scanf("%d",&num);
8.
9. while(num){
10. r=num%10;
11. reverse=reverse*10+r;
12. num=num/10;
13. }
14.
15. printf("Reversed of number: %d",reverse);
16. return 0;
17. }
18.
19. Sample output:
20. Enter any number: 12
21. Reversed of number: 21
22. Sample output:
23. Enter any number: 12
24. Reversed of number: 21
25.Palindrome number in c
26. #include <stdio.h>
27.
28. main()
29. {
30. int n, reverse = 0, temp;
31.
32. printf("Enter a number to check if it is a palindrome or notn");
33. scanf("%d",&n);
34.
35. temp = n;
36.
37. while (temp != 0)
38. {
39. reverse = reverse * 10;
40. reverse = reverse + temp%10;
41. temp = temp/10;
42. }
43.
44. if (n == reverse)
45. printf("%d is a palindrome number.n", n);
46. else
47. printf("%d is not a palindrome number.n", n);
48.
49. return 0;
50. }
51. How towrite a C program to determine the smallest among
52. three nos using conditional operator?
#include<stdio.h>
#include<conio.h>
voidmain()
{
intn1,n2,n3,small;
clrscr();
printf("Enterthree numbers");
scanf("%d%d%d",&n1,&n2,&n3);
small=n1<n2?(n1<n3?n1:n3):(n2<n3?n2:n3);
printf("smallestnumberis:%d",small);
printf("pressanykeytoclose");
getch();
}
write program to perform sum = 1-2+3-4+..
#include<stdio.h>
#include<conio.h>
void main()
{
int e=0,o=0;
Int n;
Printf(“enterano”);
Scanf(“%d”,&n);
For(i=1;i<=n;i++)
{if(i%2==0)
E=e+I;
Else
o=o+I;
}
Printf(“the sumis+%d -%d”,o-e):
}
Write a C program to find the average of N numbers by using the for
loop.
#include<stdio.h>
#include<conio.h>
void main()
int n,i,sum;
float av;
clrscr();
printf("n Enter the value of N:");
scanf("%d",&n);
for(i =1;i<=n;i++)
{
sum= sum+i;
}
printf("n sum is:%d",sum);
av=(float)sum/n;
printf("n Average is: %f",av);
getche();
}
OUTPUT:
Enter the value of n: 10
sum is: 55
Average is: 5.5
c programto count the numberof vowelsandconsonantsinastring
Here is the programto count numberof vowelsandconsonantsinc.
vowels and consonants
#include<stdio.h>
//#include<conio.h>
#include<string.h>
voidmain()
{
char str[50];
int vovels=0,consonants=0,len,i;
printf("Enterthe String:n");
gets(str);
len=strlen(str);
for(i=0;i<len;i++)
{
if((str[i]>64&&str[i]<91)||(str[i]>96&&str[i]<123)) //Firstlycheckingthe characteris
alphabetornot
{
if(str[i]=='a'||str[i]=='A'||str[i]=='e'||str[i]=='E'||str[i]=='i'||str[i]=='I'||str[i]=='o'||str[i]=='O'||str[i]=='u
'||str[i]=='U') //checkingif itisvowel ornot
vovels++;
else
consonants++;
}
}
printf("Numberof vovels=%d andconsonants= %d",vovels,consonants);
//getch();
}
Write a Programto printPrime Numbersbetween1 to 100
#include
voidmain()
{
intn,c=2;
printf("enteranumber");
scanf("%d",&n);
for(c=2;c<n-1;c++)
{
if(n%c==0){
printf("notaprime number"); break;
}
}
if(c==n){
printf("primenumber");
}
}
Write a c program to find out the sum of series 1^2 + 2^2 + …. + n^2.
Sum of the series 12 + 22 + 32 + … + n2 = n (n+1) (2n+1)/6
1
2
3
4
5
6
7
8
9
10
11
12
#include<stdio.h>
int main(){
int n,i;
int sum=0;
printf("Enter the n i.e. max values of series: ");
scanf("%d",&n);
sum = (n * (n + 1) * (2 * n + 1 )) / 6;
printf("Sum of the series : ");
13
14
15
16
17
18
19
20
21
22
23
for(i =1;i<=n;i++){
if (i != n)
printf("%d^2 + ",i);
else
printf("%d^2 = %d ",i,sum);
}
return 0;
}
Output:
Enter the n i.e. max values of series: 5
Sum of the series: 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55
FIND OUT LARGEST NUMBERINANARRAYUSING C PROGRAM
C program to find the largest element in an array
imple program of c find the largest number
#include<stdio.h>
int main(){
int n,num,i;
int big;
printf("Enter the values of n: ");
scanf("%d",&n);
printf("Number %d",1);
scanf("%d",&big);
for(i=2;i<=n;i++){
printf("Number %d: ",i);
scanf("%d",&num);
if(big<num)
big=num;
}
printf("Largest number is: %d",big);
return 0;
}
Sample Output:
Enter the values of n:
Number 1: 12
Number 2: 32
Number 3: 35
Largest number is: 35
TO FIND FACTORIALOFA NUMBERUSING C PROGRAM
Code 1:
1. C code for factorial of a number
2. C program to find the factorial of a given number
3. Factorial program in c using while loop
4. Factorial program in c without using recursion
#include<stdio.h>
int main(){
int i=1,f=1,num;
printf("Enter a number: ");
scanf("%d",&num);
while(i<=num){
f=f*i;
i++;
}
printf("Factorial of %d is: %d",num,f);
return 0;
}
Sample output:
Enter a number: 5
Factorial of 5 is: 120
Code 2:
1. Factorial program in c using for loop
2. Simple factorial program in c
3. C program to calculate factorial
#include<stdio.h>
int main(){
int i,f=1,num;
printf("Enter a number: ");
scanf("%d",&num);
for(i=1;i<=num;i++)
f=f*i;
printf("Factorial of %d is: %d",num,f);
return 0;
}
Code 3:
1. Factorial program in c using pointers
2. How to calculate factorial in c
3. Factorial program in c language
#include<stdio.h>
void findFactorial(int,int *);
int main(){
int i,factorial,num;
printf("Enter a number: ");
scanf("%d",&num);
findFactorial(num,&factorial);
printf("Factorial of %d is: %d",num,*factorial);
return 0;
}
void findFactorial(int num,int *factorial){
int i;
*factorial =1;
for(i=1;i<=num;i++)
*factorial=*factorial*i;
}
Code 4:
1. Factorial program in c using function
2. C program to find factorial of a number
#include<stdio.h>
int findFactorial(int);
int main(){
int i,factorial,num;
printf("Enter a number: ");
scanf("%d",&num);
factorial = findFactorial(num);
printf("Factorial of %d is: %d",num,factorial);
return 0;
}
int findFactorial(int num){
int i,f=1;
for(i=1;i<=num;i++)
f=f*i;
return f;
}
Sample output:
Enter a number: 8
Factorial of 8 is: 40320
Code 5:
1. Factorial series in c
#include<stdio.h>
int main(){
long f=1;
int i,num,min,max;
printf("Enter the minimum range: ");
scanf("%d",&min);
printf("Enter the maximum range: ");
scanf("%d",&max);
printf("Factorial series in given range: ");
for(num=min;num<=max;num++){
f=1;
for(i=1;i<=num;i++)
f=f*i;
printf("%ld ",f);
}
return 0;
}
Sample output:
Enter the minimum range: 1
Enter the maximum range: 10
Factorial series in given range: 1 2 6 24 120 720 5040
40320 362880 3628800
Algorithm:
Factorial value
Factorial of number is defined as:
Factorial (n) = 1*2*3 … * n
For example: Factorial of 5 = 1*2*3*4*5 = 120
Note: Factorial of zero = 1
Program to sort set of strings in alphabetical order
#include
#include
#include
void main()
{
char a[20],b[20];
int i,j,n,temp;
clrscr();
printf("n Enter any string : ");
gets(a);
n=strlen(a);
for(i=0;i<n;i++)</n;i++)
{
for(j=0;j<n-i;j++)</n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}}}
printf("n The final string is :");
for(i=0;i<=n;i++)
printf("%c",a[i]);
getch();
}
C program to check odd or even
C program to check odd or even: We will determine whether a number is odd or even by using
different methods all are provided with a code in c language. As you have study in mathematics
that in decimal number system even numbers are divisible by 2 while odd are not so we may use
modulus operator(%) which returns remainder, For example 4%3 gives 1 ( remainder when four
is divided by three). Even numbers are of the form 2*p and odd are of the form (2*p+1) where p
is is an integer.
C program to check odd or even using modulus operator
#include <stdio.h>
int main()
{
int n;
printf("Enter an integern");
scanf("%d", &n);
if (n%2 == 0)
printf("Evenn");
else
printf("Oddn");
return 0;
}
We can use bitwise AND (&) operator to check odd or even, as an example consider binary of 7
(0111) when we perform 7 & 1 the result will be one and you may observe that the least
significant bit of every odd number is 1, so ( odd_number & 1 ) will be one always and also (
even_number & 1 ) is zero.
C program to check odd or even using bitwise operator
#include <stdio.h>
int main()
{
int n;
printf("Enter an integern");
scanf("%d", &n);
if (n & 1 == 1)
printf("Oddn");
else
printf("Evenn");
return 0;
}
Find odd or even using conditional operator
#include <stdio.h>
int main()
{
int n;
printf("Input an integern");
scanf("%d", &n);
n%2 == 0 ? printf("Evenn") : printf("Oddn");
return 0;
}
C program to check odd or even without using bitwise or
modulus operator
#include <stdio.h>
int main()
{
int n;
printf("Enter an integern");
scanf("%d", &n);
if ((n/2)*2 == n)
printf("Evenn");
else
printf("Oddn");
return 0;
}
In c programming language when we divide two integers we get an integer result, For example
the result of 7/3 will be 2. So we can take advantage of this and may use it to find whether the
number is odd or even. Consider an integer n we can first divide by 2 and then multiply it by 2 if
the result is the original number then the number is even otherwise the number is odd. For
example 11/2 = 5, 5*2 = 10 (which is not equal to eleven), now consider 12/2 = 6 and 6*2 = 12
(same as original number). These are some logic which may help you in finding if a number is
odd or not.
C program to check whether input alphabet is a vowel or not
This code checks whether an input alphabet is a vowel or not. Both lower-case and upper-case
are checked.
C programming code
#include <stdio.h>
int main()
{
char ch;
printf("Enter a charactern");
scanf("%c", &ch);
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch ==
'I' || ch =='o' || ch=='O' || ch == 'u' || ch == 'U')
printf("%c is a vowel.n", ch);
else
printf("%c is not a vowel.n", ch);
return 0;
}
Output of program:
Check vowel using switch statement
#include <stdio.h>
int main()
{
char ch;
printf("Input a charactern");
scanf("%c", &ch);
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("%c is a vowel.n", ch);
break;
default:
printf("%c is not a vowel.n", ch);
}
return 0;
}
Functionto checkvowel
int check_vowel(char a)
{
if (a >= 'A' && a <= 'Z')
a = a + 'a' - 'A'; /* Converting to lower case or use a = a + 32 */
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
return 1;
return 0;
}
This function can also be used to check if a character is a consonant or not, if it's not a vowel
then it will be a consonant, but make sure that the character is an alphabet not a special character.
C program to check leap year
C program to check leap year: c code to check leap year, year will be entered by the user.
C programming code
#include <stdio.h>
int main()
{
int year;
printf("Enter a year to check if it is a leap yearn");
scanf("%d", &year);
if ( year%400 == 0)
printf("%d is a leap year.n", year);
else if ( year%100 == 0)
printf("%d is not a leap year.n", year);
else if ( year%4 == 0 )
printf("%d is a leap year.n", year);
else
printf("%d is not a leap year.n", year);
return 0;
}
Output of program:
Please read the leap year article at Wikipedia, it will help you to understand the program. This
code is based on Gregorian Calendar.
C program to find hcf and lcm
C program to find hcf and lcm: The code below finds highest common factor and least common
multiple of two integers. HCF is also known as greatest common divisor(GCD) or greatest
common factor(gcf).
C programming code
#include <stdio.h>
int main() {
int a, b, x, y, t, gcd, lcm;
printf("Enter two integersn");
scanf("%d%d", &x, &y);
a = x;
b = y;
while (b != 0) {
t = b;
b = a % b;
a = t;
}
gcd = a;
lcm = (x*y)/gcd;
printf("Greatest common divisor of %d and %d = %dn", x, y, gcd);
printf("Least common multiple of %d and %d = %dn", x, y, lcm);
return 0;
}
Download HCF and LCM program.
Output of program:
C program to find hcf and lcm using recursion
#include <stdio.h>
long gcd(long, long);
int main() {
long x, y, hcf, lcm;
printf("Enter two integersn");
scanf("%ld%ld", &x, &y);
hcf = gcd(x, y);
lcm = (x*y)/hcf;
printf("Greatest common divisor of %ld and %ld = %ldn", x, y, hcf);
printf("Least common multiple of %ld and %ld = %ldn", x, y, lcm);
return 0;
}
long gcd(long a, long b) {
if (b == 0) {
return a;
}
else {
return gcd(b, a % b);
}
}
C program to find hcf and lcm using function
#include <stdio.h>
long gcd(long, long);
int main() {
long x, y, hcf, lcm;
printf("Enter two integersn");
scanf("%ld%ld", &x, &y);
hcf = gcd(x, y);
lcm = (x*y)/hcf;
printf("Greatest common divisor of %ld and %ld = %ldn", x, y, hcf);
printf("Least common multiple of %ld and %ld = %ldn", x, y, lcm);
return 0;
}
long gcd(long x, long y) {
if (x == 0) {
return y;
}
while (y != 0) {
if (x > y) {
x = x - y;
}
else {
y = y - x;
}
}
return x;
}
Decimal to binary conversion
C program to convert decimal to binary: c language code to convert an integer from decimal
number system(base-10) to binary number system(base-2). Size of integer is assumed to be 32
bits. We use bitwise operators to perform the desired task. We right shift the original number by
31, 30, 29, ..., 1, 0 bits using a loop and bitwise AND the number obtained with 1(one), if the
result is 1 then that bit is 1 otherwise it is 0(zero).
C programming code
#include <stdio.h>
int main()
{
int n, c, k;
printf("Enter an integer in decimal number systemn");
scanf("%d", &n);
printf("%d in binary number system is:n", n);
for (c = 31; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf("n");
return 0;
}
Download Decimal binary program.
Output of program:
Above code only prints binary of integer, but we may wish to perform operations on binary so in
the code below we are storing the binary in a string. We create a function which returns a pointer
to string which is the binary of the number passed as argument to the function.
C code to store decimal to binary conversion in a string
#include <stdio.h>
#include <stdlib.h>
char *decimal_to_binary(int);
main()
{
int n, c, k;
char *pointer;
printf("Enter an integer in decimal number systemn");
scanf("%d",&n);
pointer = decimal_to_binary(n);
printf("Binary string of %d is: %sn", n, t);
free(pointer);
return 0;
}
char *decimal_to_binary(int n)
{
int c, d, count;
char *pointer;
count = 0;
pointer = (char*)malloc(32+1);
if ( pointer == NULL )
exit(EXIT_FAILURE);
for ( c = 31 ; c >= 0 ; c-- )
{
d = n >> c;
if ( d & 1 )
*(pointer+count) = 1 + '0';
else
*(pointer+count) = 0 + '0';
count++;
}
*(pointer+count) = '0';
return pointer;
}
Memory is allocated dynamically because we can't return a pointer to a local variable (character
array in this case). If we return a pointer to local variable then program may crash or we get
incorrect result.
Factorial program in c
Factorial program in c: c code to find and print factorial of a number, three methods are given,
first one uses for loop, second uses a function to find factorial and third using recursion. Factorial
is represented using '!', so five factorial will be written as (5!), n factorial as (n!). Also
n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1.
Factorial program in c using for loop
Here we find factorial using for loop.
#include <stdio.h>
int main()
{
int c, n, fact = 1;
printf("Enter a number to calculate it's factorialn");
scanf("%d", &n);
for (c = 1; c <= n; c++)
fact = fact * c;
printf("Factorial of %d = %dn", n, fact);
return 0;
}
Download Factorial program.
Output of code:
Factorial program in c using function
#include <stdio.h>
long factorial(int);
int main()
{
int number;
long fact = 1;
printf("Enter a number to calculate it's factorialn");
scanf("%d", &number);
printf("%d! = %ldn", number, factorial(number));
return 0;
}
long factorial(int n)
{
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result * c;
return result;
}
Factorial program in c using recursion
#include<stdio.h>
long factorial(int);
int main()
{
int n;
long f;
printf("Enter an integer to find factorialn");
scanf("%d", &n);
if (n < 0)
printf("Negative integers are not allowed.n");
else
{
f = factorial(n);
printf("%d! = %ldn", n, f);
}
return 0;
}
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
Recursion is a technique in which a function calls itself, for example in above code factorial
function is calling itself. To solve a problem using recursion you must first express its solution in
recursive form.
C program to find ncr and npr
C program to find nCr and nPr: This code calculate nCr which is n!/(r!*(n-r)!) and nPr = n!/(n-r)!
C program to find nCr using function
#include <stdio.h>
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
int main()
{
int n, r;
long ncr, npr;
printf("Enter the value of n and rn");
scanf("%d%d",&n,&r);
ncr = find_ncr(n, r);
npr = find_npr(n, r);
printf("%dC%d = %ldn", n, r, ncr);
printf("%dP%d = %ldn", n, r, npr);
return 0;
}
long find_ncr(int n, int r) {
long result;
result = factorial(n)/(factorial(r)*factorial(n-r));
return result;
}
long find_npr(int n, int r) {
long result;
result = factorial(n)/factorial(n-r);
return result;
}
long factorial(int n) {
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
Download NCR and NPR program.
Output of program:
Another way to calculate nPr and nCr using functions
We use long long data type in our program to handle large numbers.
#include <stdio.h>
#define ll long long
void find_ncr_npr(int, int, ll*, ll*);
ll find_npr(int, int);
ll factorial(int);
int main() {
int n, r;
ll ncr, npr;
printf("Input n and rn");
scanf("%d%d", &n, &r);
find_ncr_npr(n, r, &npr, &ncr);
printf("%dC%d = %lldn", n, r, ncr);
printf("%dP%d = %lldn", n, r, npr);
return 0;
}
void find_ncr_npr(int n, int r, ll *npr, ll *ncr) {
*npr = find_npr(n, r);
*ncr = *npr/factorial(r);
}
ll find_npr(int n, int r) {
ll result = 1;
int c = 1;
while (c <= r) {
result = result * (n - r + c);
c++;
}
return result;
}
ll factorial(int n) {
int c;
ll result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
Add digits of number in c
C program to add digits of a number: Here we are using modulus operator(%) to extract
individual digits of number and adding them.
C programming code
#include <stdio.h>
int main()
{
int n, t, sum = 0, remainder;
printf("Enter an integern");
scanf("%d", &n);
t = n;
while (t != 0)
{
remainder = t % 10;
sum = sum + remainder;
t = t / 10;
}
printf("Sum of digits of %d = %dn", n, sum);
return 0;
}
If you wish you can modify input variable (n) and do not use an additional variable (t) but it is
not recommended.
Output of program:
For example if the input is 98, sum(variable) is 0 initially
98%10 = 8 (% is modulus operator which gives us remainder when 98 is divided by 10).
sum = sum + remainder
so sum = 8 now.
98/10 = 9 because in c whenever we divide integer by another integer we get an integer.
9%10 = 9
sum = 8(previous value) + 9
sum = 17
9/10 = 0.
So finally n = 0, loop ends we get the required sum.
Download Add digits program.
Find sum of digits in c without modulus operator
C program to find sum of digit of an integer which does not use modulus operator. Our program
uses a character array (string) for storing an integer. We convert every character of string into an
integer and add all these integers.
#include <stdio.h>
int main()
{
int c, sum, t;
char n[1000];
printf("Input an integern");
scanf("%s", n);
sum = c = 0;
while (n[c] != '0') {
t = n[c] - '0'; // Converting character to integer
sum = sum + t;
c++;
}
printf("Sum of digits of %s = %dn", n, sum);
return 0;
}
An advantage of this method is that input integer can be very large which may not be stored in
int or long long data type see an example below in output.
Output of program:
Input an integer
123456789123456789123456789
Sum of digits of 123456789123456789123456789 = 135
Add digits using recursion
#include <stdio.h>
int add_digits(int);
int main()
{
int n, result;
scanf("%d", &n);
result = add_digits(n);
printf("%dn", result);
return 0;
}
int add_digits(int n) {
static int sum = 0;
if (n == 0) {
return 0;
}
sum = n%10 + add_digits(n/10);
return sum;
}
Static variable sum is used and is initialized to 0, it' value will persists after function calls i.e. it is
initialized only once when a first call to function is made.
C program to add n numbers
This c program add n numbers which will be entered by the user. Firstly user will enter a number
indicating how many numbers user wishes to add and then user will enter n numbers. In the first
c program to add numbers we are not using an array, and using array in the second code.
C programming code
#include <stdio.h>
int main()
{
int n, sum = 0, c, value;
printf("Enter the number of integers you want to addn");
scanf("%d", &n);
printf("Enter %d integersn",n);
for (c = 1; c <= n; c++)
{
scanf("%d", &value);
sum = sum + value;
}
printf("Sum of entered integers = %dn",sum);
return 0;
}
You can use long int data type for sum variable.
Download Add n numbers program.
Output of program:
C programming code using array
#include <stdio.h>
int main()
{
int n, sum = 0, c, array[100];
scanf("%d", &n);
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
sum = sum + array[c];
}
printf("Sum = %dn",sum);
return 0;
}
The advantage of using array is that we have a record of numbers inputted by user and can use
them further in program if required and obviously storing numbers will require additional
memory.
Add n numbers using recursion
#include <stdio.h>
long calculateSum(int [], int);
int main()
{
int n, c, array[100];
long result;
scanf("%d", &n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
result = calculateSum(array, n);
printf("Sum = %ldn", result);
return 0;
}
long calculateSum(int a[], int n) {
static long sum = 0;
if (n == 0)
return sum;
sum = sum + a[n-1];
return calculateSum(a, --n);
}
C program to swap two numbers
C program to swap two numbers with and without using third variable, swapping in c using
pointers, functions (Call by reference) and using bitwise XOR operator, swapping means
interchanging. For example if in your c program you have taken two variable a and b where a = 4
and b = 5, then before swapping a = 4, b = 5 after swapping a = 5, b = 4
In our c program to swap numbers we will use a temp variable to swap two numbers.
Swapping of two numbers in c
#include <stdio.h>
int main()
{
int x, y, temp;
printf("Enter the value of x and yn");
scanf("%d%d", &x, &y);
printf("Before Swappingnx = %dny = %dn",x,y);
temp = x;
x = y;
y = temp;
printf("After Swappingnx = %dny = %dn",x,y);
return 0;
}
Download Swap numbers program.
Output of program:
Swapping of two numbers without third variable
You can also swap two numbers without using temp or temporary or third variable. In that case c
program will be as shown :-
#include <stdio.h>
int main()
{
int a, b;
printf("Enter two integers to swapn");
scanf("%d%d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("a = %dnb = %dn",a,b);
return 0;
}
To understand above logic simply choose a as 7 and b as 9 and then do what is written in
program. You can choose any other combination of numbers as well. Sometimes it's a good way
to understand a program.
Swap two numbers using pointers
#include <stdio.h>
int main()
{
int x, y, *a, *b, temp;
printf("Enter the value of x and yn");
scanf("%d%d", &x, &y);
printf("Before Swappingnx = %dny = %dn", x, y);
a = &x;
b = &y;
temp = *b;
*b = *a;
*a = temp;
printf("After Swappingnx = %dny = %dn", x, y);
return 0;
}
Swapping numbers using call by reference
In this method we will make a function to swap numbers.
#include <stdio.h>
void swap(int*, int*);
int main()
{
int x, y;
printf("Enter the value of x and yn");
scanf("%d%d",&x,&y);
printf("Before Swappingnx = %dny = %dn", x, y);
swap(&x, &y);
printf("After Swappingnx = %dny = %dn", x, y);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *b;
*b = *a;
*a = temp;
}
C programming code to swap using bitwise XOR
#include <stdio.h>
int main()
{
int x, y;
scanf("%d%d", &x, &y);
printf("x = %dny = %dn", x, y);
x = x ^ y;
y = x ^ y;
x = x ^ y;
printf("x = %dny = %dn", x, y);
return 0;
}
Swapping is used in sorting algorithms that is when we wish to arrange numbers in a particular
order either in ascending order or in descending.
C program to reverse a number
C Program to reverse a number :- This program reverse the number entered by the user and then
prints the reversed number on the screen. For example if user enter 123 as input then 321 is
printed as output. In our program we use modulus(%) operator to obtain the digits of a number.
To invert number look at it and write it from opposite direction or the output of code is a number
obtained by writing original number from right to left. To reverse or invert large numbers use
long data type or long long data type if your compiler supports it, if you still have large numbers
then use strings or other data structure.
C programming code
#include <stdio.h>
int main()
{
int n, reverse = 0;
printf("Enter a number to reversen");
scanf("%d", &n);
while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
printf("Reverse of entered number is = %dn", reverse);
return 0;
}
Download Reverse number program.
Output of program:
C program to reverse number using recursion
#include <stdio.h>
long reverse(long);
int main()
{
long n, r;
scanf("%ld", &n);
r = reverse(n);
printf("%ldn", r);
return 0;
}
long reverse(long n) {
static long r = 0;
if (n == 0)
return 0;
r = r * 10;
r = r + n % 10;
reverse(n/10);
return r;
}
Palindrome Numbers
Palindrome number in c: A palindrome number is a number such that if we reverse it, it will not
change. For example some palindrome numbers examples are 121, 212, 12321, -454. To check
whether a number is palindrome or not first we reverse it and then compare the number obtained
with the original, if both are same then number is palindrome otherwise not. C program for
palindrome number is given below.
Palindrome number algorithm
1. Get the number from user.
2. Reverse it.
3. Compare it with the number entered by the user.
4. If both are same then print palindrome number
5. Else print not a palindrome number.
Palindrome number program c
#include <stdio.h>
int main()
{
int n, reverse = 0, temp;
printf("Enter a number to check if it is a palindrome or notn");
scanf("%d",&n);
temp = n;
while( temp != 0 )
{
reverse = reverse * 10;
reverse = reverse + temp%10;
temp = temp/10;
}
if ( n == reverse )
printf("%d is a palindrome number.n", n);
else
printf("%d is not a palindrome number.n", n);
return 0;
}
Download Palindrome number program.
Output of program:
C program to print patterns of numbers and stars
These program prints various different patterns of numbers and stars. These codes illustrate how
to create various patterns using c programming. Most of these c programs involve usage of
nested loops and space. A pattern of numbers, star or characters is a way of arranging these in
some logical manner or they may form a sequence. Some of these patterns are triangles which
have special importance in mathematics. Some patterns are symmetrical while other are not.
Please see the complete page and look at comments for many different patterns.
*
***
*****
*******
*********
We have shown five rows above, in the program you will be asked to enter the numbers of rows
you want to print in the pyramid of stars.
C programming code
#include <stdio.h>
int main()
{
int row, c, n, temp;
printf("Enter the number of rows in pyramid of stars you wish to see ");
scanf("%d",&n);
temp = n;
for ( row = 1 ; row <= n ; row++ )
{
for ( c = 1 ; c < temp ; c++ )
printf(" ");
temp--;
for ( c = 1 ; c <= 2*row - 1 ; c++ )
printf("*");
printf("n");
}
return 0;
}
Download Stars pyramid program.
Output of program:
For more patterns or shapes on numbers and characters see comments below and also see codes
on following pages:
Floyd triangle
Pascal triangle
Consider the pattern
*
**
***
****
*****
to print above pattern see the code below:
#include <stdio.h>
int main()
{
int n, c, k;
printf("Enter number of rowsn");
scanf("%d",&n);
for ( c = 1 ; c <= n ; c++ )
{
for( k = 1 ; k <= c ; k++ )
printf("*");
printf("n");
}
return 0;
}
Using these examples you are in a better position to create your desired pattern for yourself.
Creating a pattern involves how to use nested loops properly, some pattern may involve
alphabets or other special characters. Key aspect is knowing how the characters in pattern
changes.
C pattern programs
Pattern:
*
*A*
*A*A*
*A*A*A*
C pattern program of stars and alphabets:
#include<stdio.h>
main()
{
int n, c, k, space, count = 1;
printf("Enter number of rowsn");
scanf("%d",&n);
space = n;
for ( c = 1 ; c <= n ; c++)
{
for( k = 1 ; k < space ; k++)
printf(" ");
for ( k = 1 ; k <= c ; k++)
{
printf("*");
if ( c > 1 && count < c)
{
printf("A");
count++;
}
}
printf("n");
space--;
count = 1;
}
return 0;
}
Pattern:
1
232
34543
4567654
567898765
C program:
#include<stdio.h>
main()
{
int n, c, d, num = 1, space;
scanf("%d",&n);
space = n - 1;
for ( d = 1 ; d <= n ; d++ )
{
num = d;
for ( c = 1 ; c <= space ; c++ )
printf(" ");
space--;
for ( c = 1 ; c <= d ; c++ )
{
printf("%d", num);
num++;
}
num--;
num--;
for ( c = 1 ; c < d ; c++)
{
printf("%d", num);
num--;
}
printf("n");
}
return 0;
}
C program to print diamond pattern
Diamond pattern in c: This code print diamond pattern of stars. Diamond shape is as follows:
*
***
*****
***
*
C programming code
#include <stdio.h>
int main()
{
int n, c, k, space = 1;
printf("Enter number of rowsn");
scanf("%d", &n);
space = n - 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space--;
for (c = 1; c <= 2*k-1; c++)
printf("*");
printf("n");
}
space = 1;
for (k = 1; k <= n - 1; k++)
{
for (c = 1; c <= space; c++)
printf(" ");
space++;
for (c = 1 ; c <= 2*(n-k)-1; c++)
printf("*");
printf("n");
}
return 0;
}
Download Diamond program.
Output of program:
C program to print diamond using recursion
#include <stdio.h>
void print (int);
int main () {
int rows;
scanf("%d", &rows);
print(rows);
return 0;
}
void print (int r) {
int c, space;
static int stars = -1;
if (r <= 0)
return;
space = r - 1;
stars += 2;
for (c = 0; c < space; c++)
printf(" ");
for (c = 0; c < stars; c++)
printf("*");
printf("n");
print(--r);
space = r + 1;
stars -= 2;
for (c = 0; c < space; c++)
printf(" ");
for (c = 0; c < stars; c++)
printf("*");
printf("n");
}
C program for prime number
Prime number program in c: c program for prime number, this code prints prime numbers using c
programming language. To check whether a number is prime or not see another code below.
Prime number logic: a number is prime if it is divisible only by one and itself. Remember two is
the only even and also the smallest prime number. First few prime numbers are 2, 3, 5, 7, 11, 13,
17....etc. Prime numbers have many applications in computer science and mathematics. A
number greater than one can be factorized into prime numbers, For example 540 = 22*33*51
Prime number program in c language
#include<stdio.h>
int main()
{
int n, i = 3, count, c;
printf("Enter the number of prime numbers requiredn");
scanf("%d",&n);
if ( n >= 1 )
{
printf("First %d prime numbers are :n",n);
printf("2n");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%dn",i);
count++;
}
i++;
}
return 0;
}
Download Prime number program.
Output of program:
C program for prime number or not
#include<stdio.h>
main()
{
int n, c = 2;
printf("Enter a number to check if it is primen");
scanf("%d",&n);
for ( c = 2 ; c <= n - 1 ; c++ )
{
if ( n%c == 0 )
{
printf("%d is not prime.n", n);
break;
}
}
if ( c == n )
printf("%d is prime.n", n);
return 0;
}
C program for prime number using function
#include<stdio.h>
int check_prime(int);
main()
{
int n, result;
printf("Enter an integer to check whether it is prime or not.n");
scanf("%d",&n);
result = check_prime(n);
if ( result == 1 )
printf("%d is prime.n", n);
else
printf("%d is not prime.n", n);
return 0;
}
int check_prime(int a)
{
int c;
for ( c = 2 ; c <= a - 1 ; c++ )
{
if ( a%c == 0 )
return 0;
}
if ( c == a )
return 1;
}
There are many logic to check prime numbers, one given below is more efficient then above
method.
for ( c = 2 ; c <= (int)sqrt(n) ; c++ )
Only checking from 2 to square root of number is sufficient.
There are many more efficient logic available.
Armstrong number c program
Armstrong number c program: c programming code to check whether a number is Armstrong or
not. Armstrong number is a number which is equal to sum of digits raise to the power total
number of digits in the number. Some Armstrong numbers are: 0, 1, 2, 3, 153, 370, 407, 1634,
8208 etc. Read more about Armstrong numbers at Wikipedia. We will consider base 10 numbers
in our program. Algorithm to check Armstrong is: First we calculate number of digits in our
program and then compute sum of individual digits raise to the power number of digits. If this
sum equals input number then number is Armstrong otherwise not an Armstrong number.
Examples:
7 = 7^1
371 = 3^3 + 7^3 + 1^3 (27 + 343 +1)
8208 = 8^4 + 2^4 +0^4 + 8^4 (4096 + 16 + 0 + 4096).
1741725 = 1^7 + 7^7 + 4^7 + 1^7 + 7^7 + 2^7 +5^7 (1 + 823543 + 16384 + 1 + 823543 +128 +
78125)
C programming code
#include <stdio.h>
int power(int, int);
int main()
{
int n, sum = 0, temp, remainder, digits = 0;
printf("Input an integern");
scanf("%d", &n);
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
printf("%d is an Armstrong number.n", n);
else
printf("%d is not an Armstrong number.n", n);
return 0;
}
int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
Download Check Armstrong number program.
Output of program:
C program to check Armstrong number using function
We will use long long data type in our program so that we can check numbers up to 2^64-1.
#include <stdio.h>
int check_armstrong(long long);
long long power(int, int);
int main () {
long long n;
printf("Input a numbern");
scanf("%lld", &n);
if (check_armstrong(n) == 1)
printf("%lld is an armstrong number.n", n);
else
printf("%lld is not an armstrong number.n", n);
return 0;
}
int check_armstrong(long long n) {
long long sum = 0, temp;
int remainder, digits = 0;
temp = n;
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
return 1;
else
return 0;
}
long long power(int n, int r) {
int c;
long long p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
Output of program:
Input a number
35641594208964132
35641594208964132 is an Armstrong number.
C program to generate and print armstrong numbers
C program to generate Armstrong numbers. In our program user will input two integers and we
will print all Armstrong numbers between two integers. Using a for loop we will check numbers
in the desired range. In our loop we call our function check_armstrong which returns 1 if number
is Armstrong and 0 otherwise. If you are not familiar with Armstrong numbers see Check
Armstrong number program.
C programming code
#include <stdio.h>
int check_armstrong(int);
int power(int, int);
int main () {
int c, a, b;
printf("Input two integersn");
scanf("%d%d", &a, &b);
for (c = a; c <= b; c++) {
if (check_armstrong(c) == 1)
printf("%dn", c);
}
return 0;
}
int check_armstrong(int n) {
long long sum = 0, temp;
int remainder, digits = 0;
temp = n;
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
return 1;
else
return 0;
}
int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
Download Generate Armstrong numbers program.
Output of program:
In the sample output we are printing Armstrong numbers in range [0, 1000000].
Fibonacci series inc
Fibonacci series in c programming: c program for Fibonacci series without and with recursion.
Using the code below you can print as many numbers of terms of series as desired. Numbers of
Fibonacci sequence are known as Fibonacci numbers. First few numbers of series are 0, 1, 1, 2,
3, 5, 8 etc, Except first two terms in sequence every other term is the sum of two previous terms,
For example 8 = 3 + 5 (addition of 3, 5). This sequence has many applications in mathematics
and Computer Science.
Fibonacci series in c using for loop
/* Fibonacci Series c language */
#include<stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;
printf("Enter the number of termsn");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are :-n",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%dn",next);
}
return 0;
}
Output of program:
Fibonacci series program in c using recursion
#include<stdio.h>
int Fibonacci(int);
main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci seriesn");
for ( c = 1 ; c <= n ; c++ )
{
printf("%dn", Fibonacci(i));
i++;
}
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
Recursion method is less efficient as it involves function calls which uses stack, also there are
chances of stack overflow if function is called frequently for calculating larger Fibonacci
numbers.
C program to print Floyd's triangle
C program to print Floyd's triangle:- This program prints Floyd's triangle. Number of rows of
Floyd's triangle to print is entered by the user. First four rows of Floyd's triangle are as follows :-
1
2 3
4 5 6
7 8 9 10
It's clear that in Floyd's triangle nth row contains n numbers.
C programming code
#include <stdio.h>
int main()
{
int n, i, c, a = 1;
printf("Enter the number of rows of Floyd's triangle to printn");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
for (c = 1; c <= i; c++)
{
printf("%d ",a);
a++;
}
printf("n");
}
return 0;
}
Download Floyd triangle program.
Output of program:
C program to print Floyd's triangle using recursion
#include <stdio.h>
void print_floyd(int);
int main()
{
int n, i, c, a = 1;
printf("Input number of rows of Floyd's triangle to printn");
scanf("%d", &n);
print_floyd(n);
return 0;
}
void print_floyd(int n) {
static int row = 1, c = 1;
int d;
if (n <= 0)
return;
for (d = 1; d <= row; ++d)
printf("%d ", c++);
printf("n");
row++;
print_floyd(--n);
}
C program to print Pascal triangle
Pascal Triangle in c: C program to print Pascal triangle which you might have studied in
Binomial Theorem in Mathematics. Number of rows of Pascal triangle to print is entered by the
user. First four rows of Pascal triangle are shown below :-
1
1 1
1 2 1
1 3 3 1
Pascal triangle in c
#include <stdio.h>
long factorial(int);
int main()
{
int i, n, c;
printf("Enter the number of rows you wish to see in pascal trianglen");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
for (c = 0; c <= (n - i - 2); c++)
printf(" ");
for (c = 0 ; c <= i; c++)
printf("%ld ",factorial(i)/(factorial(c)*factorial(i-c)));
printf("n");
}
return 0;
}
long factorial(int n)
{
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}
Download Pascal triangle program.
Output of program:
C program to find maximum element in array
This code find maximum or largest element present in an array. It also prints the location or
index at which maximum element occurs in array. This can also be done by using pointers (see
both codes). The algorithm to find maximum is first we assume that maximum element occurs at
beginning of array and stores that value in a variable. Then we compare it with other array
elements one by one, if any element is greater than our assumed maximum then maximum value
and index at which it occurs is updated. Similarly we can find minimum element in an array.
C programming code
#include <stdio.h>
int main()
{
int array[100], maximum, size, c, location = 1;
printf("Enter the number of elements in arrayn");
scanf("%d", &size);
printf("Enter %d integersn", size);
for (c = 0; c < size; c++)
scanf("%d", &array[c]);
maximum = array[0];
for (c = 1; c < size; c++)
{
if (array[c] > maximum)
{
maximum = array[c];
location = c+1;
}
}
printf("Maximum element is present at location %d and it's value is %d.n",
location, maximum);
return 0;
}
If maximum occurs two or more times times in array then index at which it occurs first is printed
or maximum value at smallest index. You can easily modify this code this code to print largest
index at which maximum occur. You can also store all indices at which maximum occur in an
array.
Download Maximum element in array program.
Output of program:
C programming code to find maximum using function
Our function returns index at which maximum element occur.
#include <stdio.h>
int find_maximum(int[], int);
int main() {
int c, array[100], size, location, maximum;
printf("Input number of elements in arrayn");
scanf("%d", &size);
printf("Enter %d integersn", size);
for (c = 0; c < size; c++)
scanf("%d", &array[c]);
location = find_maximum(array, size);
maximum = array[location];
printf("Maximum element location = %d and value = %d.n", location + 1,
maximum);
return 0;
}
int find_maximum(int a[], int n) {
int c, max, index;
max = a[0];
index = 0;
for (c = 1; c < n; c++) {
if (a[c] > max) {
index = c;
max = a[c];
}
}
return index;
}
C programming code using pointers
#include <stdio.h>
int main()
{
long array[100], *maximum, size, c, location = 1;
printf("Enter the number of elements in arrayn");
scanf("%ld", &size);
printf("Enter %ld integersn", size);
for ( c = 0 ; c < size ; c++ )
scanf("%ld", &array[c]);
maximum = array;
*maximum = *array;
for (c = 1; c < size; c++)
{
if (*(array+c) > *maximum)
{
*maximum = *(array+c);
location = c+1;
}
}
printf("Maximum element found at location %ld and it's value is %ld.n",
location, *maximum);
return 0;
}
The complexity of above code is O(n) as the time used depends on the size of input array or in
other words time to find maximum increases linearly as array size grows.
C program to find minimum element in array
C code to find minimum or smallest element present in an array. It also prints the location or
index at which minimum element occurs in array. This can also be done by using pointers (see
both the codes). Our algorithm first assumes first element as minimum and then compare it with
other elements if an element is smaller than it then it becomes the new minimum and this process
is repeated till complete array is scanned.
C programming code
#include <stdio.h>
int main()
{
int array[100], minimum, size, c, location = 1;
printf("Enter the number of elements in arrayn");
scanf("%d",&size);
printf("Enter %d integersn", size);
for ( c = 0 ; c < size ; c++ )
scanf("%d", &array[c]);
minimum = array[0];
for ( c = 1 ; c < size ; c++ )
{
if ( array[c] < minimum )
{
minimum = array[c];
location = c+1;
}
}
printf("Minimum element is present at location %d and it's value is
%d.n", location, minimum);
return 0;
}
If minimum occurs two or more times times in array then index at which it occurs first is printed
or minimum value at smallest index. You can modify this code this code to print largest index at
which minimum occur. You can also store all indices at which minimum occur in an array.
Download Minimum element in array program.
Output of program:
C programming code to find minimum using function
Our function returns index at which minimum element occur.
#include <stdio.h>
int find_minimum(int[], int);
int main() {
int c, array[100], size, location, minimum;
printf("Input number of elements in arrayn");
scanf("%d", &size);
printf("Input %d integersn", size);
for (c = 0; c < size; c++)
scanf("%d", &array[c]);
location = find_minimum(array, size);
minimum = array[location];
printf("Minimum element location = %d and value = %d.n", location + 1,
minimum);
return 0;
}
int find_minimum(int a[], int n) {
int c, min, index;
min = a[0];
index = 0;
for (c = 1; c < n; c++) {
if (a[c] < min) {
index = c;
min = a[c];
}
}
return index;
}
C programming code using pointers
#include <stdio.h>
int main()
{
int array[100], *minimum, size, c, location = 1;
printf("Enter the number of elements in arrayn");
scanf("%d",&size);
printf("Enter %d integersn", size);
for ( c = 0 ; c < size ; c++ )
scanf("%d", &array[c]);
minimum = array;
*minimum = *array;
for ( c = 1 ; c < size ; c++ )
{
if ( *(array+c) < *minimum )
{
*minimum = *(array+c);
location = c+1;
}
}
printf("Minimum element found at location %d and it's value is %d.n",
location, *minimum);
return 0;
}
C program to insert an element in an array
This code will insert an element into an array, For example consider an array a[10] having three
elements in it initially and a[0] = 1, a[1] = 2 and a[2] = 3 and you want to insert a number 45 at
location 1 i.e. a[0] = 45, so we have to move elements one step below so after insertion a[1] = 1
which was a[0] initially, and a[2] = 2 and a[3] = 3. Array insertion does not mean increasing its
size i.e array will not be containing 11 elements.
C programming code
#include <stdio.h>
int main()
{
int array[100], position, c, n, value;
printf("Enter number of elements in arrayn");
scanf("%d", &n);
printf("Enter %d elementsn", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the location where you wish to insert an elementn");
scanf("%d", &position);
printf("Enter the value to insertn");
scanf("%d", &value);
for (c = n - 1; c >= position - 1; c--)
array[c+1] = array[c];
array[position-1] = value;
printf("Resultant array isn");
for (c = 0; c <= n; c++)
printf("%dn", array[c]);
return 0;
}
Download Insert element in array program.
Output of program:
C program to delete an element from an array
This program delete an element from an array. Deleting an element does not affect the size of
array. It is also checked whether deletion is possible or not, For example if array is containing
five elements and you want to delete element at position six which is not possible.
C programming code
#include <stdio.h>
int main()
{
int array[100], position, c, n;
printf("Enter number of elements in arrayn");
scanf("%d", &n);
printf("Enter %d elementsn", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d", &array[c]);
printf("Enter the location where you wish to delete elementn");
scanf("%d", &position);
if ( position >= n+1 )
printf("Deletion not possible.n");
else
{
for ( c = position - 1 ; c < n - 1 ; c++ )
array[c] = array[c+1];
printf("Resultant array isn");
for( c = 0 ; c < n - 1 ; c++ )
printf("%dn", array[c]);
}
return 0;
}
Download Delete element from array program.
Output of program:
C program to merge two arrays
C program to merge two arrays into third array: Arrays are assumed to be sorted in ascending
order. You enter two short sorted arrays and combine them to get a large array.
C programming code to merge two sorted arrays
#include <stdio.h>
void merge(int [], int, int [], int, int []);
int main() {
int a[100], b[100], m, n, c, sorted[200];
printf("Input number of elements in first arrayn");
scanf("%d", &m);
printf("Input %d integersn", m);
for (c = 0; c < m; c++) {
scanf("%d", &a[c]);
}
printf("Input number of elements in second arrayn");
scanf("%d", &n);
printf("Input %d integersn", n);
for (c = 0; c < n; c++) {
scanf("%d", &b[c]);
}
merge(a, m, b, n, sorted);
printf("Sorted array:n");
for (c = 0; c < m + n; c++) {
printf("%dn", sorted[c]);
}
return 0;
}
void merge(int a[], int m, int b[], int n, int sorted[]) {
int i, j, k;
j = k = 0;
for (i = 0; i < m + n;) {
if (j < m && k < n) {
if (a[j] < b[k]) {
sorted[i] = a[j];
j++;
}
else {
sorted[i] = b[k];
k++;
}
i++;
}
else if (j == m) {
for (; i < m + n;) {
sorted[i] = b[k];
k++;
i++;
}
}
else {
for (; i < m + n;) {
sorted[i] = a[j];
j++;
i++;
}
}
}
}
Download Merge arrays program.
Output of program:
If the arrays are not sorted then you can sort them first and then use the above merge function,
another method is to merge them and then sort the array. Sorting two smaller arrays will take less
time as compared to sorting a big array. Merging two sorted array is used in merge sort
algorithm.
C program to reverse an array
C program to reverse an array: This program reverses the array elements. For example if a is an
array of integers with three elements such that
a[0] = 1
a[1] = 2
a[2] = 3
Then on reversing the array will be
a[0] = 3
a[1] = 2
a[0] = 1
Given below is the c code to reverse an array.
C programming code
#include <stdio.h>
int main()
{
int n, c, d, a[100], b[100];
printf("Enter the number of elements in arrayn");
scanf("%d", &n);
printf("Enter the array elementsn");
for (c = 0; c < n ; c++)
scanf("%d", &a[c]);
/*
* Copying elements into array b starting from end of array a
*/
for (c = n - 1, d = 0; c >= 0; c--, d++)
b[d] = a[c];
/*
* Copying reversed array into original.
* Here we are modifying original array, this is optional.
*/
for (c = 0; c < n; c++)
a[c] = b[c];
printf("Reverse array isn");
for (c = 0; c < n; c++)
printf("%dn", a[c]);
return 0;
}
Download Reverse array program.
Output of program:
Reverse array by swapping (without using additional
memory)
#include <stdio.h>
int main() {
int array[100], n, c, t, end;
scanf("%d", &n);
end = n - 1;
for (c = 0; c < n; c++) {
scanf("%d", &array[c]);
}
for (c = 0; c < n/2; c++) {
t = array[c];
array[c] = array[end];
array[end] = t;
end--;
}
printf("Reversed array elements are:n");
for (c = 0; c < n; c++) {
printf("%dn", array[c]);
}
return 0;
}
C program to reverse an array using pointers
#include <stdio.h>
#include <stdlib.h>
void reverse_array(int*, int);
int main()
{
int n, c, *pointer;
scanf("%d",&n);
pointer = (int*)malloc(sizeof(int)*n);
if( pointer == NULL )
exit(EXIT_FAILURE);
for ( c = 0 ; c < n ; c++ )
scanf("%d",(pointer+c));
reverse_array(pointer, n);
printf("Original array on reversal isn");
for ( c = 0 ; c < n ; c++ )
printf("%dn",*(pointer+c));
free(pointer);
return 0;
}
void reverse_array(int *pointer, int n)
{
int *s, c, d;
s = (int*)malloc(sizeof(int)*n);
if( s == NULL )
exit(EXIT_FAILURE);
for ( c = n - 1, d = 0 ; c >= 0 ; c--, d++ )
*(s+d) = *(pointer+c);
for ( c = 0 ; c < n ; c++ )
*(pointer+c) = *(s+c);
free(s);
}
Array is passed to function and a new array is created and contents of passed array (in reverse
order) are copied into it and finally contents of new array are copied into array passed to
function.
C program to add two matrix
This c program add two matrices i.e. compute the sum of two matrices and then print it. Firstly
user will be asked to enter the order of matrix (number of rows and columns) and then two
matrices. For example if the user entered order as 2, 2 i.e. two rows and two columns and
matrices as
First Matrix :-
1 2
3 4
Second matrix :-
4 5
-1 5
then output of the program (sum of First and Second matrix) will be
5 7
2 9
C programming code
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrixn");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrixn");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrixn");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-n");
for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%dt", sum[c][d]);
}
printf("n");
}
return 0;
}
Download Add Matrix program.
Output of program:
Subtract matrices
C code to subtract matrices of any order. This program finds difference between corresponding
elements of two matrices and then print the resultant matrix.
C programming code
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], difference[10][10];
printf("Enter the number of rows and columns of matrixn");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrixn");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrixn");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &second[c][d]);
printf("Difference of entered matrices:-n");
for (c = 0; c < m; c++) {
for (d = 0; d < n; d++) {
difference[c][d] = first[c][d] - second[c][d];
printf("%dt",difference[c][d]);
}
printf("n");
}
return 0;
}
Download Subtract matrices program.
Output of program:
C program to transpose a matrix
This c program prints transpose of a matrix. It is obtained by interchanging rows and columns of
a matrix. For example if a matrix is
1 2
3 4
5 6
then transpose of above matrix will be
1 3 5
2 4 6
When we transpose a matrix then the order of matrix changes, but for a square matrix order
remains same.
C programming code
#include <stdio.h>
int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
printf("Enter the number of rows and columns of matrixn");
scanf("%d%d", &m, &n);
printf("Enter the elements of matrixn");
for (c = 0; c < m; c++)
for(d = 0; d < n; d++)
scanf("%d",&matrix[c][d]);
for (c = 0; c < m; c++)
for( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];
printf("Transpose of entered matrix :-n");
for (c = 0; c < n; c++) {
for (d = 0; d < m; d++)
printf("%dt",transpose[c][d]);
printf("n");
}
return 0;
}
Download Transpose Matrix program.
Output of program:
Matrix multiplicationin c
Matrix multiplication in c language: c program to multiply matrices (two dimensional array), this
program multiplies two matrices which will be entered by the user. Firstly user will enter the
order of a matrix. If the entered orders of two matrix is such that they can't be multiplied then an
error message is displayed on the screen. You have already studied the logic to multiply them in
Mathematics.
Matrix multiplication in c language
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter the number of rows and columns of first matrixn");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrixn");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the number of rows and columns of second matrixn");
scanf("%d%d", &p, &q);
if (n != p)
printf("Matrices with entered orders can't be multiplied with each
other.n");
else
{
printf("Enter the elements of second matrixn");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of entered matrices:-n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%dt", multiply[c][d]);
printf("n");
}
}
return 0;
}
Download Matrix multiplication program.
A 3 X 3 matrix multiply in c is shown as example below.
Matrices are frequently used while doing programming and are used to represent graph data
structure, in solving system of linear equations and many more. Lot of research is being done on
how to multiply matrices using minimum number of operations. You can also implement it using
pointers.
C program print string
This program print a string. String can be printed by using various functions such as printf, puts.
C programming code
#include <stdio.h>
int main()
{
char array[20] = "Hello World";
printf("%sn",array);
return 0;
}
To input a string we use scanf function.
C programming code
#include <stdio.h>
int main()
{
char array[100];
printf("Enter a stringn");
scanf("%s", array);
printf("You entered the string %sn",array);
return 0;
}
Input stringcontainingspaces
#include <stdio.h>
int main()
{
char a[80];
gets(a);
printf("%sn", a);
return 0;
}
Note that scanf can only input single word strings, to receive strings containing spaces use gets
function.
C programto print stringusingrecursion
#include <stdio.h>
void print(char*);
int main() {
char s[100];
gets(s);
print(s);
return 0;
}
void print(char *t) {
if (*t == '0')
return;
printf("%c", *t);
print(++t);
}
Print stringusingloop
We print string using for loop by printing individual characters of string.
#include <stdio.h>
#include <string.h>
int main() {
char s[100];
int c, l;
gets(s);
l = strlen(s);
for (c = 0; c < l; c++)
printf("%c", s[c]);
return 0;
}
String length
This program prints length of string, for example consider the string "c programming" it's length
is 13. Null character is not counted when calculating string length. To find string length we use
strlen function of string.h.
C program to find string length
#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
int length;
printf("Enter a string to calculate it's lengthn");
gets(a);
length = strlen(a);
printf("Length of entered string is = %dn",length);
return 0;
}
Download String length program.
Output of program:
C program to find string length without strlen
You can also find string length without strlen function. We create our own function to find string
length.
#include <stdio.h>
int string_length(char []);
int main()
{
char s[1000];
int length;
printf("Input a stringn");
gets(s);
length = string_length(s);
printf("Length of "%s" = %dn", s, length);
return 0;
}
int string_length(char s[]) {
int c = 0;
while (s[c] != '0')
c++;
return c;
}
Function to find string length using pointers
int string_length(char *s) {
int c = 0;
while(*(s+c))
c++;
return c;
}
C program to compare two strings
This c program compares two strings using strcmp, without strcmp and using pointers. For
comparing strings without using library function see another code below.
C program to compare two strings using strcmp
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
printf("Enter the first stringn");
gets(a);
printf("Enter the second stringn");
gets(b);
if (strcmp(a,b) == 0)
printf("Entered strings are equal.n");
else
printf("Entered strings are not equal.n");
return 0;
}
Function strcmp is case sensitive and returns 0 if both strings are equal.
Download Compare Strings program.
Output of program:
C program to compare two strings without using strcmp
Here we create our own function to compare strings.
#include <stdio.h>
int compare_strings(char [], char []);
int main()
{
int flag;
char a[1000], b[1000];
printf("Input first stringn");
gets(a);
printf("Input second stringn");
gets(b);
flag = compare_strings(a, b);
if (flag == 0)
printf("Entered strings are equal.n");
else
printf("Entered strings are not equal.n");
return 0;
}
int compare_strings(char a[], char b[])
{
int c = 0;
while (a[c] == b[c]) {
if (a[c] == '0' || b[c] == '0')
break;
c++;
}
if (a[c] == '0' && b[c] == '0')
return 0;
else
return -1;
}
C program to compare two strings using pointers
In this method we will make our own function to perform string comparison, we will use
character pointers in our function to manipulate string.
#include<stdio.h>
int compare_string(char*, char*);
int main()
{
char first[1000], second[1000], result;
printf("Input first stringn");
gets(first);
printf("Input second stringn");
gets(second);
result = compare_string(first, second);
if (result == 0)
printf("Both strings are same.n");
else
printf("Entered strings are not equal.n");
return 0;
}
int compare_string(char *first, char *second) {
while (*first == *second) {
if (*first == '0' || *second == '0')
break;
first++;
second++;
}
if (*first == '0' && *second == '0')
return 0;
else
return -1;
}
String copying in c programming
This program copy string using library function strcpy, to copy string without using strcpy see
source code below in which we have made our own function to copy string.
C program to copy a string
#include <stdio.h>
#include <string.h>
int main()
{
char source[1000], destination[1000];
printf("Input a stringn");
gets(source);
strcpy(destination, source);
printf("Source string: "%s"n", source);
printf("Destination string: "%s"n", destination);
return 0;
}
Output of program:
C program to copy string without using strcpy
We create our own function to copy string and do not use the library function strcpy.
#include <stdio.h>
#include <string.h>
void copy_string(char [], char []);
int main() {
char s[1000], d[1000];
printf("Input a stringn");
gets(s);
copy_string(d, s);
printf("Source string: "%s"n", s);
printf("Destination string: "%s"n", d);
return 0;
}
void copy_string(char d[], char s[]) {
int c = 0;
while (s[c] != '0') {
d[c] = s[c];
c++;
}
d[c] = '0';
}
C program to copy a string using pointers
Function to copy string using pointers.
void copy_string(char *target, char *source) {
while (*source) {
*target = *source;
source++;
target++;
}
*target = '0';
}
C program to concatenate strings
This program concatenates strings, for example if the first string is "c " and second string is
"program" then on concatenating these two strings we get the string "c program". To concatenate
two strings we use strcat function of string.h, to concatenate without using library function see
another code below which uses pointers.
C programming code
#include <stdio.h>
#include <string.h>
int main()
{
char a[1000], b[1000];
printf("Enter the first stringn");
gets(a);
printf("Enter the second stringn");
gets(b);
strcat(a,b);
printf("String obtained on concatenation is %sn",a);
return 0;
}
Download String Concatenation program.
Output of program:
Concatenate strings without strcat function
C program to concatenate strings without using library function strcat of string.h header file. We
create our own function.
#include <stdio.h>
void concatenate(char [], char []);
int main()
{
char p[100], q[100];
printf("Input a stringn");
gets(p);
printf("Input a string to concatenaten");
gets(q);
concatenate(p, q);
printf("String obtained on concatenation is "%s"n", p);
return 0;
}
void concatenate(char p[], char q[]) {
int c, d;
c = 0;
while (p[c] != '0') {
c++;
}
d = 0;
while (q[d] != '0') {
p[c] = q[d];
d++;
c++;
}
p[c] = '0';
}
The first for loop in concatenate function is calculating string length so you can also use strlen
function if you wish.
String concatenation using pointers
#include <stdio.h>
void concatenate_string(char*, char*);
int main()
{
char original[100], add[100];
printf("Enter source stringn");
gets(original);
printf("Enter string to concatenaten");
gets(add);
concatenate_string(original, add);
printf("String after concatenation is "%s"n", original);
return 0;
}
void concatenate_string(char *original, char *add)
{
while(*original)
original++;
while(*add)
{
*original = *add;
add++;
original++;
}
*original = '0';
}
Reverse string
This program reverses a string entered by the user. For example if a user enters a string "reverse
me" then on reversing the string will be "em esrever". We show you four different methods to
reverse string the first one uses strrev library function of string.h header file, second without
using strrev and in third we make our own function to reverse string using pointers, reverse
string using recursion and Reverse words in string. If you are using first method then you must
include string.h in your program.
C programming code
/* String reverse in c*/
#include <stdio.h>
#include <string.h>
int main()
{
char arr[100];
printf("Enter a string to reversen");
gets(arr);
strrev(arr);
printf("Reverse of entered string is n%sn",arr);
return 0;
}
Download Reverse string program.
Output of program:
C program to reverse string without using function
Below code does not uses strrev library function to reverse a string. First we calculate the length
of string using strlen function and then assigns characters of input string in reverse order to
create a new string using a for loop. You can also calculate length of string without using strlen.
We use comma operator in for loop to initialize multiple variables and increment/decrement
variables.
#include <stdio.h>
#include <string.h>
int main()
{
char s[100], r[100];
int n, c, d;
printf("Input a stringn");
gets(s);
n = strlen(s);
for (c = n - 1, d = 0; c >= 0; c--, d++)
r[d] = s[c];
r[d] = '0';
printf("%sn", r);
return 0;
}
C program to reverse a string using pointers
Now we will invert string using pointers or without using library function strrev.
#include<stdio.h>
int string_length(char*);
void reverse(char*);
main()
{
char string[100];
printf("Enter a stringn");
gets(string);
reverse(string);
printf("Reverse of entered string is "%s".n", string);
return 0;
}
void reverse(char *string)
{
int length, c;
char *begin, *end, temp;
length = string_length(string);
begin = string;
end = string;
for (c = 0; c < length - 1; c++)
end++;
for (c = 0; c < length/2; c++)
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
int string_length(char *pointer)
{
int c = 0;
while( *(pointer + c) != '0' )
c++;
return c;
}
C program to reverse a string using recursion
#include <stdio.h>
#include <string.h>
void reverse(char*, int, int);
int main()
{
char a[100];
gets(a);
reverse(a, 0, strlen(a)-1);
printf("%sn",a);
return 0;
}
void reverse(char *x, int begin, int end)
{
char c;
if (begin >= end)
return;
c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
reverse(x, ++begin, --end);
}
In recursion method we swap characters at the begin and at the end and then move towards the
middle of the string. This method is inefficient due to repeated function calls but useful in
practicing recursion.
C palindrome program,c program for palindrome
C program for palindrome or palindrome in c programming: palindrome program in c language,
c code to check if a string is a palindrome or not and for palindrome number. This program
works as follows :- at first we copy the entered string into a new string, and then we reverse the
new string and then compares it with original string. If both of them have same sequence of
characters i.e. they are identical then the entered string is a palindrome otherwise not. To perform
copy, reverse and compare operations we use strcpy, strrev and strcmp functions of string.h
respectively, if you do not wish to use these functions see c programming code for palindrome
without using string functions. Some palindrome strings examples are "a", dad", "radar",
"madam", "abcba" etc.
C program for palindrome
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
printf("Enter the string to check if it is a palindromen");
gets(a);
strcpy(b,a);
strrev(b);
if (strcmp(a,b) == 0)
printf("Entered string is a palindrome.n");
else
printf("Entered string is not a palindrome.n");
return 0;
}
Download palindrome program.
Output of program:
Palindrome number in c
#include <stdio.h>
main()
{
int n, reverse = 0, temp;
printf("Enter a number to check if it is a palindrome or notn");
scanf("%d",&n);
temp = n;
while (temp != 0)
{
reverse = reverse * 10;
reverse = reverse + temp%10;
temp = temp/10;
}
if (n == reverse)
printf("%d is a palindrome number.n", n);
else
printf("%d is not a palindrome number.n", n);
return 0;
}
C program for palindrome without using string functions
#include <stdio.h>
#include <string.h>
int main()
{
char text[100];
int begin, middle, end, length = 0;
gets(text);
while (text[length] != '0')
length++;
end = length - 1;
middle = length/2;
for (begin = 0; begin < middle; begin++)
{
if (text[begin] != text[end])
{
printf("Not a palindrome.n");
break;
}
end--;
}
if (begin == middle)
printf("Palindrome.n");
return 0;
}
C program check palindrome
#include <stdio.h>
int is_palindrome(char*);
void copy_string(char*, char*);
void reverse_string(char*);
int string_length(char*);
int compare_string(char*, char*);
int main()
{
char string[100];
int result;
printf("Input a stringn");
gets(string);
result = is_palindrome(string);
if ( result == 1 )
printf(""%s" is a palindrome string.n", string);
else
printf(""%s" is not a palindrome string.n", string);
return 0;
}
int is_palindrome(char *string)
{
int check, length;
char *reverse;
length = string_length(string);
reverse = (char*)malloc(length+1);
copy_string(reverse, string);
reverse_string(reverse);
check = compare_string(string, reverse);
free(reverse);
if ( check == 0 )
return 1;
else
return 0;
}
int string_length(char *string)
{
int length = 0;
while(*string)
{
length++;
string++;
}
return length;
}
void copy_string(char *target, char *source)
{
while(*source)
{
*target = *source;
source++;
target++;
}
*target = '0';
}
void reverse_string(char *string)
{
int length, c;
char *begin, *end, temp;
length = string_length(string);
begin = string;
end = string;
for ( c = 0 ; c < ( length - 1 ) ; c++ )
end++;
for ( c = 0 ; c < length/2 ; c++ )
{
temp = *end;
*end = *begin;
*begin = temp;
begin++;
end--;
}
}
int compare_string(char *first, char *second)
{
while(*first==*second)
{
if ( *first == '0' || *second == '0' )
break;
first++;
second++;
}
if( *first == '0' && *second == '0' )
return 0;
else
return -1;
}
Pointers are used in functions, you can develop your code without using pointers.
C program to convert string to integer without using atoi function
C program to convert string to integer: It is frequently required to convert a string to an integer in
applications. String should consists of digits only and an optional '-' (minus) sign at beginning for
integers. For string containing other characters we can stop conversion as soon as a non digit
character is encountered but in our program we will handle ideal case when only valid characters
are present in string. Library function atoi can be used to convert string to an integer but we will
create our own function.
C programming code
// C program to convert string to integer without using atoi function
#include <stdio.h>
int toString(char []);
int main()
{
char a[100];
int n;
printf("Input a valid string to convert to integern");
scanf("%s", a);
n = toString(a);
printf("String = %snInteger = %dn", a, n);
return 0;
}
int toString(char a[]) {
int c, sign, offset, n;
if (a[0] == '-') { // Handle negative integers
sign = -1;
}
if (sign == -1) { // Set starting position to convert
offset = 1;
}
else {
offset = 0;
}
n = 0;
for (c = offset; a[c] != '0'; c++) {
n = n * 10 + a[c] - '0';
}
if (sign == -1) {
n = -n;
}
return n;
}
Similarly you can convert string to long.
Output of program:
Compilerused:
GCC C program to delete vowels from a string
Remove vowels from a string in c: c program to remove or delete vowels from a string, if the
input string is "c programming" then output will be "c prgrmmng". In the program we create a
new string and process entered string character by character, and if a vowel is found it is not
added to new string otherwise the character is added to new string, after the string ends we copy
the new string into original string. Finally we obtain a string without any vowels.
C programming code
#include <stdio.h>
#include <string.h>
int check_vowel(char);
int main()
{
char s[100], t[100];
int i, j = 0;
printf("Enter a string to delete vowelsn");
gets(s);
for(i = 0; s[i] != '0'; i++) {
if(check_vowel(s[i]) == 0) { //not a vowel
t[j] = s[i];
j++;
}
}
t[j] = '0';
strcpy(s, t); //We are changing initial string
printf("String after deleting vowels: %sn", s);
return 0;
}
int check_vowel(char c)
{
switch(c) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return 1;
default:
return 0;
}
}
Output of program:
C programming code using pointers
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define TRUE 1
#define FALSE 0
int check_vowel(char);
main()
{
char string[100], *temp, *pointer, ch, *start;
printf("Enter a stringn");
gets(string);
temp = string;
pointer = (char*)malloc(100);
if( pointer == NULL )
{
printf("Unable to allocate memory.n");
exit(EXIT_FAILURE);
}
start = pointer;
while(*temp)
{
ch = *temp;
if ( !check_vowel(ch) )
{
*pointer = ch;
pointer++;
}
temp++;
}
*pointer = '0';
pointer = start;
strcpy(string, pointer); /* If you wish to convert original string */
free(pointer);
printf("String after removing vowel is "%s"n", string);
return 0;
}
int check_vowel(char a)
{
if ( a >= 'A' && a <= 'Z' )
a = a + 'a' - 'A';
if ( a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
return TRUE;
return FALSE;
}
Substring in c programming,c substring
Substring in c programming: c programming code to find a substring from a given string and for
all substrings of a string, For example substrings of string "the" are "t", "th", "the", "h", "he" and
"e" to find substring we create our own c substring function which returns a pointer to string.
String address, length of substring required and position from where to extract substring are the
three arguments passed to function. String.h does not contain any library function to directly find
substring.
C substring code
#include <stdio.h>
int main()
{
char string[1000], sub[1000];
int position, length, c = 0;
printf("Input a stringn");
gets(string);
printf("Enter the position and length of substringn");
scanf("%d%d", &position, &length);
while (c < length) {
sub[c] = string[position+c-1];
c++;
}
sub[c] = '0';
printf("Required substring is "%s"n", sub);
return 0;
}
C substring program output:
C substring program using function
We create a function and pass it four arguments original string array, substring array, position
and length of desired substring. As call by reference is used we do not need to return substring
array. See another code below in which we return pointer to substring, which we create in our
array using dynamic memory allocation.
#include <stdio.h>
void substring(char [], char[], int, int);
int main()
{
char string[1000], sub[1000];
int position, length, c = 0;
printf("Input a stringn");
gets(string);
printf("Enter the position and length of substringn");
scanf("%d%d", &position, &length);
substring(string, sub, position, length);
printf("Required substring is "%s"n", sub);
return 0;
}
void substring(char s[], char sub[], int p, int l) {
int c = 0;
while (c < l) {
sub[c] = s[p+c-1];
c++;
}
sub[c] = '0';
}
C substring program using pointers
#include <stdio.h>
#include <stdlib.h>
char* substring(char*, int, int);
int main()
{
char string[100], *pointer;
int position, length;
printf("Input a stringn");
gets(string);
printf("Enter the position and length of substringn");
scanf("%d%d",&position, &length);
pointer = substring( string, position, length);
printf("Required substring is "%s"n", pointer);
free(pointer);
return 0;
}
/*C substring function: It returns a pointer to the substring */
char *substring(char *string, int position, int length)
{
char *pointer;
int c;
pointer = malloc(length+1);
if (pointer == NULL)
{
printf("Unable to allocate memory.n");
exit(1);
}
for (c = 0 ; c < length ; c++)
{
*(pointer+c) = *(string+position-1);
string++;
}
*(pointer+c) = '0';
return pointer;
}
C code for all substrings of a string
#include <stdio.h>
#include <string.h>
#include <malloc.h>
char* substring(char*, int, int);
int main()
{
char string[100], *pointer;
int position = 1, length = 1, temp, string_length;
printf("Enter a stringn");
gets(string);
temp = string_length = strlen(string);
printf("Substring of "%s" aren", string);
while (position <= string_length)
{
while (length <= temp)
{
pointer = substring(string, position, length);
printf("%sn", pointer);
free(pointer);
length++;
}
temp--;
position++;
length = 1;
}
return 0;
}
/* Use substring function given in above c program*/
Substring code output:
C program to sort a string in alphabetic order
C program to sort a string in alphabetic order: For example if user will enter a string
"programming" then output will be "aggimmnoprr" or output string will contain characters in
alphabetical order. In our program we assume input string contains only lower case alphabets.
First we count and store how many times characters 'a' to 'z' appear in input string and then create
another string which contains characters 'a' to 'z' as many times as they appear in the input string.
C programming code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char ch, input[100], output[100];
int no[26] = {0}, n, c, t, x;
printf("Enter some textn");
scanf("%s", input);
n = strlen(input);
/** Store how many times characters (a to z)
appears in input string in array */
for (c = 0; c < n; c++)
{
ch = input[c] - 'a';
no[ch]++;
}
t = 0;
/** Insert characters a to z in output string
that many number of times as they appear
in input string */
for (ch = 'a'; ch <= 'z'; ch++)
{
x = ch - 'a';
for (c = 0; c < no[x]; c++)
{
output[t] = ch;
t++;
}
}
output[t] = '0';
printf("%sn", output);
return 0;
}
Output of program:
C program using pointers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort_string(char*);
int main()
{
char string[100];
printf("Enter some textn");
gets(string);
sort_string(string);
printf("%sn", string);
return 0;
}
void sort_string(char *s)
{
int c, d = 0, length;
char *pointer, *result, ch;
length = strlen(s);
result = (char*)malloc(length+1);
pointer = s;
for ( ch = 'a' ; ch <= 'z' ; ch++ )
{
for ( c = 0 ; c < length ; c++ )
{
if ( *pointer == ch )
{
*(result+d) = *pointer;
d++;
}
pointer++;
}
pointer = s;
}
*(result+d) = '0';
strcpy(s, result);
free(result);
}

Weitere ähnliche Inhalte

Was ist angesagt?

Object Oriented Programming Using C++ Practical File
Object Oriented Programming Using C++ Practical FileObject Oriented Programming Using C++ Practical File
Object Oriented Programming Using C++ Practical FileHarjinder Singh
 
The solution manual of programming in ansi by Robin
The solution manual of programming in ansi by RobinThe solution manual of programming in ansi by Robin
The solution manual of programming in ansi by RobinShariful Haque Robin
 
Core programming in c
Core programming in cCore programming in c
Core programming in cRahul Pandit
 
Oops practical file
Oops practical fileOops practical file
Oops practical fileAnkit Dixit
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solutionAzhar Javed
 
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1rohit kumar
 
Let us c(by yashwant kanetkar) chapter 2 solution
Let us c(by yashwant kanetkar) chapter 2 solutionLet us c(by yashwant kanetkar) chapter 2 solution
Let us c(by yashwant kanetkar) chapter 2 solutionrohit kumar
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarSivakumar R D .
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programmingAppili Vamsi Krishna
 
Types of function call
Types of function callTypes of function call
Types of function callArijitDhali
 
String Library Functions
String Library FunctionsString Library Functions
String Library FunctionsNayan Sharma
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Languagemadan reddy
 
Chapter 5 Balagurusamy Programming ANSI in c
Chapter 5 Balagurusamy Programming ANSI  in cChapter 5 Balagurusamy Programming ANSI  in c
Chapter 5 Balagurusamy Programming ANSI in cBUBT
 

Was ist angesagt? (20)

pointers
pointerspointers
pointers
 
Object Oriented Programming Using C++ Practical File
Object Oriented Programming Using C++ Practical FileObject Oriented Programming Using C++ Practical File
Object Oriented Programming Using C++ Practical File
 
The solution manual of programming in ansi by Robin
The solution manual of programming in ansi by RobinThe solution manual of programming in ansi by Robin
The solution manual of programming in ansi by Robin
 
Core programming in c
Core programming in cCore programming in c
Core programming in c
 
Oops practical file
Oops practical fileOops practical file
Oops practical file
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solution
 
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
Let us c(by Yashwant Kanetkar) 5th edition solution chapter 1
 
Let us c(by yashwant kanetkar) chapter 2 solution
Let us c(by yashwant kanetkar) chapter 2 solutionLet us c(by yashwant kanetkar) chapter 2 solution
Let us c(by yashwant kanetkar) chapter 2 solution
 
Preprocessor in C
Preprocessor in CPreprocessor in C
Preprocessor in C
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 
Types of function call
Types of function callTypes of function call
Types of function call
 
String Library Functions
String Library FunctionsString Library Functions
String Library Functions
 
I PUC CS Lab_programs
I PUC CS Lab_programsI PUC CS Lab_programs
I PUC CS Lab_programs
 
C string
C stringC string
C string
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Strings in C
Strings in CStrings in C
Strings in C
 
Chapter 5 Balagurusamy Programming ANSI in c
Chapter 5 Balagurusamy Programming ANSI  in cChapter 5 Balagurusamy Programming ANSI  in c
Chapter 5 Balagurusamy Programming ANSI in c
 

Andere mochten auch

Andere mochten auch (10)

88 c programs 15184
88 c programs 1518488 c programs 15184
88 c programs 15184
 
C program
C programC program
C program
 
c-programming-using-pointers
c-programming-using-pointersc-programming-using-pointers
c-programming-using-pointers
 
Ge6161 lab manual
Ge6161 lab manualGe6161 lab manual
Ge6161 lab manual
 
Unit 4 A2 Chemistry Notes Edexcel
Unit 4 A2 Chemistry Notes EdexcelUnit 4 A2 Chemistry Notes Edexcel
Unit 4 A2 Chemistry Notes Edexcel
 
Simple c program
Simple c programSimple c program
Simple c program
 
20 C programs
20 C programs20 C programs
20 C programs
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
 
C ppt
C pptC ppt
C ppt
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 

Ähnlich wie Practical write a c program to reverse a given number

B.Com 1year Lab programs
B.Com 1year Lab programsB.Com 1year Lab programs
B.Com 1year Lab programsPrasadu Peddi
 
Common problems solving using c
Common problems solving using cCommon problems solving using c
Common problems solving using cArghodeepPaul
 
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...DR B.Surendiran .
 
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfPCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfAshutoshprasad27
 
PCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docxPCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docxAshutoshprasad27
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020vrgokila
 
Program flowchart
Program flowchartProgram flowchart
Program flowchartSowri Rajan
 
All important c programby makhan kumbhkar
All important c programby makhan kumbhkarAll important c programby makhan kumbhkar
All important c programby makhan kumbhkarsandeep kumbhkar
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using CBilal Mirza
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solutionKuntal Bhowmick
 
Programming in C Lab
Programming in C LabProgramming in C Lab
Programming in C LabNeil Mathew
 

Ähnlich wie Practical write a c program to reverse a given number (20)

B.Com 1year Lab programs
B.Com 1year Lab programsB.Com 1year Lab programs
B.Com 1year Lab programs
 
Common problems solving using c
Common problems solving using cCommon problems solving using c
Common problems solving using c
 
Progr3
Progr3Progr3
Progr3
 
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...
 
PCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdfPCA-2 Programming and Solving 2nd Sem.pdf
PCA-2 Programming and Solving 2nd Sem.pdf
 
PCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docxPCA-2 Programming and Solving 2nd Sem.docx
PCA-2 Programming and Solving 2nd Sem.docx
 
Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020Basic c programs updated on 31.8.2020
Basic c programs updated on 31.8.2020
 
Programming egs
Programming egs Programming egs
Programming egs
 
Program flowchart
Program flowchartProgram flowchart
Program flowchart
 
C
CC
C
 
SaraPIC
SaraPICSaraPIC
SaraPIC
 
All important c programby makhan kumbhkar
All important c programby makhan kumbhkarAll important c programby makhan kumbhkar
All important c programby makhan kumbhkar
 
C Programming Exam problems & Solution by sazzad hossain
C Programming Exam problems & Solution by sazzad hossainC Programming Exam problems & Solution by sazzad hossain
C Programming Exam problems & Solution by sazzad hossain
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using C
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solution
 
Programming in C Lab
Programming in C LabProgramming in C Lab
Programming in C Lab
 
C file
C fileC file
C file
 
C faq pdf
C faq pdfC faq pdf
C faq pdf
 
Hargun
HargunHargun
Hargun
 
C Programming Example
C Programming ExampleC Programming Example
C Programming Example
 

Kürzlich hochgeladen

Multicomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdfMulticomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdfGiovanaGhasary1
 
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdfSummer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdfNaveenVerma126
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptxSaiGouthamSunkara
 
Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingMarian Marinov
 
Power System electrical and electronics .pptx
Power System electrical and electronics .pptxPower System electrical and electronics .pptx
Power System electrical and electronics .pptxMUKULKUMAR210
 
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...Amil baba
 
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxVertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxLMW Machine Tool Division
 
Mohs Scale of Hardness, Hardness Scale.pptx
Mohs Scale of Hardness, Hardness Scale.pptxMohs Scale of Hardness, Hardness Scale.pptx
Mohs Scale of Hardness, Hardness Scale.pptxKISHAN KUMAR
 
Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...Apollo Techno Industries Pvt Ltd
 
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdfRenewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdfodunowoeminence2019
 
Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Bahzad5
 
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxSUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxNaveenVerma126
 
me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Akarthi keyan
 
cloud computing notes for anna university syllabus
cloud computing notes for anna university syllabuscloud computing notes for anna university syllabus
cloud computing notes for anna university syllabusViolet Violet
 
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Amil baba
 
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Sean Meyn
 
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchrohitcse52
 

Kürzlich hochgeladen (20)

Multicomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdfMulticomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdf
 
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdfSummer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
 
Phase noise transfer functions.pptx
Phase noise transfer      functions.pptxPhase noise transfer      functions.pptx
Phase noise transfer functions.pptx
 
Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & Logging
 
Power System electrical and electronics .pptx
Power System electrical and electronics .pptxPower System electrical and electronics .pptx
Power System electrical and electronics .pptx
 
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...
Best-NO1 Best Rohani Amil In Lahore Kala Ilam In Lahore Kala Jadu Amil In Lah...
 
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptxVertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
Vertical- Machining - Center - VMC -LMW-Machine-Tool-Division.pptx
 
Mohs Scale of Hardness, Hardness Scale.pptx
Mohs Scale of Hardness, Hardness Scale.pptxMohs Scale of Hardness, Hardness Scale.pptx
Mohs Scale of Hardness, Hardness Scale.pptx
 
Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...Technology Features of Apollo HDD Machine, Its Technical Specification with C...
Technology Features of Apollo HDD Machine, Its Technical Specification with C...
 
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdfRenewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
 
Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)Lecture 1: Basics of trigonometry (surveying)
Lecture 1: Basics of trigonometry (surveying)
 
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docxSUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
SUMMER TRAINING REPORT ON BUILDING CONSTRUCTION.docx
 
me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part A
 
cloud computing notes for anna university syllabus
cloud computing notes for anna university syllabuscloud computing notes for anna university syllabus
cloud computing notes for anna university syllabus
 
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
Popular-NO1 Kala Jadu Expert Specialist In Germany Kala Jadu Expert Specialis...
 
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
 
Présentation IIRB 2024 Chloe Dufrane.pdf
Présentation IIRB 2024 Chloe Dufrane.pdfPrésentation IIRB 2024 Chloe Dufrane.pdf
Présentation IIRB 2024 Chloe Dufrane.pdf
 
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
 
Lecture 4 .pdf
Lecture 4                              .pdfLecture 4                              .pdf
Lecture 4 .pdf
 
Lecture 2 .pdf
Lecture 2                           .pdfLecture 2                           .pdf
Lecture 2 .pdf
 

Practical write a c program to reverse a given number

  • 1. 1. Write a c program to reverse a given number 2. #include<stdio.h> 3. int main(){ 4. int num,r,reverse=0; 5. 6. printf("Enter any number: "); 7. scanf("%d",&num); 8. 9. while(num){ 10. r=num%10; 11. reverse=reverse*10+r; 12. num=num/10; 13. } 14. 15. printf("Reversed of number: %d",reverse); 16. return 0; 17. } 18. 19. Sample output: 20. Enter any number: 12 21. Reversed of number: 21 22. Sample output: 23. Enter any number: 12 24. Reversed of number: 21 25.Palindrome number in c 26. #include <stdio.h> 27. 28. main() 29. { 30. int n, reverse = 0, temp; 31. 32. printf("Enter a number to check if it is a palindrome or notn"); 33. scanf("%d",&n); 34. 35. temp = n; 36. 37. while (temp != 0) 38. { 39. reverse = reverse * 10; 40. reverse = reverse + temp%10; 41. temp = temp/10; 42. } 43. 44. if (n == reverse) 45. printf("%d is a palindrome number.n", n); 46. else 47. printf("%d is not a palindrome number.n", n);
  • 2. 48. 49. return 0; 50. } 51. How towrite a C program to determine the smallest among 52. three nos using conditional operator? #include<stdio.h> #include<conio.h> voidmain() { intn1,n2,n3,small; clrscr(); printf("Enterthree numbers"); scanf("%d%d%d",&n1,&n2,&n3); small=n1<n2?(n1<n3?n1:n3):(n2<n3?n2:n3); printf("smallestnumberis:%d",small); printf("pressanykeytoclose"); getch(); } write program to perform sum = 1-2+3-4+.. #include<stdio.h> #include<conio.h> void main() { int e=0,o=0; Int n; Printf(“enterano”); Scanf(“%d”,&n); For(i=1;i<=n;i++) {if(i%2==0) E=e+I; Else o=o+I; }
  • 3. Printf(“the sumis+%d -%d”,o-e): } Write a C program to find the average of N numbers by using the for loop. #include<stdio.h> #include<conio.h> void main() int n,i,sum; float av; clrscr(); printf("n Enter the value of N:"); scanf("%d",&n); for(i =1;i<=n;i++) { sum= sum+i; } printf("n sum is:%d",sum); av=(float)sum/n; printf("n Average is: %f",av); getche(); }
  • 4. OUTPUT: Enter the value of n: 10 sum is: 55 Average is: 5.5 c programto count the numberof vowelsandconsonantsinastring Here is the programto count numberof vowelsandconsonantsinc. vowels and consonants #include<stdio.h> //#include<conio.h> #include<string.h> voidmain() { char str[50]; int vovels=0,consonants=0,len,i; printf("Enterthe String:n"); gets(str); len=strlen(str); for(i=0;i<len;i++) { if((str[i]>64&&str[i]<91)||(str[i]>96&&str[i]<123)) //Firstlycheckingthe characteris alphabetornot { if(str[i]=='a'||str[i]=='A'||str[i]=='e'||str[i]=='E'||str[i]=='i'||str[i]=='I'||str[i]=='o'||str[i]=='O'||str[i]=='u '||str[i]=='U') //checkingif itisvowel ornot vovels++; else consonants++; } }
  • 5. printf("Numberof vovels=%d andconsonants= %d",vovels,consonants); //getch(); } Write a Programto printPrime Numbersbetween1 to 100 #include voidmain() { intn,c=2; printf("enteranumber"); scanf("%d",&n); for(c=2;c<n-1;c++) { if(n%c==0){ printf("notaprime number"); break; } } if(c==n){ printf("primenumber"); } } Write a c program to find out the sum of series 1^2 + 2^2 + …. + n^2. Sum of the series 12 + 22 + 32 + … + n2 = n (n+1) (2n+1)/6 1 2 3 4 5 6 7 8 9 10 11 12 #include<stdio.h> int main(){ int n,i; int sum=0; printf("Enter the n i.e. max values of series: "); scanf("%d",&n); sum = (n * (n + 1) * (2 * n + 1 )) / 6; printf("Sum of the series : ");
  • 6. 13 14 15 16 17 18 19 20 21 22 23 for(i =1;i<=n;i++){ if (i != n) printf("%d^2 + ",i); else printf("%d^2 = %d ",i,sum); } return 0; } Output: Enter the n i.e. max values of series: 5 Sum of the series: 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55 FIND OUT LARGEST NUMBERINANARRAYUSING C PROGRAM C program to find the largest element in an array imple program of c find the largest number #include<stdio.h> int main(){ int n,num,i; int big; printf("Enter the values of n: "); scanf("%d",&n); printf("Number %d",1); scanf("%d",&big); for(i=2;i<=n;i++){ printf("Number %d: ",i); scanf("%d",&num); if(big<num) big=num; } printf("Largest number is: %d",big); return 0;
  • 7. } Sample Output: Enter the values of n: Number 1: 12 Number 2: 32 Number 3: 35 Largest number is: 35 TO FIND FACTORIALOFA NUMBERUSING C PROGRAM Code 1: 1. C code for factorial of a number 2. C program to find the factorial of a given number 3. Factorial program in c using while loop 4. Factorial program in c without using recursion #include<stdio.h> int main(){ int i=1,f=1,num; printf("Enter a number: "); scanf("%d",&num); while(i<=num){ f=f*i; i++; } printf("Factorial of %d is: %d",num,f); return 0; } Sample output: Enter a number: 5 Factorial of 5 is: 120 Code 2: 1. Factorial program in c using for loop 2. Simple factorial program in c 3. C program to calculate factorial #include<stdio.h> int main(){ int i,f=1,num;
  • 8. printf("Enter a number: "); scanf("%d",&num); for(i=1;i<=num;i++) f=f*i; printf("Factorial of %d is: %d",num,f); return 0; } Code 3: 1. Factorial program in c using pointers 2. How to calculate factorial in c 3. Factorial program in c language #include<stdio.h> void findFactorial(int,int *); int main(){ int i,factorial,num; printf("Enter a number: "); scanf("%d",&num); findFactorial(num,&factorial); printf("Factorial of %d is: %d",num,*factorial); return 0; } void findFactorial(int num,int *factorial){ int i; *factorial =1; for(i=1;i<=num;i++) *factorial=*factorial*i; } Code 4: 1. Factorial program in c using function
  • 9. 2. C program to find factorial of a number #include<stdio.h> int findFactorial(int); int main(){ int i,factorial,num; printf("Enter a number: "); scanf("%d",&num); factorial = findFactorial(num); printf("Factorial of %d is: %d",num,factorial); return 0; } int findFactorial(int num){ int i,f=1; for(i=1;i<=num;i++) f=f*i; return f; } Sample output: Enter a number: 8 Factorial of 8 is: 40320 Code 5: 1. Factorial series in c #include<stdio.h> int main(){ long f=1; int i,num,min,max; printf("Enter the minimum range: "); scanf("%d",&min); printf("Enter the maximum range: "); scanf("%d",&max);
  • 10. printf("Factorial series in given range: "); for(num=min;num<=max;num++){ f=1; for(i=1;i<=num;i++) f=f*i; printf("%ld ",f); } return 0; } Sample output: Enter the minimum range: 1 Enter the maximum range: 10 Factorial series in given range: 1 2 6 24 120 720 5040 40320 362880 3628800 Algorithm: Factorial value Factorial of number is defined as: Factorial (n) = 1*2*3 … * n For example: Factorial of 5 = 1*2*3*4*5 = 120 Note: Factorial of zero = 1 Program to sort set of strings in alphabetical order #include #include #include void main() { char a[20],b[20]; int i,j,n,temp; clrscr(); printf("n Enter any string : "); gets(a); n=strlen(a);
  • 11. for(i=0;i<n;i++)</n;i++) { for(j=0;j<n-i;j++)</n-i;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; }}} printf("n The final string is :"); for(i=0;i<=n;i++) printf("%c",a[i]); getch(); } C program to check odd or even C program to check odd or even: We will determine whether a number is odd or even by using different methods all are provided with a code in c language. As you have study in mathematics that in decimal number system even numbers are divisible by 2 while odd are not so we may use modulus operator(%) which returns remainder, For example 4%3 gives 1 ( remainder when four is divided by three). Even numbers are of the form 2*p and odd are of the form (2*p+1) where p is is an integer. C program to check odd or even using modulus operator #include <stdio.h> int main() { int n; printf("Enter an integern"); scanf("%d", &n); if (n%2 == 0) printf("Evenn"); else printf("Oddn"); return 0; } We can use bitwise AND (&) operator to check odd or even, as an example consider binary of 7 (0111) when we perform 7 & 1 the result will be one and you may observe that the least significant bit of every odd number is 1, so ( odd_number & 1 ) will be one always and also ( even_number & 1 ) is zero.
  • 12. C program to check odd or even using bitwise operator #include <stdio.h> int main() { int n; printf("Enter an integern"); scanf("%d", &n); if (n & 1 == 1) printf("Oddn"); else printf("Evenn"); return 0; } Find odd or even using conditional operator #include <stdio.h> int main() { int n; printf("Input an integern"); scanf("%d", &n); n%2 == 0 ? printf("Evenn") : printf("Oddn"); return 0; } C program to check odd or even without using bitwise or modulus operator #include <stdio.h> int main() { int n; printf("Enter an integern"); scanf("%d", &n); if ((n/2)*2 == n) printf("Evenn"); else printf("Oddn");
  • 13. return 0; } In c programming language when we divide two integers we get an integer result, For example the result of 7/3 will be 2. So we can take advantage of this and may use it to find whether the number is odd or even. Consider an integer n we can first divide by 2 and then multiply it by 2 if the result is the original number then the number is even otherwise the number is odd. For example 11/2 = 5, 5*2 = 10 (which is not equal to eleven), now consider 12/2 = 6 and 6*2 = 12 (same as original number). These are some logic which may help you in finding if a number is odd or not. C program to check whether input alphabet is a vowel or not This code checks whether an input alphabet is a vowel or not. Both lower-case and upper-case are checked. C programming code #include <stdio.h> int main() { char ch; printf("Enter a charactern"); scanf("%c", &ch); if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch =='o' || ch=='O' || ch == 'u' || ch == 'U') printf("%c is a vowel.n", ch); else printf("%c is not a vowel.n", ch); return 0; } Output of program:
  • 14. Check vowel using switch statement #include <stdio.h> int main() { char ch; printf("Input a charactern"); scanf("%c", &ch); switch(ch) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': printf("%c is a vowel.n", ch); break; default: printf("%c is not a vowel.n", ch); } return 0; } Functionto checkvowel int check_vowel(char a) { if (a >= 'A' && a <= 'Z') a = a + 'a' - 'A'; /* Converting to lower case or use a = a + 32 */ if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') return 1; return 0; } This function can also be used to check if a character is a consonant or not, if it's not a vowel then it will be a consonant, but make sure that the character is an alphabet not a special character. C program to check leap year C program to check leap year: c code to check leap year, year will be entered by the user.
  • 15. C programming code #include <stdio.h> int main() { int year; printf("Enter a year to check if it is a leap yearn"); scanf("%d", &year); if ( year%400 == 0) printf("%d is a leap year.n", year); else if ( year%100 == 0) printf("%d is not a leap year.n", year); else if ( year%4 == 0 ) printf("%d is a leap year.n", year); else printf("%d is not a leap year.n", year); return 0; } Output of program: Please read the leap year article at Wikipedia, it will help you to understand the program. This code is based on Gregorian Calendar. C program to find hcf and lcm C program to find hcf and lcm: The code below finds highest common factor and least common multiple of two integers. HCF is also known as greatest common divisor(GCD) or greatest common factor(gcf). C programming code
  • 16. #include <stdio.h> int main() { int a, b, x, y, t, gcd, lcm; printf("Enter two integersn"); scanf("%d%d", &x, &y); a = x; b = y; while (b != 0) { t = b; b = a % b; a = t; } gcd = a; lcm = (x*y)/gcd; printf("Greatest common divisor of %d and %d = %dn", x, y, gcd); printf("Least common multiple of %d and %d = %dn", x, y, lcm); return 0; } Download HCF and LCM program. Output of program: C program to find hcf and lcm using recursion #include <stdio.h> long gcd(long, long); int main() { long x, y, hcf, lcm; printf("Enter two integersn"); scanf("%ld%ld", &x, &y); hcf = gcd(x, y); lcm = (x*y)/hcf;
  • 17. printf("Greatest common divisor of %ld and %ld = %ldn", x, y, hcf); printf("Least common multiple of %ld and %ld = %ldn", x, y, lcm); return 0; } long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } C program to find hcf and lcm using function #include <stdio.h> long gcd(long, long); int main() { long x, y, hcf, lcm; printf("Enter two integersn"); scanf("%ld%ld", &x, &y); hcf = gcd(x, y); lcm = (x*y)/hcf; printf("Greatest common divisor of %ld and %ld = %ldn", x, y, hcf); printf("Least common multiple of %ld and %ld = %ldn", x, y, lcm); return 0; } long gcd(long x, long y) { if (x == 0) { return y; } while (y != 0) { if (x > y) { x = x - y; } else { y = y - x; } } return x; }
  • 18. Decimal to binary conversion C program to convert decimal to binary: c language code to convert an integer from decimal number system(base-10) to binary number system(base-2). Size of integer is assumed to be 32 bits. We use bitwise operators to perform the desired task. We right shift the original number by 31, 30, 29, ..., 1, 0 bits using a loop and bitwise AND the number obtained with 1(one), if the result is 1 then that bit is 1 otherwise it is 0(zero). C programming code #include <stdio.h> int main() { int n, c, k; printf("Enter an integer in decimal number systemn"); scanf("%d", &n); printf("%d in binary number system is:n", n); for (c = 31; c >= 0; c--) { k = n >> c; if (k & 1) printf("1"); else printf("0"); } printf("n"); return 0; } Download Decimal binary program. Output of program: Above code only prints binary of integer, but we may wish to perform operations on binary so in the code below we are storing the binary in a string. We create a function which returns a pointer to string which is the binary of the number passed as argument to the function.
  • 19. C code to store decimal to binary conversion in a string #include <stdio.h> #include <stdlib.h> char *decimal_to_binary(int); main() { int n, c, k; char *pointer; printf("Enter an integer in decimal number systemn"); scanf("%d",&n); pointer = decimal_to_binary(n); printf("Binary string of %d is: %sn", n, t); free(pointer); return 0; } char *decimal_to_binary(int n) { int c, d, count; char *pointer; count = 0; pointer = (char*)malloc(32+1); if ( pointer == NULL ) exit(EXIT_FAILURE); for ( c = 31 ; c >= 0 ; c-- ) { d = n >> c; if ( d & 1 ) *(pointer+count) = 1 + '0'; else *(pointer+count) = 0 + '0'; count++; } *(pointer+count) = '0'; return pointer; } Memory is allocated dynamically because we can't return a pointer to a local variable (character array in this case). If we return a pointer to local variable then program may crash or we get incorrect result.
  • 20. Factorial program in c Factorial program in c: c code to find and print factorial of a number, three methods are given, first one uses for loop, second uses a function to find factorial and third using recursion. Factorial is represented using '!', so five factorial will be written as (5!), n factorial as (n!). Also n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1. Factorial program in c using for loop Here we find factorial using for loop. #include <stdio.h> int main() { int c, n, fact = 1; printf("Enter a number to calculate it's factorialn"); scanf("%d", &n); for (c = 1; c <= n; c++) fact = fact * c; printf("Factorial of %d = %dn", n, fact); return 0; } Download Factorial program. Output of code: Factorial program in c using function #include <stdio.h> long factorial(int); int main() { int number;
  • 21. long fact = 1; printf("Enter a number to calculate it's factorialn"); scanf("%d", &number); printf("%d! = %ldn", number, factorial(number)); return 0; } long factorial(int n) { int c; long result = 1; for (c = 1; c <= n; c++) result = result * c; return result; } Factorial program in c using recursion #include<stdio.h> long factorial(int); int main() { int n; long f; printf("Enter an integer to find factorialn"); scanf("%d", &n); if (n < 0) printf("Negative integers are not allowed.n"); else { f = factorial(n); printf("%d! = %ldn", n, f); } return 0; } long factorial(int n) { if (n == 0) return 1; else return(n * factorial(n-1)); }
  • 22. Recursion is a technique in which a function calls itself, for example in above code factorial function is calling itself. To solve a problem using recursion you must first express its solution in recursive form. C program to find ncr and npr C program to find nCr and nPr: This code calculate nCr which is n!/(r!*(n-r)!) and nPr = n!/(n-r)! C program to find nCr using function #include <stdio.h> long factorial(int); long find_ncr(int, int); long find_npr(int, int); int main() { int n, r; long ncr, npr; printf("Enter the value of n and rn"); scanf("%d%d",&n,&r); ncr = find_ncr(n, r); npr = find_npr(n, r); printf("%dC%d = %ldn", n, r, ncr); printf("%dP%d = %ldn", n, r, npr); return 0; } long find_ncr(int n, int r) { long result; result = factorial(n)/(factorial(r)*factorial(n-r)); return result; } long find_npr(int n, int r) { long result; result = factorial(n)/factorial(n-r); return result; } long factorial(int n) { int c; long result = 1;
  • 23. for (c = 1; c <= n; c++) result = result*c; return result; } Download NCR and NPR program. Output of program: Another way to calculate nPr and nCr using functions We use long long data type in our program to handle large numbers. #include <stdio.h> #define ll long long void find_ncr_npr(int, int, ll*, ll*); ll find_npr(int, int); ll factorial(int); int main() { int n, r; ll ncr, npr; printf("Input n and rn"); scanf("%d%d", &n, &r); find_ncr_npr(n, r, &npr, &ncr); printf("%dC%d = %lldn", n, r, ncr); printf("%dP%d = %lldn", n, r, npr); return 0; } void find_ncr_npr(int n, int r, ll *npr, ll *ncr) { *npr = find_npr(n, r); *ncr = *npr/factorial(r); } ll find_npr(int n, int r) { ll result = 1; int c = 1;
  • 24. while (c <= r) { result = result * (n - r + c); c++; } return result; } ll factorial(int n) { int c; ll result = 1; for (c = 1; c <= n; c++) result = result*c; return result; } Add digits of number in c C program to add digits of a number: Here we are using modulus operator(%) to extract individual digits of number and adding them. C programming code #include <stdio.h> int main() { int n, t, sum = 0, remainder; printf("Enter an integern"); scanf("%d", &n); t = n; while (t != 0) { remainder = t % 10; sum = sum + remainder; t = t / 10; } printf("Sum of digits of %d = %dn", n, sum); return 0; } If you wish you can modify input variable (n) and do not use an additional variable (t) but it is not recommended.
  • 25. Output of program: For example if the input is 98, sum(variable) is 0 initially 98%10 = 8 (% is modulus operator which gives us remainder when 98 is divided by 10). sum = sum + remainder so sum = 8 now. 98/10 = 9 because in c whenever we divide integer by another integer we get an integer. 9%10 = 9 sum = 8(previous value) + 9 sum = 17 9/10 = 0. So finally n = 0, loop ends we get the required sum. Download Add digits program. Find sum of digits in c without modulus operator C program to find sum of digit of an integer which does not use modulus operator. Our program uses a character array (string) for storing an integer. We convert every character of string into an integer and add all these integers. #include <stdio.h> int main() { int c, sum, t; char n[1000]; printf("Input an integern"); scanf("%s", n); sum = c = 0; while (n[c] != '0') { t = n[c] - '0'; // Converting character to integer sum = sum + t; c++; } printf("Sum of digits of %s = %dn", n, sum); return 0; }
  • 26. An advantage of this method is that input integer can be very large which may not be stored in int or long long data type see an example below in output. Output of program: Input an integer 123456789123456789123456789 Sum of digits of 123456789123456789123456789 = 135 Add digits using recursion #include <stdio.h> int add_digits(int); int main() { int n, result; scanf("%d", &n); result = add_digits(n); printf("%dn", result); return 0; } int add_digits(int n) { static int sum = 0; if (n == 0) { return 0; } sum = n%10 + add_digits(n/10); return sum; } Static variable sum is used and is initialized to 0, it' value will persists after function calls i.e. it is initialized only once when a first call to function is made. C program to add n numbers This c program add n numbers which will be entered by the user. Firstly user will enter a number indicating how many numbers user wishes to add and then user will enter n numbers. In the first c program to add numbers we are not using an array, and using array in the second code. C programming code
  • 27. #include <stdio.h> int main() { int n, sum = 0, c, value; printf("Enter the number of integers you want to addn"); scanf("%d", &n); printf("Enter %d integersn",n); for (c = 1; c <= n; c++) { scanf("%d", &value); sum = sum + value; } printf("Sum of entered integers = %dn",sum); return 0; } You can use long int data type for sum variable. Download Add n numbers program. Output of program: C programming code using array #include <stdio.h> int main() { int n, sum = 0, c, array[100]; scanf("%d", &n); for (c = 0; c < n; c++) { scanf("%d", &array[c]); sum = sum + array[c]; }
  • 28. printf("Sum = %dn",sum); return 0; } The advantage of using array is that we have a record of numbers inputted by user and can use them further in program if required and obviously storing numbers will require additional memory. Add n numbers using recursion #include <stdio.h> long calculateSum(int [], int); int main() { int n, c, array[100]; long result; scanf("%d", &n); for (c = 0; c < n; c++) scanf("%d", &array[c]); result = calculateSum(array, n); printf("Sum = %ldn", result); return 0; } long calculateSum(int a[], int n) { static long sum = 0; if (n == 0) return sum; sum = sum + a[n-1]; return calculateSum(a, --n); } C program to swap two numbers C program to swap two numbers with and without using third variable, swapping in c using pointers, functions (Call by reference) and using bitwise XOR operator, swapping means interchanging. For example if in your c program you have taken two variable a and b where a = 4 and b = 5, then before swapping a = 4, b = 5 after swapping a = 5, b = 4 In our c program to swap numbers we will use a temp variable to swap two numbers.
  • 29. Swapping of two numbers in c #include <stdio.h> int main() { int x, y, temp; printf("Enter the value of x and yn"); scanf("%d%d", &x, &y); printf("Before Swappingnx = %dny = %dn",x,y); temp = x; x = y; y = temp; printf("After Swappingnx = %dny = %dn",x,y); return 0; } Download Swap numbers program. Output of program: Swapping of two numbers without third variable You can also swap two numbers without using temp or temporary or third variable. In that case c program will be as shown :- #include <stdio.h> int main() { int a, b; printf("Enter two integers to swapn"); scanf("%d%d", &a, &b);
  • 30. a = a + b; b = a - b; a = a - b; printf("a = %dnb = %dn",a,b); return 0; } To understand above logic simply choose a as 7 and b as 9 and then do what is written in program. You can choose any other combination of numbers as well. Sometimes it's a good way to understand a program. Swap two numbers using pointers #include <stdio.h> int main() { int x, y, *a, *b, temp; printf("Enter the value of x and yn"); scanf("%d%d", &x, &y); printf("Before Swappingnx = %dny = %dn", x, y); a = &x; b = &y; temp = *b; *b = *a; *a = temp; printf("After Swappingnx = %dny = %dn", x, y); return 0; } Swapping numbers using call by reference In this method we will make a function to swap numbers. #include <stdio.h> void swap(int*, int*); int main() { int x, y; printf("Enter the value of x and yn"); scanf("%d%d",&x,&y); printf("Before Swappingnx = %dny = %dn", x, y);
  • 31. swap(&x, &y); printf("After Swappingnx = %dny = %dn", x, y); return 0; } void swap(int *a, int *b) { int temp; temp = *b; *b = *a; *a = temp; } C programming code to swap using bitwise XOR #include <stdio.h> int main() { int x, y; scanf("%d%d", &x, &y); printf("x = %dny = %dn", x, y); x = x ^ y; y = x ^ y; x = x ^ y; printf("x = %dny = %dn", x, y); return 0; } Swapping is used in sorting algorithms that is when we wish to arrange numbers in a particular order either in ascending order or in descending. C program to reverse a number C Program to reverse a number :- This program reverse the number entered by the user and then prints the reversed number on the screen. For example if user enter 123 as input then 321 is printed as output. In our program we use modulus(%) operator to obtain the digits of a number. To invert number look at it and write it from opposite direction or the output of code is a number obtained by writing original number from right to left. To reverse or invert large numbers use long data type or long long data type if your compiler supports it, if you still have large numbers then use strings or other data structure.
  • 32. C programming code #include <stdio.h> int main() { int n, reverse = 0; printf("Enter a number to reversen"); scanf("%d", &n); while (n != 0) { reverse = reverse * 10; reverse = reverse + n%10; n = n/10; } printf("Reverse of entered number is = %dn", reverse); return 0; } Download Reverse number program. Output of program: C program to reverse number using recursion #include <stdio.h> long reverse(long); int main() { long n, r; scanf("%ld", &n); r = reverse(n); printf("%ldn", r); return 0; }
  • 33. long reverse(long n) { static long r = 0; if (n == 0) return 0; r = r * 10; r = r + n % 10; reverse(n/10); return r; } Palindrome Numbers Palindrome number in c: A palindrome number is a number such that if we reverse it, it will not change. For example some palindrome numbers examples are 121, 212, 12321, -454. To check whether a number is palindrome or not first we reverse it and then compare the number obtained with the original, if both are same then number is palindrome otherwise not. C program for palindrome number is given below. Palindrome number algorithm 1. Get the number from user. 2. Reverse it. 3. Compare it with the number entered by the user. 4. If both are same then print palindrome number 5. Else print not a palindrome number. Palindrome number program c #include <stdio.h> int main() { int n, reverse = 0, temp; printf("Enter a number to check if it is a palindrome or notn"); scanf("%d",&n); temp = n; while( temp != 0 ) { reverse = reverse * 10; reverse = reverse + temp%10; temp = temp/10; } if ( n == reverse ) printf("%d is a palindrome number.n", n);
  • 34. else printf("%d is not a palindrome number.n", n); return 0; } Download Palindrome number program. Output of program: C program to print patterns of numbers and stars These program prints various different patterns of numbers and stars. These codes illustrate how to create various patterns using c programming. Most of these c programs involve usage of nested loops and space. A pattern of numbers, star or characters is a way of arranging these in some logical manner or they may form a sequence. Some of these patterns are triangles which have special importance in mathematics. Some patterns are symmetrical while other are not. Please see the complete page and look at comments for many different patterns. * *** ***** ******* ********* We have shown five rows above, in the program you will be asked to enter the numbers of rows you want to print in the pyramid of stars. C programming code #include <stdio.h> int main() { int row, c, n, temp; printf("Enter the number of rows in pyramid of stars you wish to see "); scanf("%d",&n); temp = n; for ( row = 1 ; row <= n ; row++ ) {
  • 35. for ( c = 1 ; c < temp ; c++ ) printf(" "); temp--; for ( c = 1 ; c <= 2*row - 1 ; c++ ) printf("*"); printf("n"); } return 0; } Download Stars pyramid program. Output of program: For more patterns or shapes on numbers and characters see comments below and also see codes on following pages: Floyd triangle Pascal triangle Consider the pattern * ** *** **** ***** to print above pattern see the code below: #include <stdio.h> int main() { int n, c, k;
  • 36. printf("Enter number of rowsn"); scanf("%d",&n); for ( c = 1 ; c <= n ; c++ ) { for( k = 1 ; k <= c ; k++ ) printf("*"); printf("n"); } return 0; } Using these examples you are in a better position to create your desired pattern for yourself. Creating a pattern involves how to use nested loops properly, some pattern may involve alphabets or other special characters. Key aspect is knowing how the characters in pattern changes. C pattern programs Pattern: * *A* *A*A* *A*A*A* C pattern program of stars and alphabets: #include<stdio.h> main() { int n, c, k, space, count = 1; printf("Enter number of rowsn"); scanf("%d",&n); space = n; for ( c = 1 ; c <= n ; c++) { for( k = 1 ; k < space ; k++) printf(" "); for ( k = 1 ; k <= c ; k++) { printf("*"); if ( c > 1 && count < c) { printf("A");
  • 37. count++; } } printf("n"); space--; count = 1; } return 0; } Pattern: 1 232 34543 4567654 567898765 C program: #include<stdio.h> main() { int n, c, d, num = 1, space; scanf("%d",&n); space = n - 1; for ( d = 1 ; d <= n ; d++ ) { num = d; for ( c = 1 ; c <= space ; c++ ) printf(" "); space--; for ( c = 1 ; c <= d ; c++ ) { printf("%d", num); num++; } num--; num--; for ( c = 1 ; c < d ; c++) { printf("%d", num); num--; } printf("n"); }
  • 38. return 0; } C program to print diamond pattern Diamond pattern in c: This code print diamond pattern of stars. Diamond shape is as follows: * *** ***** *** * C programming code #include <stdio.h> int main() { int n, c, k, space = 1; printf("Enter number of rowsn"); scanf("%d", &n); space = n - 1; for (k = 1; k <= n; k++) { for (c = 1; c <= space; c++) printf(" "); space--; for (c = 1; c <= 2*k-1; c++) printf("*"); printf("n"); } space = 1; for (k = 1; k <= n - 1; k++) { for (c = 1; c <= space; c++) printf(" "); space++; for (c = 1 ; c <= 2*(n-k)-1; c++) printf("*"); printf("n");
  • 39. } return 0; } Download Diamond program. Output of program: C program to print diamond using recursion #include <stdio.h> void print (int); int main () { int rows; scanf("%d", &rows); print(rows); return 0; } void print (int r) { int c, space; static int stars = -1; if (r <= 0)
  • 40. return; space = r - 1; stars += 2; for (c = 0; c < space; c++) printf(" "); for (c = 0; c < stars; c++) printf("*"); printf("n"); print(--r); space = r + 1; stars -= 2; for (c = 0; c < space; c++) printf(" "); for (c = 0; c < stars; c++) printf("*"); printf("n"); } C program for prime number Prime number program in c: c program for prime number, this code prints prime numbers using c programming language. To check whether a number is prime or not see another code below. Prime number logic: a number is prime if it is divisible only by one and itself. Remember two is the only even and also the smallest prime number. First few prime numbers are 2, 3, 5, 7, 11, 13, 17....etc. Prime numbers have many applications in computer science and mathematics. A number greater than one can be factorized into prime numbers, For example 540 = 22*33*51 Prime number program in c language #include<stdio.h> int main() { int n, i = 3, count, c; printf("Enter the number of prime numbers requiredn"); scanf("%d",&n); if ( n >= 1 ) { printf("First %d prime numbers are :n",n); printf("2n"); }
  • 41. for ( count = 2 ; count <= n ; ) { for ( c = 2 ; c <= i - 1 ; c++ ) { if ( i%c == 0 ) break; } if ( c == i ) { printf("%dn",i); count++; } i++; } return 0; } Download Prime number program. Output of program: C program for prime number or not #include<stdio.h> main() { int n, c = 2; printf("Enter a number to check if it is primen"); scanf("%d",&n); for ( c = 2 ; c <= n - 1 ; c++ ) { if ( n%c == 0 ) {
  • 42. printf("%d is not prime.n", n); break; } } if ( c == n ) printf("%d is prime.n", n); return 0; } C program for prime number using function #include<stdio.h> int check_prime(int); main() { int n, result; printf("Enter an integer to check whether it is prime or not.n"); scanf("%d",&n); result = check_prime(n); if ( result == 1 ) printf("%d is prime.n", n); else printf("%d is not prime.n", n); return 0; } int check_prime(int a) { int c; for ( c = 2 ; c <= a - 1 ; c++ ) { if ( a%c == 0 ) return 0; } if ( c == a ) return 1; } There are many logic to check prime numbers, one given below is more efficient then above method. for ( c = 2 ; c <= (int)sqrt(n) ; c++ ) Only checking from 2 to square root of number is sufficient. There are many more efficient logic available.
  • 43. Armstrong number c program Armstrong number c program: c programming code to check whether a number is Armstrong or not. Armstrong number is a number which is equal to sum of digits raise to the power total number of digits in the number. Some Armstrong numbers are: 0, 1, 2, 3, 153, 370, 407, 1634, 8208 etc. Read more about Armstrong numbers at Wikipedia. We will consider base 10 numbers in our program. Algorithm to check Armstrong is: First we calculate number of digits in our program and then compute sum of individual digits raise to the power number of digits. If this sum equals input number then number is Armstrong otherwise not an Armstrong number. Examples: 7 = 7^1 371 = 3^3 + 7^3 + 1^3 (27 + 343 +1) 8208 = 8^4 + 2^4 +0^4 + 8^4 (4096 + 16 + 0 + 4096). 1741725 = 1^7 + 7^7 + 4^7 + 1^7 + 7^7 + 2^7 +5^7 (1 + 823543 + 16384 + 1 + 823543 +128 + 78125) C programming code #include <stdio.h> int power(int, int); int main() { int n, sum = 0, temp, remainder, digits = 0; printf("Input an integern"); scanf("%d", &n); temp = n; // Count number of digits while (temp != 0) { digits++; temp = temp/10; } temp = n; while (temp != 0) { remainder = temp%10; sum = sum + power(remainder, digits); temp = temp/10; } if (n == sum) printf("%d is an Armstrong number.n", n); else printf("%d is not an Armstrong number.n", n); return 0;
  • 44. } int power(int n, int r) { int c, p = 1; for (c = 1; c <= r; c++) p = p*n; return p; } Download Check Armstrong number program. Output of program: C program to check Armstrong number using function We will use long long data type in our program so that we can check numbers up to 2^64-1. #include <stdio.h> int check_armstrong(long long); long long power(int, int); int main () { long long n; printf("Input a numbern"); scanf("%lld", &n); if (check_armstrong(n) == 1) printf("%lld is an armstrong number.n", n); else printf("%lld is not an armstrong number.n", n); return 0; } int check_armstrong(long long n) { long long sum = 0, temp; int remainder, digits = 0; temp = n; while (temp != 0) { digits++; temp = temp/10;
  • 45. } temp = n; while (temp != 0) { remainder = temp%10; sum = sum + power(remainder, digits); temp = temp/10; } if (n == sum) return 1; else return 0; } long long power(int n, int r) { int c; long long p = 1; for (c = 1; c <= r; c++) p = p*n; return p; } Output of program: Input a number 35641594208964132 35641594208964132 is an Armstrong number. C program to generate and print armstrong numbers C program to generate Armstrong numbers. In our program user will input two integers and we will print all Armstrong numbers between two integers. Using a for loop we will check numbers in the desired range. In our loop we call our function check_armstrong which returns 1 if number is Armstrong and 0 otherwise. If you are not familiar with Armstrong numbers see Check Armstrong number program. C programming code #include <stdio.h> int check_armstrong(int); int power(int, int); int main () { int c, a, b; printf("Input two integersn"); scanf("%d%d", &a, &b);
  • 46. for (c = a; c <= b; c++) { if (check_armstrong(c) == 1) printf("%dn", c); } return 0; } int check_armstrong(int n) { long long sum = 0, temp; int remainder, digits = 0; temp = n; while (temp != 0) { digits++; temp = temp/10; } temp = n; while (temp != 0) { remainder = temp%10; sum = sum + power(remainder, digits); temp = temp/10; } if (n == sum) return 1; else return 0; } int power(int n, int r) { int c, p = 1; for (c = 1; c <= r; c++) p = p*n; return p; } Download Generate Armstrong numbers program.
  • 47. Output of program: In the sample output we are printing Armstrong numbers in range [0, 1000000]. Fibonacci series inc Fibonacci series in c programming: c program for Fibonacci series without and with recursion. Using the code below you can print as many numbers of terms of series as desired. Numbers of Fibonacci sequence are known as Fibonacci numbers. First few numbers of series are 0, 1, 1, 2, 3, 5, 8 etc, Except first two terms in sequence every other term is the sum of two previous terms, For example 8 = 3 + 5 (addition of 3, 5). This sequence has many applications in mathematics and Computer Science. Fibonacci series in c using for loop /* Fibonacci Series c language */ #include<stdio.h> int main() { int n, first = 0, second = 1, next, c; printf("Enter the number of termsn"); scanf("%d",&n); printf("First %d terms of Fibonacci series are :-n",n); for ( c = 0 ; c < n ; c++ )
  • 48. { if ( c <= 1 ) next = c; else { next = first + second; first = second; second = next; } printf("%dn",next); } return 0; } Output of program: Fibonacci series program in c using recursion #include<stdio.h> int Fibonacci(int); main() { int n, i = 0, c; scanf("%d",&n); printf("Fibonacci seriesn"); for ( c = 1 ; c <= n ; c++ ) { printf("%dn", Fibonacci(i)); i++; } return 0; }
  • 49. int Fibonacci(int n) { if ( n == 0 ) return 0; else if ( n == 1 ) return 1; else return ( Fibonacci(n-1) + Fibonacci(n-2) ); } Recursion method is less efficient as it involves function calls which uses stack, also there are chances of stack overflow if function is called frequently for calculating larger Fibonacci numbers. C program to print Floyd's triangle C program to print Floyd's triangle:- This program prints Floyd's triangle. Number of rows of Floyd's triangle to print is entered by the user. First four rows of Floyd's triangle are as follows :- 1 2 3 4 5 6 7 8 9 10 It's clear that in Floyd's triangle nth row contains n numbers. C programming code #include <stdio.h> int main() { int n, i, c, a = 1; printf("Enter the number of rows of Floyd's triangle to printn"); scanf("%d", &n); for (i = 1; i <= n; i++) { for (c = 1; c <= i; c++) { printf("%d ",a); a++; } printf("n"); } return 0; } Download Floyd triangle program.
  • 50. Output of program: C program to print Floyd's triangle using recursion #include <stdio.h> void print_floyd(int); int main() { int n, i, c, a = 1; printf("Input number of rows of Floyd's triangle to printn"); scanf("%d", &n); print_floyd(n); return 0; } void print_floyd(int n) { static int row = 1, c = 1; int d; if (n <= 0) return; for (d = 1; d <= row; ++d) printf("%d ", c++); printf("n"); row++; print_floyd(--n); }
  • 51. C program to print Pascal triangle Pascal Triangle in c: C program to print Pascal triangle which you might have studied in Binomial Theorem in Mathematics. Number of rows of Pascal triangle to print is entered by the user. First four rows of Pascal triangle are shown below :- 1 1 1 1 2 1 1 3 3 1 Pascal triangle in c #include <stdio.h> long factorial(int); int main() { int i, n, c; printf("Enter the number of rows you wish to see in pascal trianglen"); scanf("%d",&n); for (i = 0; i < n; i++) { for (c = 0; c <= (n - i - 2); c++) printf(" "); for (c = 0 ; c <= i; c++) printf("%ld ",factorial(i)/(factorial(c)*factorial(i-c))); printf("n"); } return 0; } long factorial(int n) { int c; long result = 1; for (c = 1; c <= n; c++) result = result*c; return result; } Download Pascal triangle program.
  • 52. Output of program: C program to find maximum element in array This code find maximum or largest element present in an array. It also prints the location or index at which maximum element occurs in array. This can also be done by using pointers (see both codes). The algorithm to find maximum is first we assume that maximum element occurs at beginning of array and stores that value in a variable. Then we compare it with other array elements one by one, if any element is greater than our assumed maximum then maximum value and index at which it occurs is updated. Similarly we can find minimum element in an array. C programming code #include <stdio.h> int main() { int array[100], maximum, size, c, location = 1; printf("Enter the number of elements in arrayn"); scanf("%d", &size); printf("Enter %d integersn", size); for (c = 0; c < size; c++) scanf("%d", &array[c]); maximum = array[0]; for (c = 1; c < size; c++) { if (array[c] > maximum) { maximum = array[c]; location = c+1; } }
  • 53. printf("Maximum element is present at location %d and it's value is %d.n", location, maximum); return 0; } If maximum occurs two or more times times in array then index at which it occurs first is printed or maximum value at smallest index. You can easily modify this code this code to print largest index at which maximum occur. You can also store all indices at which maximum occur in an array. Download Maximum element in array program. Output of program: C programming code to find maximum using function Our function returns index at which maximum element occur. #include <stdio.h> int find_maximum(int[], int); int main() { int c, array[100], size, location, maximum; printf("Input number of elements in arrayn"); scanf("%d", &size); printf("Enter %d integersn", size); for (c = 0; c < size; c++) scanf("%d", &array[c]); location = find_maximum(array, size); maximum = array[location]; printf("Maximum element location = %d and value = %d.n", location + 1, maximum); return 0; }
  • 54. int find_maximum(int a[], int n) { int c, max, index; max = a[0]; index = 0; for (c = 1; c < n; c++) { if (a[c] > max) { index = c; max = a[c]; } } return index; } C programming code using pointers #include <stdio.h> int main() { long array[100], *maximum, size, c, location = 1; printf("Enter the number of elements in arrayn"); scanf("%ld", &size); printf("Enter %ld integersn", size); for ( c = 0 ; c < size ; c++ ) scanf("%ld", &array[c]); maximum = array; *maximum = *array; for (c = 1; c < size; c++) { if (*(array+c) > *maximum) { *maximum = *(array+c); location = c+1; } } printf("Maximum element found at location %ld and it's value is %ld.n", location, *maximum); return 0; } The complexity of above code is O(n) as the time used depends on the size of input array or in other words time to find maximum increases linearly as array size grows.
  • 55. C program to find minimum element in array C code to find minimum or smallest element present in an array. It also prints the location or index at which minimum element occurs in array. This can also be done by using pointers (see both the codes). Our algorithm first assumes first element as minimum and then compare it with other elements if an element is smaller than it then it becomes the new minimum and this process is repeated till complete array is scanned. C programming code #include <stdio.h> int main() { int array[100], minimum, size, c, location = 1; printf("Enter the number of elements in arrayn"); scanf("%d",&size); printf("Enter %d integersn", size); for ( c = 0 ; c < size ; c++ ) scanf("%d", &array[c]); minimum = array[0]; for ( c = 1 ; c < size ; c++ ) { if ( array[c] < minimum ) { minimum = array[c]; location = c+1; } } printf("Minimum element is present at location %d and it's value is %d.n", location, minimum); return 0; } If minimum occurs two or more times times in array then index at which it occurs first is printed or minimum value at smallest index. You can modify this code this code to print largest index at which minimum occur. You can also store all indices at which minimum occur in an array. Download Minimum element in array program.
  • 56. Output of program: C programming code to find minimum using function Our function returns index at which minimum element occur. #include <stdio.h> int find_minimum(int[], int); int main() { int c, array[100], size, location, minimum; printf("Input number of elements in arrayn"); scanf("%d", &size); printf("Input %d integersn", size); for (c = 0; c < size; c++) scanf("%d", &array[c]); location = find_minimum(array, size); minimum = array[location]; printf("Minimum element location = %d and value = %d.n", location + 1, minimum); return 0; } int find_minimum(int a[], int n) { int c, min, index; min = a[0]; index = 0; for (c = 1; c < n; c++) { if (a[c] < min) { index = c; min = a[c]; } }
  • 57. return index; } C programming code using pointers #include <stdio.h> int main() { int array[100], *minimum, size, c, location = 1; printf("Enter the number of elements in arrayn"); scanf("%d",&size); printf("Enter %d integersn", size); for ( c = 0 ; c < size ; c++ ) scanf("%d", &array[c]); minimum = array; *minimum = *array; for ( c = 1 ; c < size ; c++ ) { if ( *(array+c) < *minimum ) { *minimum = *(array+c); location = c+1; } } printf("Minimum element found at location %d and it's value is %d.n", location, *minimum); return 0; } C program to insert an element in an array This code will insert an element into an array, For example consider an array a[10] having three elements in it initially and a[0] = 1, a[1] = 2 and a[2] = 3 and you want to insert a number 45 at location 1 i.e. a[0] = 45, so we have to move elements one step below so after insertion a[1] = 1 which was a[0] initially, and a[2] = 2 and a[3] = 3. Array insertion does not mean increasing its size i.e array will not be containing 11 elements. C programming code #include <stdio.h> int main() { int array[100], position, c, n, value;
  • 58. printf("Enter number of elements in arrayn"); scanf("%d", &n); printf("Enter %d elementsn", n); for (c = 0; c < n; c++) scanf("%d", &array[c]); printf("Enter the location where you wish to insert an elementn"); scanf("%d", &position); printf("Enter the value to insertn"); scanf("%d", &value); for (c = n - 1; c >= position - 1; c--) array[c+1] = array[c]; array[position-1] = value; printf("Resultant array isn"); for (c = 0; c <= n; c++) printf("%dn", array[c]); return 0; } Download Insert element in array program. Output of program:
  • 59. C program to delete an element from an array This program delete an element from an array. Deleting an element does not affect the size of array. It is also checked whether deletion is possible or not, For example if array is containing five elements and you want to delete element at position six which is not possible. C programming code #include <stdio.h> int main() { int array[100], position, c, n; printf("Enter number of elements in arrayn"); scanf("%d", &n); printf("Enter %d elementsn", n); for ( c = 0 ; c < n ; c++ ) scanf("%d", &array[c]); printf("Enter the location where you wish to delete elementn"); scanf("%d", &position); if ( position >= n+1 ) printf("Deletion not possible.n"); else { for ( c = position - 1 ; c < n - 1 ; c++ ) array[c] = array[c+1]; printf("Resultant array isn"); for( c = 0 ; c < n - 1 ; c++ ) printf("%dn", array[c]); } return 0; } Download Delete element from array program.
  • 60. Output of program: C program to merge two arrays C program to merge two arrays into third array: Arrays are assumed to be sorted in ascending order. You enter two short sorted arrays and combine them to get a large array. C programming code to merge two sorted arrays #include <stdio.h> void merge(int [], int, int [], int, int []); int main() { int a[100], b[100], m, n, c, sorted[200]; printf("Input number of elements in first arrayn"); scanf("%d", &m); printf("Input %d integersn", m); for (c = 0; c < m; c++) { scanf("%d", &a[c]); } printf("Input number of elements in second arrayn"); scanf("%d", &n); printf("Input %d integersn", n); for (c = 0; c < n; c++) { scanf("%d", &b[c]); } merge(a, m, b, n, sorted);
  • 61. printf("Sorted array:n"); for (c = 0; c < m + n; c++) { printf("%dn", sorted[c]); } return 0; } void merge(int a[], int m, int b[], int n, int sorted[]) { int i, j, k; j = k = 0; for (i = 0; i < m + n;) { if (j < m && k < n) { if (a[j] < b[k]) { sorted[i] = a[j]; j++; } else { sorted[i] = b[k]; k++; } i++; } else if (j == m) { for (; i < m + n;) { sorted[i] = b[k]; k++; i++; } } else { for (; i < m + n;) { sorted[i] = a[j]; j++; i++; } } } } Download Merge arrays program.
  • 62. Output of program: If the arrays are not sorted then you can sort them first and then use the above merge function, another method is to merge them and then sort the array. Sorting two smaller arrays will take less time as compared to sorting a big array. Merging two sorted array is used in merge sort algorithm. C program to reverse an array C program to reverse an array: This program reverses the array elements. For example if a is an array of integers with three elements such that a[0] = 1 a[1] = 2 a[2] = 3 Then on reversing the array will be a[0] = 3 a[1] = 2 a[0] = 1 Given below is the c code to reverse an array. C programming code #include <stdio.h> int main() {
  • 63. int n, c, d, a[100], b[100]; printf("Enter the number of elements in arrayn"); scanf("%d", &n); printf("Enter the array elementsn"); for (c = 0; c < n ; c++) scanf("%d", &a[c]); /* * Copying elements into array b starting from end of array a */ for (c = n - 1, d = 0; c >= 0; c--, d++) b[d] = a[c]; /* * Copying reversed array into original. * Here we are modifying original array, this is optional. */ for (c = 0; c < n; c++) a[c] = b[c]; printf("Reverse array isn"); for (c = 0; c < n; c++) printf("%dn", a[c]); return 0; } Download Reverse array program. Output of program:
  • 64. Reverse array by swapping (without using additional memory) #include <stdio.h> int main() { int array[100], n, c, t, end; scanf("%d", &n); end = n - 1; for (c = 0; c < n; c++) { scanf("%d", &array[c]); } for (c = 0; c < n/2; c++) { t = array[c]; array[c] = array[end]; array[end] = t; end--; } printf("Reversed array elements are:n"); for (c = 0; c < n; c++) { printf("%dn", array[c]); } return 0; } C program to reverse an array using pointers #include <stdio.h> #include <stdlib.h> void reverse_array(int*, int); int main() { int n, c, *pointer; scanf("%d",&n); pointer = (int*)malloc(sizeof(int)*n); if( pointer == NULL ) exit(EXIT_FAILURE); for ( c = 0 ; c < n ; c++ ) scanf("%d",(pointer+c)); reverse_array(pointer, n);
  • 65. printf("Original array on reversal isn"); for ( c = 0 ; c < n ; c++ ) printf("%dn",*(pointer+c)); free(pointer); return 0; } void reverse_array(int *pointer, int n) { int *s, c, d; s = (int*)malloc(sizeof(int)*n); if( s == NULL ) exit(EXIT_FAILURE); for ( c = n - 1, d = 0 ; c >= 0 ; c--, d++ ) *(s+d) = *(pointer+c); for ( c = 0 ; c < n ; c++ ) *(pointer+c) = *(s+c); free(s); } Array is passed to function and a new array is created and contents of passed array (in reverse order) are copied into it and finally contents of new array are copied into array passed to function. C program to add two matrix This c program add two matrices i.e. compute the sum of two matrices and then print it. Firstly user will be asked to enter the order of matrix (number of rows and columns) and then two matrices. For example if the user entered order as 2, 2 i.e. two rows and two columns and matrices as First Matrix :- 1 2 3 4 Second matrix :- 4 5 -1 5 then output of the program (sum of First and Second matrix) will be 5 7 2 9 C programming code
  • 66. #include <stdio.h> int main() { int m, n, c, d, first[10][10], second[10][10], sum[10][10]; printf("Enter the number of rows and columns of matrixn"); scanf("%d%d", &m, &n); printf("Enter the elements of first matrixn"); for (c = 0; c < m; c++) for (d = 0; d < n; d++) scanf("%d", &first[c][d]); printf("Enter the elements of second matrixn"); for (c = 0; c < m; c++) for (d = 0 ; d < n; d++) scanf("%d", &second[c][d]); printf("Sum of entered matrices:-n"); for (c = 0; c < m; c++) { for (d = 0 ; d < n; d++) { sum[c][d] = first[c][d] + second[c][d]; printf("%dt", sum[c][d]); } printf("n"); } return 0; } Download Add Matrix program. Output of program:
  • 67. Subtract matrices C code to subtract matrices of any order. This program finds difference between corresponding elements of two matrices and then print the resultant matrix. C programming code #include <stdio.h> int main() { int m, n, c, d, first[10][10], second[10][10], difference[10][10]; printf("Enter the number of rows and columns of matrixn"); scanf("%d%d", &m, &n); printf("Enter the elements of first matrixn"); for (c = 0; c < m; c++) for (d = 0 ; d < n; d++) scanf("%d", &first[c][d]); printf("Enter the elements of second matrixn"); for (c = 0; c < m; c++) for (d = 0; d < n; d++) scanf("%d", &second[c][d]); printf("Difference of entered matrices:-n"); for (c = 0; c < m; c++) { for (d = 0; d < n; d++) { difference[c][d] = first[c][d] - second[c][d]; printf("%dt",difference[c][d]); } printf("n"); } return 0; } Download Subtract matrices program.
  • 68. Output of program: C program to transpose a matrix This c program prints transpose of a matrix. It is obtained by interchanging rows and columns of a matrix. For example if a matrix is 1 2 3 4 5 6 then transpose of above matrix will be 1 3 5 2 4 6 When we transpose a matrix then the order of matrix changes, but for a square matrix order remains same. C programming code #include <stdio.h> int main() { int m, n, c, d, matrix[10][10], transpose[10][10]; printf("Enter the number of rows and columns of matrixn"); scanf("%d%d", &m, &n); printf("Enter the elements of matrixn"); for (c = 0; c < m; c++) for(d = 0; d < n; d++) scanf("%d",&matrix[c][d]); for (c = 0; c < m; c++) for( d = 0 ; d < n ; d++ ) transpose[d][c] = matrix[c][d];
  • 69. printf("Transpose of entered matrix :-n"); for (c = 0; c < n; c++) { for (d = 0; d < m; d++) printf("%dt",transpose[c][d]); printf("n"); } return 0; } Download Transpose Matrix program. Output of program: Matrix multiplicationin c Matrix multiplication in c language: c program to multiply matrices (two dimensional array), this program multiplies two matrices which will be entered by the user. Firstly user will enter the order of a matrix. If the entered orders of two matrix is such that they can't be multiplied then an error message is displayed on the screen. You have already studied the logic to multiply them in Mathematics. Matrix multiplication in c language #include <stdio.h> int main() { int m, n, p, q, c, d, k, sum = 0; int first[10][10], second[10][10], multiply[10][10]; printf("Enter the number of rows and columns of first matrixn"); scanf("%d%d", &m, &n); printf("Enter the elements of first matrixn");
  • 70. for (c = 0; c < m; c++) for (d = 0; d < n; d++) scanf("%d", &first[c][d]); printf("Enter the number of rows and columns of second matrixn"); scanf("%d%d", &p, &q); if (n != p) printf("Matrices with entered orders can't be multiplied with each other.n"); else { printf("Enter the elements of second matrixn"); for (c = 0; c < p; c++) for (d = 0; d < q; d++) scanf("%d", &second[c][d]); for (c = 0; c < m; c++) { for (d = 0; d < q; d++) { for (k = 0; k < p; k++) { sum = sum + first[c][k]*second[k][d]; } multiply[c][d] = sum; sum = 0; } } printf("Product of entered matrices:-n"); for (c = 0; c < m; c++) { for (d = 0; d < q; d++) printf("%dt", multiply[c][d]); printf("n"); } } return 0; } Download Matrix multiplication program.
  • 71. A 3 X 3 matrix multiply in c is shown as example below. Matrices are frequently used while doing programming and are used to represent graph data structure, in solving system of linear equations and many more. Lot of research is being done on how to multiply matrices using minimum number of operations. You can also implement it using pointers. C program print string This program print a string. String can be printed by using various functions such as printf, puts. C programming code #include <stdio.h> int main() { char array[20] = "Hello World"; printf("%sn",array); return 0; } To input a string we use scanf function. C programming code #include <stdio.h>
  • 72. int main() { char array[100]; printf("Enter a stringn"); scanf("%s", array); printf("You entered the string %sn",array); return 0; } Input stringcontainingspaces #include <stdio.h> int main() { char a[80]; gets(a); printf("%sn", a); return 0; } Note that scanf can only input single word strings, to receive strings containing spaces use gets function. C programto print stringusingrecursion #include <stdio.h> void print(char*); int main() { char s[100]; gets(s); print(s); return 0; } void print(char *t) { if (*t == '0') return; printf("%c", *t); print(++t); } Print stringusingloop We print string using for loop by printing individual characters of string. #include <stdio.h> #include <string.h>
  • 73. int main() { char s[100]; int c, l; gets(s); l = strlen(s); for (c = 0; c < l; c++) printf("%c", s[c]); return 0; } String length This program prints length of string, for example consider the string "c programming" it's length is 13. Null character is not counted when calculating string length. To find string length we use strlen function of string.h. C program to find string length #include <stdio.h> #include <string.h> int main() { char a[100]; int length; printf("Enter a string to calculate it's lengthn"); gets(a); length = strlen(a); printf("Length of entered string is = %dn",length); return 0; } Download String length program. Output of program:
  • 74. C program to find string length without strlen You can also find string length without strlen function. We create our own function to find string length. #include <stdio.h> int string_length(char []); int main() { char s[1000]; int length; printf("Input a stringn"); gets(s); length = string_length(s); printf("Length of "%s" = %dn", s, length); return 0; } int string_length(char s[]) { int c = 0; while (s[c] != '0') c++; return c; } Function to find string length using pointers int string_length(char *s) { int c = 0; while(*(s+c)) c++; return c; } C program to compare two strings This c program compares two strings using strcmp, without strcmp and using pointers. For comparing strings without using library function see another code below. C program to compare two strings using strcmp
  • 75. #include <stdio.h> #include <string.h> int main() { char a[100], b[100]; printf("Enter the first stringn"); gets(a); printf("Enter the second stringn"); gets(b); if (strcmp(a,b) == 0) printf("Entered strings are equal.n"); else printf("Entered strings are not equal.n"); return 0; } Function strcmp is case sensitive and returns 0 if both strings are equal. Download Compare Strings program. Output of program: C program to compare two strings without using strcmp Here we create our own function to compare strings. #include <stdio.h> int compare_strings(char [], char []); int main() { int flag; char a[1000], b[1000]; printf("Input first stringn"); gets(a); printf("Input second stringn");
  • 76. gets(b); flag = compare_strings(a, b); if (flag == 0) printf("Entered strings are equal.n"); else printf("Entered strings are not equal.n"); return 0; } int compare_strings(char a[], char b[]) { int c = 0; while (a[c] == b[c]) { if (a[c] == '0' || b[c] == '0') break; c++; } if (a[c] == '0' && b[c] == '0') return 0; else return -1; } C program to compare two strings using pointers In this method we will make our own function to perform string comparison, we will use character pointers in our function to manipulate string. #include<stdio.h> int compare_string(char*, char*); int main() { char first[1000], second[1000], result; printf("Input first stringn"); gets(first); printf("Input second stringn"); gets(second); result = compare_string(first, second); if (result == 0) printf("Both strings are same.n"); else printf("Entered strings are not equal.n"); return 0;
  • 77. } int compare_string(char *first, char *second) { while (*first == *second) { if (*first == '0' || *second == '0') break; first++; second++; } if (*first == '0' && *second == '0') return 0; else return -1; } String copying in c programming This program copy string using library function strcpy, to copy string without using strcpy see source code below in which we have made our own function to copy string. C program to copy a string #include <stdio.h> #include <string.h> int main() { char source[1000], destination[1000]; printf("Input a stringn"); gets(source); strcpy(destination, source); printf("Source string: "%s"n", source); printf("Destination string: "%s"n", destination); return 0; } Output of program:
  • 78. C program to copy string without using strcpy We create our own function to copy string and do not use the library function strcpy. #include <stdio.h> #include <string.h> void copy_string(char [], char []); int main() { char s[1000], d[1000]; printf("Input a stringn"); gets(s); copy_string(d, s); printf("Source string: "%s"n", s); printf("Destination string: "%s"n", d); return 0; } void copy_string(char d[], char s[]) { int c = 0; while (s[c] != '0') { d[c] = s[c]; c++; } d[c] = '0'; } C program to copy a string using pointers Function to copy string using pointers. void copy_string(char *target, char *source) { while (*source) { *target = *source; source++; target++; } *target = '0'; } C program to concatenate strings This program concatenates strings, for example if the first string is "c " and second string is "program" then on concatenating these two strings we get the string "c program". To concatenate
  • 79. two strings we use strcat function of string.h, to concatenate without using library function see another code below which uses pointers. C programming code #include <stdio.h> #include <string.h> int main() { char a[1000], b[1000]; printf("Enter the first stringn"); gets(a); printf("Enter the second stringn"); gets(b); strcat(a,b); printf("String obtained on concatenation is %sn",a); return 0; } Download String Concatenation program. Output of program: Concatenate strings without strcat function C program to concatenate strings without using library function strcat of string.h header file. We create our own function. #include <stdio.h> void concatenate(char [], char []); int main() { char p[100], q[100]; printf("Input a stringn");
  • 80. gets(p); printf("Input a string to concatenaten"); gets(q); concatenate(p, q); printf("String obtained on concatenation is "%s"n", p); return 0; } void concatenate(char p[], char q[]) { int c, d; c = 0; while (p[c] != '0') { c++; } d = 0; while (q[d] != '0') { p[c] = q[d]; d++; c++; } p[c] = '0'; } The first for loop in concatenate function is calculating string length so you can also use strlen function if you wish. String concatenation using pointers #include <stdio.h> void concatenate_string(char*, char*); int main() { char original[100], add[100]; printf("Enter source stringn"); gets(original); printf("Enter string to concatenaten"); gets(add); concatenate_string(original, add); printf("String after concatenation is "%s"n", original);
  • 81. return 0; } void concatenate_string(char *original, char *add) { while(*original) original++; while(*add) { *original = *add; add++; original++; } *original = '0'; } Reverse string This program reverses a string entered by the user. For example if a user enters a string "reverse me" then on reversing the string will be "em esrever". We show you four different methods to reverse string the first one uses strrev library function of string.h header file, second without using strrev and in third we make our own function to reverse string using pointers, reverse string using recursion and Reverse words in string. If you are using first method then you must include string.h in your program. C programming code /* String reverse in c*/ #include <stdio.h> #include <string.h> int main() { char arr[100]; printf("Enter a string to reversen"); gets(arr); strrev(arr); printf("Reverse of entered string is n%sn",arr); return 0; } Download Reverse string program.
  • 82. Output of program: C program to reverse string without using function Below code does not uses strrev library function to reverse a string. First we calculate the length of string using strlen function and then assigns characters of input string in reverse order to create a new string using a for loop. You can also calculate length of string without using strlen. We use comma operator in for loop to initialize multiple variables and increment/decrement variables. #include <stdio.h> #include <string.h> int main() { char s[100], r[100]; int n, c, d; printf("Input a stringn"); gets(s); n = strlen(s); for (c = n - 1, d = 0; c >= 0; c--, d++) r[d] = s[c]; r[d] = '0'; printf("%sn", r); return 0; } C program to reverse a string using pointers Now we will invert string using pointers or without using library function strrev. #include<stdio.h> int string_length(char*); void reverse(char*); main() {
  • 83. char string[100]; printf("Enter a stringn"); gets(string); reverse(string); printf("Reverse of entered string is "%s".n", string); return 0; } void reverse(char *string) { int length, c; char *begin, *end, temp; length = string_length(string); begin = string; end = string; for (c = 0; c < length - 1; c++) end++; for (c = 0; c < length/2; c++) { temp = *end; *end = *begin; *begin = temp; begin++; end--; } } int string_length(char *pointer) { int c = 0; while( *(pointer + c) != '0' ) c++; return c; } C program to reverse a string using recursion #include <stdio.h> #include <string.h> void reverse(char*, int, int); int main() { char a[100];
  • 84. gets(a); reverse(a, 0, strlen(a)-1); printf("%sn",a); return 0; } void reverse(char *x, int begin, int end) { char c; if (begin >= end) return; c = *(x+begin); *(x+begin) = *(x+end); *(x+end) = c; reverse(x, ++begin, --end); } In recursion method we swap characters at the begin and at the end and then move towards the middle of the string. This method is inefficient due to repeated function calls but useful in practicing recursion. C palindrome program,c program for palindrome C program for palindrome or palindrome in c programming: palindrome program in c language, c code to check if a string is a palindrome or not and for palindrome number. This program works as follows :- at first we copy the entered string into a new string, and then we reverse the new string and then compares it with original string. If both of them have same sequence of characters i.e. they are identical then the entered string is a palindrome otherwise not. To perform copy, reverse and compare operations we use strcpy, strrev and strcmp functions of string.h respectively, if you do not wish to use these functions see c programming code for palindrome without using string functions. Some palindrome strings examples are "a", dad", "radar", "madam", "abcba" etc. C program for palindrome #include <stdio.h> #include <string.h> int main() { char a[100], b[100]; printf("Enter the string to check if it is a palindromen"); gets(a);
  • 85. strcpy(b,a); strrev(b); if (strcmp(a,b) == 0) printf("Entered string is a palindrome.n"); else printf("Entered string is not a palindrome.n"); return 0; } Download palindrome program. Output of program: Palindrome number in c #include <stdio.h> main() { int n, reverse = 0, temp; printf("Enter a number to check if it is a palindrome or notn"); scanf("%d",&n); temp = n; while (temp != 0) { reverse = reverse * 10; reverse = reverse + temp%10; temp = temp/10; } if (n == reverse) printf("%d is a palindrome number.n", n); else printf("%d is not a palindrome number.n", n); return 0; } C program for palindrome without using string functions
  • 86. #include <stdio.h> #include <string.h> int main() { char text[100]; int begin, middle, end, length = 0; gets(text); while (text[length] != '0') length++; end = length - 1; middle = length/2; for (begin = 0; begin < middle; begin++) { if (text[begin] != text[end]) { printf("Not a palindrome.n"); break; } end--; } if (begin == middle) printf("Palindrome.n"); return 0; } C program check palindrome #include <stdio.h> int is_palindrome(char*); void copy_string(char*, char*); void reverse_string(char*); int string_length(char*); int compare_string(char*, char*); int main() { char string[100]; int result; printf("Input a stringn"); gets(string); result = is_palindrome(string); if ( result == 1 ) printf(""%s" is a palindrome string.n", string); else printf(""%s" is not a palindrome string.n", string);
  • 87. return 0; } int is_palindrome(char *string) { int check, length; char *reverse; length = string_length(string); reverse = (char*)malloc(length+1); copy_string(reverse, string); reverse_string(reverse); check = compare_string(string, reverse); free(reverse); if ( check == 0 ) return 1; else return 0; } int string_length(char *string) { int length = 0; while(*string) { length++; string++; } return length; } void copy_string(char *target, char *source) { while(*source) { *target = *source; source++; target++; } *target = '0'; } void reverse_string(char *string) { int length, c; char *begin, *end, temp; length = string_length(string); begin = string;
  • 88. end = string; for ( c = 0 ; c < ( length - 1 ) ; c++ ) end++; for ( c = 0 ; c < length/2 ; c++ ) { temp = *end; *end = *begin; *begin = temp; begin++; end--; } } int compare_string(char *first, char *second) { while(*first==*second) { if ( *first == '0' || *second == '0' ) break; first++; second++; } if( *first == '0' && *second == '0' ) return 0; else return -1; } Pointers are used in functions, you can develop your code without using pointers. C program to convert string to integer without using atoi function C program to convert string to integer: It is frequently required to convert a string to an integer in applications. String should consists of digits only and an optional '-' (minus) sign at beginning for integers. For string containing other characters we can stop conversion as soon as a non digit character is encountered but in our program we will handle ideal case when only valid characters are present in string. Library function atoi can be used to convert string to an integer but we will create our own function. C programming code // C program to convert string to integer without using atoi function #include <stdio.h> int toString(char []); int main() {
  • 89. char a[100]; int n; printf("Input a valid string to convert to integern"); scanf("%s", a); n = toString(a); printf("String = %snInteger = %dn", a, n); return 0; } int toString(char a[]) { int c, sign, offset, n; if (a[0] == '-') { // Handle negative integers sign = -1; } if (sign == -1) { // Set starting position to convert offset = 1; } else { offset = 0; } n = 0; for (c = offset; a[c] != '0'; c++) { n = n * 10 + a[c] - '0'; } if (sign == -1) { n = -n; } return n; } Similarly you can convert string to long. Output of program: Compilerused:
  • 90. GCC C program to delete vowels from a string Remove vowels from a string in c: c program to remove or delete vowels from a string, if the input string is "c programming" then output will be "c prgrmmng". In the program we create a new string and process entered string character by character, and if a vowel is found it is not added to new string otherwise the character is added to new string, after the string ends we copy the new string into original string. Finally we obtain a string without any vowels. C programming code #include <stdio.h> #include <string.h> int check_vowel(char); int main() { char s[100], t[100]; int i, j = 0; printf("Enter a string to delete vowelsn"); gets(s); for(i = 0; s[i] != '0'; i++) { if(check_vowel(s[i]) == 0) { //not a vowel t[j] = s[i]; j++; } } t[j] = '0'; strcpy(s, t); //We are changing initial string printf("String after deleting vowels: %sn", s); return 0; } int check_vowel(char c) { switch(c) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U':
  • 91. return 1; default: return 0; } } Output of program: C programming code using pointers #include<stdio.h> #include<stdlib.h> #include<string.h> #define TRUE 1 #define FALSE 0 int check_vowel(char); main() { char string[100], *temp, *pointer, ch, *start; printf("Enter a stringn"); gets(string); temp = string; pointer = (char*)malloc(100); if( pointer == NULL ) { printf("Unable to allocate memory.n"); exit(EXIT_FAILURE); } start = pointer; while(*temp) { ch = *temp; if ( !check_vowel(ch) ) { *pointer = ch; pointer++; } temp++; }
  • 92. *pointer = '0'; pointer = start; strcpy(string, pointer); /* If you wish to convert original string */ free(pointer); printf("String after removing vowel is "%s"n", string); return 0; } int check_vowel(char a) { if ( a >= 'A' && a <= 'Z' ) a = a + 'a' - 'A'; if ( a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u') return TRUE; return FALSE; } Substring in c programming,c substring Substring in c programming: c programming code to find a substring from a given string and for all substrings of a string, For example substrings of string "the" are "t", "th", "the", "h", "he" and "e" to find substring we create our own c substring function which returns a pointer to string. String address, length of substring required and position from where to extract substring are the three arguments passed to function. String.h does not contain any library function to directly find substring. C substring code #include <stdio.h> int main() { char string[1000], sub[1000]; int position, length, c = 0; printf("Input a stringn"); gets(string); printf("Enter the position and length of substringn"); scanf("%d%d", &position, &length); while (c < length) { sub[c] = string[position+c-1]; c++; } sub[c] = '0';
  • 93. printf("Required substring is "%s"n", sub); return 0; } C substring program output: C substring program using function We create a function and pass it four arguments original string array, substring array, position and length of desired substring. As call by reference is used we do not need to return substring array. See another code below in which we return pointer to substring, which we create in our array using dynamic memory allocation. #include <stdio.h> void substring(char [], char[], int, int); int main() { char string[1000], sub[1000]; int position, length, c = 0; printf("Input a stringn"); gets(string); printf("Enter the position and length of substringn"); scanf("%d%d", &position, &length); substring(string, sub, position, length); printf("Required substring is "%s"n", sub); return 0; } void substring(char s[], char sub[], int p, int l) { int c = 0; while (c < l) { sub[c] = s[p+c-1]; c++; }
  • 94. sub[c] = '0'; } C substring program using pointers #include <stdio.h> #include <stdlib.h> char* substring(char*, int, int); int main() { char string[100], *pointer; int position, length; printf("Input a stringn"); gets(string); printf("Enter the position and length of substringn"); scanf("%d%d",&position, &length); pointer = substring( string, position, length); printf("Required substring is "%s"n", pointer); free(pointer); return 0; } /*C substring function: It returns a pointer to the substring */ char *substring(char *string, int position, int length) { char *pointer; int c; pointer = malloc(length+1); if (pointer == NULL) { printf("Unable to allocate memory.n"); exit(1); } for (c = 0 ; c < length ; c++) { *(pointer+c) = *(string+position-1); string++; } *(pointer+c) = '0'; return pointer; }
  • 95. C code for all substrings of a string #include <stdio.h> #include <string.h> #include <malloc.h> char* substring(char*, int, int); int main() { char string[100], *pointer; int position = 1, length = 1, temp, string_length; printf("Enter a stringn"); gets(string); temp = string_length = strlen(string); printf("Substring of "%s" aren", string); while (position <= string_length) { while (length <= temp) { pointer = substring(string, position, length); printf("%sn", pointer); free(pointer); length++; } temp--; position++; length = 1; } return 0; } /* Use substring function given in above c program*/
  • 96. Substring code output: C program to sort a string in alphabetic order C program to sort a string in alphabetic order: For example if user will enter a string "programming" then output will be "aggimmnoprr" or output string will contain characters in alphabetical order. In our program we assume input string contains only lower case alphabets. First we count and store how many times characters 'a' to 'z' appear in input string and then create another string which contains characters 'a' to 'z' as many times as they appear in the input string. C programming code #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char ch, input[100], output[100]; int no[26] = {0}, n, c, t, x; printf("Enter some textn"); scanf("%s", input); n = strlen(input); /** Store how many times characters (a to z) appears in input string in array */ for (c = 0; c < n; c++) { ch = input[c] - 'a'; no[ch]++; }
  • 97. t = 0; /** Insert characters a to z in output string that many number of times as they appear in input string */ for (ch = 'a'; ch <= 'z'; ch++) { x = ch - 'a'; for (c = 0; c < no[x]; c++) { output[t] = ch; t++; } } output[t] = '0'; printf("%sn", output); return 0; } Output of program: C program using pointers #include <stdio.h> #include <stdlib.h> #include <string.h> void sort_string(char*); int main() { char string[100]; printf("Enter some textn"); gets(string); sort_string(string); printf("%sn", string); return 0; } void sort_string(char *s)
  • 98. { int c, d = 0, length; char *pointer, *result, ch; length = strlen(s); result = (char*)malloc(length+1); pointer = s; for ( ch = 'a' ; ch <= 'z' ; ch++ ) { for ( c = 0 ; c < length ; c++ ) { if ( *pointer == ch ) { *(result+d) = *pointer; d++; } pointer++; } pointer = s; } *(result+d) = '0'; strcpy(s, result); free(result); }