SlideShare a Scribd company logo
PROGRAMMING EXAMPLES
Check Whether a Number is Even or Odd
/*C program to check whether a number entered by user is even or odd. */
#include <stdio.h>
int main(){
int num;
printf("Enter an integer you want to check: ");
scanf("%d",&num);
if((num%2)==0) /* Checking whether remainder is 0 or not. */
printf("%d is even.",num);
else
printf("%d is odd.",num);
return 0;
}
Output 1
Enter an integer you want to check: 25
25 is odd.
Output 2
Enter an integer you want to check: 12
12 is even.
In this program, user is asked to enter an integer which is stored in variable num. Then,
the remainder is found when that number is divided by 2 and checked whether remainder
is 0 or not. If remainder is 0 then, that number is even otherwise that number is odd.
This task is performed using if...else statement in C programming and the result is
displayed accordingly.
This program also can be solved using conditional operator[ ?: ] which is the shorthand
notation for if...else statement.
/* C program to check whether an integer is odd or even using conditional operator */
#include <stdio.h>
int main(){
int num;
printf("Enter an integer you want to check: ");
scanf("%d",&num);
((num%2)==0) ? printf("%d is even.",num) : printf("%d is odd.",num);
return 0;
}
C Program to Print a Integer Entered by a User
#include <stdio.h>
int main()
{
int num;
printf("Enter a integer: ");
scanf("%d",&num); /* Storing a integer entered by user in variable num */
printf("You entered: %d",num);
return 0;
}
Output
Enter a integer: 25
You entered: 25
In this program, a variable num is declared of type integer using keyword int.
The printf() function prints the content inside quotation mark which is "Enter a integer: ".
Then, the scanf() takes integer value from user and stores it in variable num. Finally, the
value entered by user is displayed in the screen using printf().
C Program to Count Number of Digits of an Integer
#include <stdio.h>
int main()
{
int n,count=0;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
n/=10; /* n=n/10 */
++count;
}
printf("Number of digits: %d",count);
}
Output
Enter an integer: 34523
Number of digits: 5
This program takes an integer from user and stores that number in variable n. Suppose,
user entered 34523. Then, while loop is executed because n!=0 will be true in first
iteration. The codes inside while loop will be executed. After first iteration, value of n
will be 3452 and count will be 1. Similarly, in second iteration n will be equal to 345
and count will be equal to 2. This process goes on and after fourth iteration, n will be
equal to 3 and count will be equal to 4. Then, in next iteration n will be equal to 0
and count will be equal to 5 and program will be terminated as n!=0 becomes false.
Check Character is an alphabet or not
/* C programming code to check whether a character is alphabet or not.*/
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
if( (c>='a'&& c<='z') || (c>='A' && c<='Z'))
printf("%c is an alphabet.",c);
else
printf("%c is not an alphabet.",c);
return 0;
}
Output 1
Enter a character: *
* is not an alphabet
Output 2
Enter a character: K
K is an alphabet
When a character is stored in a variable, ASCII value of that character is stored instead
of that character itself. For example: If 'a' is stored in a variable, ASCII value of 'a'
which is 97 is stored. If you see the ASCII table, the lowercase alphabets are from 97 to
122 and uppercase letter are from 65 to 90. If the ASCII value of number stored is
between any of these two intervals then, that character will be an alphabet. In this
program, instead of number 97, 122, 65 and 90; we have used 'a', 'z', 'A' and 'Z'
respectively which is basically the same thing.
This program also can be performed using standard library function isalpha().
Find HCF or GCD
/* C Program to Find Highest Common Factor. */
#include <stdio.h>
int main()
{
int num1, num2, i, hcf;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
for(i=1; i<=num1 || i<=num2; ++i)
{
if(num1%i==0 && num2%i==0) /* Checking whether i is a factor of both number */
hcf=i;
}
printf("H.C.F of %d and %d is %d", num1, num2, hcf);
return 0;
}
In this program, two integers are taken from user and stored in variable num1 and num2.
Then i is initialized to 1 and for loop is executed until i becomes equal to smallest of
two numbers. In each looping iteration, it is checked whether i is factor of both numbers
or not. If i is factor of both numbers, it is stored to hcf. When for loop is completed, the
H.C.F of those two numbers will be stored in variable hcf.
Find Factorial of a Number
/* C program to display factorial of an integer if user enters non-negative integer. */
#include <stdio.h>
int main()
{
int n, count;
unsigned long long int factorial=1;
printf("Enter an integer: ");
scanf("%d",&n);
if ( n< 0)
printf("Error!!! Factorial of negative number doesn't exist.");
else
{
for(count=1;count<=n;++count) /* for loop terminates if count>n */
{
factorial*=count; /* factorial=factorial*count */
}
printf("Factorial = %lu",factorial);
}
return 0;
}
Output 1
Enter an integer: -5
Error!!! Factorial of negative number doesn't exist.
Output 2
Enter an integer: 10
Factorial = 3628800
Here the type of factorial variable is declared as: unsigned long long. It is because, the
factorial is always positive, so unsigned keyword is used and the factorial of a number
can be pretty large. For example: the factorial of 10 is 3628800 thus, long long keyword is
used.
Find Number of Vowels, Consonants, Digits and
White Space Character
#include<stdio.h>
int main(){
char line[150];
int i,v,c,ch,d,s,o;
o=v=c=ch=d=s=0;
printf("Enter a line of string:n");
gets(line);
for(i=0;line[i]!='0';++i)
{
if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' ||
line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U')
++v;
else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
++c;
else if(line[i]>='0'&&c<='9')
++d;
else if (line[i]==' ')
++s;
}
printf("Vowels: %d",v);
printf("nConsonants: %d",c);
printf("nDigits: %d",d);
printf("nWhite spaces: %d",s);
return 0;
}
Output
Enter a line of string:
This program is easy 2 understand
Vowels: 9
Consonants: 18
Digits: 1
White spaces: 5
Calculate Length without Using strlen() Function
#include <stdio.h>
int main()
{
char s[1000],i;
printf("Enter a string: ");
scanf("%s",s);
for(i=0; s[i]!='0'; ++i);
printf("Length of string: %d",i);
return 0;
}
Output
Enter a string: Programiz
Length of string: 9
Copy String Manually
#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);
for(i=0; s1[i]!='0'; ++i)
{
s2[i]=s1[i];
}
s2[i]='0';
printf("String s2: %s",s2);
return 0;
}
Output
Enter String s1: programiz
String s2: programiz
This above program copies the content of string s1 to string s2 manually.
Calculate Sum of Natural Numbers
/* This program is solved using while loop. */
#include <stdio.h>
int main()
{
int n, count, sum=0;
printf("Enter an integer: ");
scanf("%d",&n);
count=1;
while(count<=n) /* while loop terminates if count>n */
{
sum+=count; /* sum=sum+count */
++count;
}
printf("Sum = %d",sum);
return 0;
}
Calculate Sum Using for Loop
/* This program is solved using for loop. */
#include <stdio.h>
int main()
{
int n, count, sum=0;
printf("Enter an integer: ");
scanf("%d",&n);
for(count=1;count<=n;++count) /* for loop terminates if count>n */
{
sum+=count; /* sum=sum+count */
}
printf("Sum = %d",sum);
return 0;
}
Output
Enter an integer: 100
Sum = 5050
Both program above does exactly the same thing. Initially, the value of count is set to 1.
Both program have test condition to perform looping iteration until
condition count<=n becomes false and in each iteration ++count is executed.
This program works perfectly for positive number but, if user enters negative number or
0, Sum = 0is displayed but, it is better is display the error message in this case. The
above program can be made user-friendly by adding if else statement as:
/* This program displays error message when user enters negative number or 0 and displays
the sum of natural numbers if user enters positive number. */
#include <stdio.h>
int main()
{
int n, count, sum=0;
printf("Enter an integer: ");
scanf("%d",&n);
if ( n<= 0)
printf("Error!!!!");
else
{
for(count=1;count<=n;++count) /* for loop terminates if count>n */
{
sum+=count; /* sum=sum+count */
}
printf("Sum = %d",sum);
}
return 0;
}
Display Fibonacci series up to n terms
/* Displaying Fibonacci sequence up to nth term where n is entered by user. */
#include <stdio.h>
int main()
{
int count, n, t1=0, t2=1, display=0;
printf("Enter number of terms: ");
scanf("%d",&n);
printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */
count=2; /* count=2 because first two terms are already displayed. */
while (count<n)
{
display=t1+t2;
t1=t2;
t2=display;
++count;
printf("%d+",display);
}
return 0;
}
Output
Enter number of terms: 10
Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+
Suppose, instead of number of terms, you want to display the Fibonacci series util the
term is less than certain number entered by user. Then, this can be done using source
code below:
/* Displaying Fibonacci series up to certain number entered by user. */
#include <stdio.h>
int main()
{
int t1=0, t2=1, display=0, num;
printf("Enter an integer: ");
scanf("%d",&num);
printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */
display=t1+t2;
while(display<num)
{
printf("%d+",display);
t1=t2;
t2=display;
display=t1+t2;
}
return 0;
}
Output
Enter an integer: 200
Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+55+89+144+
Generate Multiplication Table
/* C program to find multiplication table up to 10. */
#include <stdio.h>
int main()
{
int n, i;
printf("Enter an integer to find multiplication table: ");
scanf("%d",&n);
for(i=1;i<=10;++i)
{
printf("%d * %d = %dn", n, i, n*i);
}
return 0;
}
Output
Enter an integer to find multiplication table: 9
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
This program generates multiplication table of an integer up 10. But, this program can be
made more user friendly by giving option to user to enter number up to which, he/she
want to generate multiplication table. The source code below will perform this task.
#include <stdio.h>
int main()
{
int n, range, i;
printf("Enter an integer to find multiplication table: ");
scanf("%d",&n);
printf("Enter range of multiplication table: ");
scanf("%d",&range);
for(i=1;i<=range;++i)
{
printf("%d * %d = %dn", n, i, n*i);
}
return 0;
}
Output
Enter an integer to find multiplication table: 6
Enter range of multiplication table: 4
6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
Reverse an Integer
#include <stdio.h>
int main()
{
int n, reverse=0, rem;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
printf("Reversed Number = %d",reverse);
return 0;
}
Output
Enter an integer: 2345
Reversed Number = 5432
Check Palindrome Number
/* C program to check whether a number is palindrome or not */
#include <stdio.h>
int main()
{
int n, reverse=0, rem,temp;
printf("Enter an integer: ");
scanf("%d", &n);
temp=n;
while(temp!=0)
{
rem=temp%10;
reverse=reverse*10+rem;
temp/=10;
}
/* Checking if number entered by user and it's reverse number is equal. */
if(reverse==n)
printf("%d is a palindrome.",n);
else
printf("%d is not a palindrome.",n);
return 0;
}
Output
Enter an integer: 12321
12321 is a palindrome.
Check Armstrong Number
/* C program to check whether a number entered by user is Armstrong or not. */
#include <stdio.h>
int main()
{
int n, n1, rem, num=0;
printf("Enter a positive integer: ");
scanf("%d", &n);
n1=n;
while(n1!=0)
{
rem=n1%10;
num+=rem*rem*rem;
n1/=10;
}
if(num==n)
printf("%d is an Armstrong number.",n);
else
printf("%d is not an Armstrong number.",n);
}
Output
Enter a positive integer: 371
371 is an Armstrong number.
Make Simple Calculator in C
/* Source code to create a simple calculator for addition, subtraction, multiplication and
division using switch...case statement in C programming. */
# include <stdio.h>
int main()
{
char o;
float num1,num2;
printf("Enter operator either + or - or * or divide : ");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
return 0;
}
Output
Enter operator either + or - or * or divide : -
Enter two operands: 3.4
8.4
3.4 - 8.4 = -5.0
This program takes an operator and two operands from user. The operator is stored in
variable operator and two operands are stored in num1 and num2 respectively. Then,
switch...case statement is used for checking the operator entered by user. If user enters +
then, statements for case: '+' is executed and program is terminated. If user enters - then,
statements for case: '-' is executed and program is terminated. This program works
similarly for * and / operator. But, if the operator doesn't matches any of the four
character [ +, -, * and / ], default statement is executed which displays error message.

