After being bored about the variables, datatypes and so on, today let us try something towards the programming side. That is, we can take a step towards the control structures.
IF STATEMENT:
If statement is used to control the program by deciding which block is to be executed based on the condition. The most commonly used structures are -
1. if
syntax:
if(condition)
{
\\code
}
2. if..else
syntax:
if(condition)
{
\\code
}
else
{
\\code
}
3. Nested if:
syntax:
if(condition)
{
if(condition)
{
\\code
}
}
Examples:
Prime or Not:
void main()
{
int n,i,prime=1;
printf("Enter a number: ");
scanf("%d",&n);
for(i=2;i<n;i++)
{
if(n%i==0)
{
prime=0;
}
}
if(prime==0)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
}
Odd or Even:
#include <stdio.h>
void main()
{
int n;
printf("Enter an integer\n");
scanf("%d", &n);
if (n %2==0)
printf("Even\n");
else
printf("Odd\n");
}
Palindrome and Reverse of a number:
#include <stdio.h>
void 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=temp/10;
}
if(reverse==n)
printf("%d is a palindrome.",n);
else
printf("%d is not a palindrome.",n);
printf("The reverse of the number is %d",reverse);
}
Reverse of a string:
#include<stdio.h>
#include<string.h>
void main()
{
char str[100], temp;
int i, j = 0;
printf("\nEnter the string :");
scanf("%s",&str);
i = 0;
j = strlen(str) - 1;
while (i < j)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
printf("\nReverse string is :%s", str);
}
Tags: interview c programs, prime or not, palindrome, reverse of a string, reverse of a number, odd or even, if statement
Copy Article URL:
No comments:
Post a Comment