More Related Content

What's hot

C Programming
C ProgrammingC Programming
C Programming
Sumant Diwakar
 
C programs
C programsC programs
C programsMinu S
 
The solution manual of c by robin
The solution manual of c by robinThe solution manual of c by robin
The solution manual of c by robin
Abdullah Al Naser
 
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
BUBT
 
Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C
BUBT
 
Chapter 2 : Balagurusamy_ Programming ANsI in C
Chapter 2 :  Balagurusamy_ Programming ANsI in CChapter 2 :  Balagurusamy_ Programming ANsI in C
Chapter 2 : Balagurusamy_ Programming ANsI in C
BUBT
 
Chapter 6 Balagurusamy Programming ANSI in c
Chapter 6  Balagurusamy Programming ANSI  in cChapter 6  Balagurusamy Programming ANSI  in c
Chapter 6 Balagurusamy Programming ANSI in c
BUBT
 
C programming Lab 2
C programming Lab 2C programming Lab 2
C programming Lab 2
Zaibi Gondal
 
C important questions
C important questionsC important questions
C important questions
JYOTI RANJAN PAL
 
Programming fundamentals
Programming fundamentalsProgramming fundamentals
Programming fundamentals
Zaibi Gondal
 
C Programming
C ProgrammingC Programming
C Programming
Sumant Diwakar
 
B.Com 1year Lab programs
B.Com 1year Lab programsB.Com 1year Lab programs
B.Com 1year Lab programs
Prasadu Peddi
 
programs of c www.eakanchha.com
 programs of c www.eakanchha.com programs of c www.eakanchha.com
programs of c www.eakanchha.com
Akanchha Agrawal
 
Write a program to check a given number is prime or not
Write a program to check a given number is prime or notWrite a program to check a given number is prime or not
Write a program to check a given number is prime or not
aluavi
 
FLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONFLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHON
vikram mahendra
 

What's hot (20)

C Programming
C ProgrammingC Programming
C Programming
 
C programs
C programsC programs
C programs
 
The solution manual of c by robin
The solution manual of c by robinThe solution manual of c by robin
The solution manual of c by robin
 
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
 
Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C Chapter 3 : Balagurusamy Programming ANSI in C
Chapter 3 : Balagurusamy Programming ANSI in C
 
Chapter 2 : Balagurusamy_ Programming ANsI in C
Chapter 2 :  Balagurusamy_ Programming ANsI in CChapter 2 :  Balagurusamy_ Programming ANsI in C
Chapter 2 : Balagurusamy_ Programming ANsI in C
 
Chapter 6 Balagurusamy Programming ANSI in c
Chapter 6  Balagurusamy Programming ANSI  in cChapter 6  Balagurusamy Programming ANSI  in c
Chapter 6 Balagurusamy Programming ANSI in c
 
C programming Lab 2
C programming Lab 2C programming Lab 2
C programming Lab 2
 
C important questions
C important questionsC important questions
C important questions
 
Programming fundamentals
Programming fundamentalsProgramming fundamentals
Programming fundamentals
 
C lab-programs
C lab-programsC lab-programs
C lab-programs
 
C code examples
C code examplesC code examples
C code examples
 
C Programming
C ProgrammingC Programming
C Programming
 
B.Com 1year Lab programs
B.Com 1year Lab programsB.Com 1year Lab programs
B.Com 1year Lab programs
 
Input And Output
 Input And Output Input And Output
Input And Output
 
programs of c www.eakanchha.com
 programs of c www.eakanchha.com programs of c www.eakanchha.com
programs of c www.eakanchha.com
 
comp1
comp1comp1
comp1
 
comp2
comp2comp2
comp2
 
Write a program to check a given number is prime or not
Write a program to check a given number is prime or notWrite a program to check a given number is prime or not
Write a program to check a given number is prime or not
 
FLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONFLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHON
 

Similar to Programming egs

Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
Mainak Sasmal
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
Suhail Akraam
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
Haard Shah
 
C faq pdf
C faq pdfC faq pdf
C faq pdf
DebiPanda
 
Common problems solving using c
Common problems solving using cCommon problems solving using c
Common problems solving using c
ArghodeepPaul
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
Wingston
 
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
Ashutoshprasad27
 
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
Ashutoshprasad27
 
Qust & ans inc
Qust & ans incQust & ans inc
Qust & ans incnayakq
 
C programs
C programsC programs
C programs
Vikram Nandini
 
C Language Programming Introduction Lecture
C Language Programming Introduction LectureC Language Programming Introduction Lecture
C Language Programming Introduction Lecture
myinstalab
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
Komal Kotak
 
C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptx
DEEPAK948083
 
Best C Programming Solution
Best C Programming SolutionBest C Programming Solution
Best C Programming Solution
yogini sharma
 
C file
C fileC file
Programming in C Lab
Programming in C LabProgramming in C Lab
Programming in C Lab
Neil Mathew
 
Sample Program file class 11.pdf
Sample Program file class 11.pdfSample Program file class 11.pdf
Sample Program file class 11.pdf
YashMirge2
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
AnkitaVerma776806
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysisVishal Singh
 

Similar to Programming egs (20)

Practical write a c program to reverse a given number
Practical write a c program to reverse a given numberPractical write a c program to reverse a given number
Practical write a c program to reverse a given number
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
 
C decision making and looping.
C decision making and looping.C decision making and looping.
C decision making and looping.
 
C faq pdf
C faq pdfC faq pdf
C faq pdf
 
Common problems solving using c
Common problems solving using cCommon problems solving using c
Common problems solving using c
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
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
 
Qust & ans inc
Qust & ans incQust & ans inc
Qust & ans inc
 
C programs
C programsC programs
C programs
 
C Language Programming Introduction Lecture
C Language Programming Introduction LectureC Language Programming Introduction Lecture
C Language Programming Introduction Lecture
 
Progr3
Progr3Progr3
Progr3
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
C programming Control Structure.pptx
C programming Control Structure.pptxC programming Control Structure.pptx
C programming Control Structure.pptx
 
Best C Programming Solution
Best C Programming SolutionBest C Programming Solution
Best C Programming Solution
 
C file
C fileC file
C file
 
Programming in C Lab
Programming in C LabProgramming in C Lab
Programming in C Lab
 
Sample Program file class 11.pdf
Sample Program file class 11.pdfSample Program file class 11.pdf
Sample Program file class 11.pdf
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysis
 

More from Dr.Subha Krishna

Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
Dr.Subha Krishna
 
Programming questions
Programming questionsProgramming questions
Programming questions
Dr.Subha Krishna
 
Programming qns
Programming qnsProgramming qns
Programming qns
Dr.Subha Krishna
 
Functions
Functions Functions
Functions
Dr.Subha Krishna
 
C Tutorial
C TutorialC Tutorial
C Tutorial
Dr.Subha Krishna
 
Decision control
Decision controlDecision control
Decision control
Dr.Subha Krishna
 

More from Dr.Subha Krishna (6)

Arrays and Strings
Arrays and Strings Arrays and Strings
Arrays and Strings
 
Programming questions
Programming questionsProgramming questions
Programming questions
 
Programming qns
Programming qnsProgramming qns
Programming qns
 
Functions
Functions Functions
Functions
 
C Tutorial
C TutorialC Tutorial
C Tutorial
 
Decision control
Decision controlDecision control
Decision control
 

Recently uploaded

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 

Recently uploaded (20)

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 

Programming egs

  • 1. PROGRAMMING EXAMPLES Check Whether a Number is Even or Odd /*C program to check whether a number entered by user is even or odd. */ #include <stdio.h> int main(){ int num; printf("Enter an integer you want to check: "); scanf("%d",&num); if((num%2)==0) /* Checking whether remainder is 0 or not. */ printf("%d is even.",num); else printf("%d is odd.",num); return 0; } Output 1 Enter an integer you want to check: 25 25 is odd. Output 2 Enter an integer you want to check: 12 12 is even. In this program, user is asked to enter an integer which is stored in variable num. Then, the remainder is found when that number is divided by 2 and checked whether remainder is 0 or not. If remainder is 0 then, that number is even otherwise that number is odd. This task is performed using if...else statement in C programming and the result is displayed accordingly. This program also can be solved using conditional operator[ ?: ] which is the shorthand notation for if...else statement. /* C program to check whether an integer is odd or even using conditional operator */
  • 2. #include <stdio.h> int main(){ int num; printf("Enter an integer you want to check: "); scanf("%d",&num); ((num%2)==0) ? printf("%d is even.",num) : printf("%d is odd.",num); return 0; } C Program to Print a Integer Entered by a User #include <stdio.h> int main() { int num; printf("Enter a integer: "); scanf("%d",&num); /* Storing a integer entered by user in variable num */ printf("You entered: %d",num); return 0; } Output Enter a integer: 25 You entered: 25 In this program, a variable num is declared of type integer using keyword int. The printf() function prints the content inside quotation mark which is "Enter a integer: ". Then, the scanf() takes integer value from user and stores it in variable num. Finally, the value entered by user is displayed in the screen using printf(). C Program to Count Number of Digits of an Integer #include <stdio.h> int main() { int n,count=0; printf("Enter an integer: "); scanf("%d", &n); while(n!=0) { n/=10; /* n=n/10 */ ++count; } printf("Number of digits: %d",count); }
  • 3. Output Enter an integer: 34523 Number of digits: 5 This program takes an integer from user and stores that number in variable n. Suppose, user entered 34523. Then, while loop is executed because n!=0 will be true in first iteration. The codes inside while loop will be executed. After first iteration, value of n will be 3452 and count will be 1. Similarly, in second iteration n will be equal to 345 and count will be equal to 2. This process goes on and after fourth iteration, n will be equal to 3 and count will be equal to 4. Then, in next iteration n will be equal to 0 and count will be equal to 5 and program will be terminated as n!=0 becomes false. Check Character is an alphabet or not /* C programming code to check whether a character is alphabet or not.*/ #include <stdio.h> int main() { char c; printf("Enter a character: "); scanf("%c",&c); if( (c>='a'&& c<='z') || (c>='A' && c<='Z')) printf("%c is an alphabet.",c); else printf("%c is not an alphabet.",c); return 0; } Output 1 Enter a character: * * is not an alphabet Output 2 Enter a character: K K is an alphabet
  • 4. When a character is stored in a variable, ASCII value of that character is stored instead of that character itself. For example: If 'a' is stored in a variable, ASCII value of 'a' which is 97 is stored. If you see the ASCII table, the lowercase alphabets are from 97 to 122 and uppercase letter are from 65 to 90. If the ASCII value of number stored is between any of these two intervals then, that character will be an alphabet. In this program, instead of number 97, 122, 65 and 90; we have used 'a', 'z', 'A' and 'Z' respectively which is basically the same thing. This program also can be performed using standard library function isalpha(). Find HCF or GCD /* C Program to Find Highest Common Factor. */ #include <stdio.h> int main() { int num1, num2, i, hcf; printf("Enter two integers: "); scanf("%d %d", &num1, &num2); for(i=1; i<=num1 || i<=num2; ++i) { if(num1%i==0 && num2%i==0) /* Checking whether i is a factor of both number */ hcf=i; } printf("H.C.F of %d and %d is %d", num1, num2, hcf); return 0; } In this program, two integers are taken from user and stored in variable num1 and num2. Then i is initialized to 1 and for loop is executed until i becomes equal to smallest of two numbers. In each looping iteration, it is checked whether i is factor of both numbers or not. If i is factor of both numbers, it is stored to hcf. When for loop is completed, the H.C.F of those two numbers will be stored in variable hcf. Find Factorial of a Number /* C program to display factorial of an integer if user enters non-negative integer. */ #include <stdio.h> int main() { int n, count; unsigned long long int factorial=1; printf("Enter an integer: "); scanf("%d",&n); if ( n< 0)
  • 5. printf("Error!!! Factorial of negative number doesn't exist."); else { for(count=1;count<=n;++count) /* for loop terminates if count>n */ { factorial*=count; /* factorial=factorial*count */ } printf("Factorial = %lu",factorial); } return 0; } Output 1 Enter an integer: -5 Error!!! Factorial of negative number doesn't exist. Output 2 Enter an integer: 10 Factorial = 3628800 Here the type of factorial variable is declared as: unsigned long long. It is because, the factorial is always positive, so unsigned keyword is used and the factorial of a number can be pretty large. For example: the factorial of 10 is 3628800 thus, long long keyword is used. Find Number of Vowels, Consonants, Digits and White Space Character #include<stdio.h> int main(){ char line[150]; int i,v,c,ch,d,s,o; o=v=c=ch=d=s=0; printf("Enter a line of string:n"); gets(line); for(i=0;line[i]!='0';++i) { if(line[i]=='a' || line[i]=='e' || line[i]=='i' || line[i]=='o' || line[i]=='u' || line[i]=='A' || line[i]=='E' || line[i]=='I' || line[i]=='O' || line[i]=='U') ++v; else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z')) ++c; else if(line[i]>='0'&&c<='9') ++d; else if (line[i]==' ')
  • 6. ++s; } printf("Vowels: %d",v); printf("nConsonants: %d",c); printf("nDigits: %d",d); printf("nWhite spaces: %d",s); return 0; } Output Enter a line of string: This program is easy 2 understand Vowels: 9 Consonants: 18 Digits: 1 White spaces: 5 Calculate Length without Using strlen() Function #include <stdio.h> int main() { char s[1000],i; printf("Enter a string: "); scanf("%s",s); for(i=0; s[i]!='0'; ++i); printf("Length of string: %d",i); return 0; } Output Enter a string: Programiz Length of string: 9 Copy String Manually #include <stdio.h> int main() { char s1[100], s2[100], i; printf("Enter string s1: "); scanf("%s",s1); for(i=0; s1[i]!='0'; ++i) {
  • 7. s2[i]=s1[i]; } s2[i]='0'; printf("String s2: %s",s2); return 0; } Output Enter String s1: programiz String s2: programiz This above program copies the content of string s1 to string s2 manually. Calculate Sum of Natural Numbers /* This program is solved using while loop. */ #include <stdio.h> int main() { int n, count, sum=0; printf("Enter an integer: "); scanf("%d",&n); count=1; while(count<=n) /* while loop terminates if count>n */ { sum+=count; /* sum=sum+count */ ++count; } printf("Sum = %d",sum); return 0; } Calculate Sum Using for Loop /* This program is solved using for loop. */ #include <stdio.h> int main() { int n, count, sum=0; printf("Enter an integer: "); scanf("%d",&n); for(count=1;count<=n;++count) /* for loop terminates if count>n */ { sum+=count; /* sum=sum+count */ } printf("Sum = %d",sum); return 0; }
  • 8. Output Enter an integer: 100 Sum = 5050 Both program above does exactly the same thing. Initially, the value of count is set to 1. Both program have test condition to perform looping iteration until condition count<=n becomes false and in each iteration ++count is executed. This program works perfectly for positive number but, if user enters negative number or 0, Sum = 0is displayed but, it is better is display the error message in this case. The above program can be made user-friendly by adding if else statement as: /* This program displays error message when user enters negative number or 0 and displays the sum of natural numbers if user enters positive number. */ #include <stdio.h> int main() { int n, count, sum=0; printf("Enter an integer: "); scanf("%d",&n); if ( n<= 0) printf("Error!!!!"); else { for(count=1;count<=n;++count) /* for loop terminates if count>n */ { sum+=count; /* sum=sum+count */ } printf("Sum = %d",sum); } return 0; } Display Fibonacci series up to n terms /* Displaying Fibonacci sequence up to nth term where n is entered by user. */ #include <stdio.h> int main() { int count, n, t1=0, t2=1, display=0; printf("Enter number of terms: "); scanf("%d",&n); printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */ count=2; /* count=2 because first two terms are already displayed. */ while (count<n) {
  • 9. display=t1+t2; t1=t2; t2=display; ++count; printf("%d+",display); } return 0; } Output Enter number of terms: 10 Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+ Suppose, instead of number of terms, you want to display the Fibonacci series util the term is less than certain number entered by user. Then, this can be done using source code below: /* Displaying Fibonacci series up to certain number entered by user. */ #include <stdio.h> int main() { int t1=0, t2=1, display=0, num; printf("Enter an integer: "); scanf("%d",&num); printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */ display=t1+t2; while(display<num) { printf("%d+",display); t1=t2; t2=display; display=t1+t2; } return 0; } Output Enter an integer: 200 Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+55+89+144+ Generate Multiplication Table /* C program to find multiplication table up to 10. */
  • 10. #include <stdio.h> int main() { int n, i; printf("Enter an integer to find multiplication table: "); scanf("%d",&n); for(i=1;i<=10;++i) { printf("%d * %d = %dn", n, i, n*i); } return 0; } Output Enter an integer to find multiplication table: 9 9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81 9 * 10 = 90 This program generates multiplication table of an integer up 10. But, this program can be made more user friendly by giving option to user to enter number up to which, he/she want to generate multiplication table. The source code below will perform this task. #include <stdio.h> int main() { int n, range, i; printf("Enter an integer to find multiplication table: ");
  • 11. scanf("%d",&n); printf("Enter range of multiplication table: "); scanf("%d",&range); for(i=1;i<=range;++i) { printf("%d * %d = %dn", n, i, n*i); } return 0; } Output Enter an integer to find multiplication table: 6 Enter range of multiplication table: 4 6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 Reverse an Integer #include <stdio.h> int main() { int n, reverse=0, rem; printf("Enter an integer: "); scanf("%d", &n); while(n!=0) { rem=n%10; reverse=reverse*10+rem; n/=10; } printf("Reversed Number = %d",reverse); return 0; } Output Enter an integer: 2345 Reversed Number = 5432
  • 12. Check Palindrome Number /* C program to check whether a number is palindrome or not */ #include <stdio.h> int main() { int n, reverse=0, rem,temp; printf("Enter an integer: "); scanf("%d", &n); temp=n; while(temp!=0) { rem=temp%10; reverse=reverse*10+rem; temp/=10; } /* Checking if number entered by user and it's reverse number is equal. */ if(reverse==n) printf("%d is a palindrome.",n); else printf("%d is not a palindrome.",n); return 0; } Output Enter an integer: 12321 12321 is a palindrome. Check Armstrong Number /* C program to check whether a number entered by user is Armstrong or not. */ #include <stdio.h> int main() { int n, n1, rem, num=0; printf("Enter a positive integer: "); scanf("%d", &n); n1=n; while(n1!=0) { rem=n1%10; num+=rem*rem*rem; n1/=10; } if(num==n) printf("%d is an Armstrong number.",n); else printf("%d is not an Armstrong number.",n); }
  • 13. Output Enter a positive integer: 371 371 is an Armstrong number. Make Simple Calculator in C /* Source code to create a simple calculator for addition, subtraction, multiplication and division using switch...case statement in C programming. */ # include <stdio.h> int main() { char o; float num1,num2; printf("Enter operator either + or - or * or divide : "); scanf("%c",&o); printf("Enter two operands: "); scanf("%f%f",&num1,&num2); switch(o) { case '+': printf("%.1f + %.1f = %.1f",num1, num2, num1+num2); break; case '-': printf("%.1f - %.1f = %.1f",num1, num2, num1-num2); break; case '*': printf("%.1f * %.1f = %.1f",num1, num2, num1*num2); break; case '/': printf("%.1f / %.1f = %.1f",num1, num2, num1/num2); break; default: /* If operator is other than +, -, * or /, error message is shown */ printf("Error! operator is not correct"); break; } return 0; } Output Enter operator either + or - or * or divide : - Enter two operands: 3.4 8.4 3.4 - 8.4 = -5.0
  • 14. This program takes an operator and two operands from user. The operator is stored in variable operator and two operands are stored in num1 and num2 respectively. Then, switch...case statement is used for checking the operator entered by user. If user enters + then, statements for case: '+' is executed and program is terminated. If user enters - then, statements for case: '-' is executed and program is terminated. This program works similarly for * and / operator. But, if the operator doesn't matches any of the four character [ +, -, * and / ], default statement is executed which displays error message.