Unit Ii - C Programming Basics
Unit Ii - C Programming Basics
Unit Ii - C Programming Basics
2.1 C PROGRAMMING-FUNDAMENTALS:
History of C Programming Language:
C was written by Dennis Ritchie in 1972, thats why he is also called as father of c
programming language.
C language was created for a specific purpose i.e designing the UNIX operating system
Many of C‟s principles and ideas were derived from the earlier language B. (Ken Thompson
was the developer of B Language.)
BCPL and CPL are the earlier ancestors of B Language
As many of the features were derived from “B” Language thats why it was named as “C”.
C PROGRAMMING LANGUAGE TIMELINE :
Programming Development
Developed by
Language Year
Programming Development
Developed by
Language Year
Application Of C Programming:
C Programming is near to machine as well as human so it is called as Middle level
Programming Language.
C language is used for creating computer applications
Used in writing Embedded softwares
Firmware for various electronics, industrial and communications products which use
micro-controllers.
It is also used in developing verification software, test code, simulatorsetc. for various
applications and hardware products.
For Creating Compilers of different Languages which can take input from other language
and convert it into lower level machine dependent language.
C is used to implement different Operating System Operations.
UNIX kernel is completely developed in C Language.
Documentation Section
This section consists of comment lines which include the name of programmer, the
author and other details like time and date of writing the program.
Documentation section helps anyone to get an overview of the program.
Link Section / Preprocessor section
The link section consists of the header files of the functions that are used in the program.
It provides instructions to the compiler to link functions from the system library.
These commands tells the compiler to do preprocessing before doing actual compilation.
Like #include <stdio.h> is a preprocessor command which tells a C compiler to include
stdio.h file before going to actual compilation
Definition Section
All the symbolic constants are written in definition section. Macros are known as symbolic
constants.
Eg: # define PI 3.14
Global Declaration Section
The global variables that can be used anywhere in the program are declared in global
declaration section. This section also declares the user defined functions.
main() Function Section
It is necessary have one main() function section in every C program. This section contains
two parts, declaration and executable part.
The declaration part declares all the variables that are used in executable part. These two
parts must be written in between the opening and closing braces.
Each statement in the declaration and executable part must end with a semicolon (;). The
execution of program starts at opening braces and ends at closing braces.
Subprogram Section
The subprogram section contains all the user defined functions that are used to perform a
specific task. These user defined functions are called in the main() function.
Example:
/*Documentation Section: program to find the area of circle*/
#include <stdio.h> /*link section*/
#include <conio.h> /*link section*/
For example
#include -- includes contents of a named file. Files usually called header files. e.g
o #include <math.h> -- standard library maths file.
o #include <stdio.h> -- standard library I/O file
#define -- defines a symbolic name or constant. Macro substitution.
o #define MAX_ARRAY_SIZE 100
C COMPILER
Compiling is the transformation from Source Code (human readable) into machine code
(computer executable). A compiler is a program.
A compiler takes the code for a new program (written in a high level language) and
transforms this Code into a new language (Machine Language) that can be understood by the
computer itself.
This "machine language" is difficult to impossible for humans to read and understand (much
less debug and maintain), thus the need for "high level languages" such as C.
1. The compiler also ensures that your program is TYPE correct. For example, you are not
allowed to assign a string to an integer variable!
2. The compiler also ensures that your program is syntactically correct. For example, "x *
y" is valid, but "x @ y" is not.
ASSEMBLER
During the assembly stage, an assembler is used to translate the assembly instructions to
machine code, or object code.
The output consists of actual instructions to be run by the target processor. On a UNIX
system you may see files with a .o suffix (.OBJ on MSDOS) to indicate object code files.
LINK EDITOR
Linking combines the separate object codes into one complete program by integrating
libraries and the code and producing either an executable program or a library.
Linking is performed by a linker, which is often part of a compiler.
2.4 C TOKENS:
In C Programming punctuation, individual words, characters etc are called tokens.
Tokens are basic building blocks of C Programming
Token Example :
1 Keyword do while
2 Constants -76 89
5 Special Symbol * @
6 Operators ++ /
Token Meaning
Keywords are the reserved words used in programming. Each keywords has fixed
Keyword
meaning and that cannot be changed by user.
Constant Constants are the terms that can't be changed during the execution of a program.
Token Meaning
Special
Symbols other than the Alphabets and Digits and white-spaces
Symbol
2.4.1 KEYWORDS:
Keywords are the reserved words used in programming. Each keywords has fixed
meaning and that cannot be changed by user.
Cannot be used as Variable Name
2.4.3 VARIABLE :
A Variable is a name given to the memory location where the actual data is stored. Variable
name may have different data types to identify the type of value stored.
Suppose we declare variable of type integer then it can store only integer values.
Variable is considered as one of the building block of C Programming which is also called as
identifier.
Initially 5 is Stored in memory location and name x is given to it
After We are assigning the new value (3) to the same memory location
This would Overwrite the earlier value 5 since memory location can hold only one value at a
time
Since the location „x‟can hold Different values at different time so it is refered as „Variable„
In short Variable is name given to Specific memory location or Group.
3. Address of Variable
Variable can hold data ,it means there should be a container.
4.Type of Variable
Type of variable tells compiler that – “Allocate memory for data of Specified type“.
5.Size of Variable
We can use sizeof operator to calculate size of any data type.
TYPES OF VARIABLE:
1. Local variable
2. Global variable
Local Variable:
Local Variable is Variable having Local Scope.
Local Variable is accessible only from function or block in which it is declared .
Local variable is given Higher Priority than the Global Variable.
Example :
#include<stdio.h>
void main()
{
int var1=10;
{
int var2 = 20;
printf("%d %d",var1,var2); // Legal : var1 can be accessed
}
printf("%d %d",var1,var2); // Error : var2 is not declared
}
var1 is Local to Outer Block.
var1 cannot be accessed from its outer block.
var1 cannot be accessed from Other Function or other block
Similarly Variables declared inside inner block are visible or meaningful only inside
Inner block.
Variables declared inside inner block are not accessed by outer block
Global Variable :
Global Variable is Variable that is Globally available.
Scope of Global variable is throughout the program [ i.e in all functions including main() ]
Global variable is also visible inside function , provided that it should not be re-declared with
same name inside function
#include<stdio.h>
int var=10;
void message();
void main()
{
int var=20;
{
int var = 30;
printf("%d ",var);
}
printf("%d ",var);
message();
}
void message()
{
printf("%d ",var);
}
Output :
30 20 10
Inside message() „var‟ is not declared so global version of „var‟ is used , so 10 will be
printed.
{ int var = 30; printf("%d ",var); }
Here variable is re-declared inside block , so Local version is used and 30 will be printed.
2.4.4 CONSTANT:
Constant in C means the content whose value does not change at the time of execution of a
program.
Different Types of C Constants :
const int a = 1;
int const a = 1;
above declaration is bit confusing but no need to worry, We can start reading these variables
from right to left. i.e
Declaration Explanation
INTEGER TYPES
Integers are used to store whole numbers.
“int” keyword is used to refer integer data type.
If we use int data type to store decimal values, decimal values will be truncated and we will
get only whole number.
The following table provides the details of standard integer types with their storage sizes and
value ranges −
CHARACTER TYPES:
Character types are used to store characters value.
Character data type allows a variable to store only one character.
For example, „A‟ can be stored using char datatype. You can‟t store more than one
character using char data type.
The following table provides the details of standard character types with their storage sizes and
value ranges −
FLOATING-POINT TYPES:
Floating types are used to store real numbers.
The following table provide the details of standard floating-point types with storage sizes and
value ranges and their precision −
2.6 C OPERATOR:
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions.
C language is rich in built-in operators and provides the following types of operators −
1. Arithmetic Operators
2. Increment operator
3. Decrement operator
4. Relational Operators
5. Logical Operators
6. Conditional operator
7. Bitwise Operators
8. Assignment Operators
+ Addition Operator 10 + 20 = 30
- Subtraction Operator 20 – 10 = 10
/ Division Operator 20 / 10 = 2
% Modulo Operator 20 % 6 = 2
Example :
#include <stdio.h>
void main()
{
int num1,num2;
int sum,sub,mult,div,mod;
printf("\nEnter First Number :");
scanf("%d",&num1);
printf("\nEnter Second Number :");
scanf("%d",&num2);
sum = num1 + num2;
printf("\nAddition is : %d",sum);
sub = num1 - num2;
printf("\nSubtraction is : %d",sub);
mult = num1 * num2;
printf("\nMultiplication is : %d",mult);
div = num1 / num2;
printf("\nDivision is : %d",div);
mod = num1 % num2;
printf("\nModulus is : %d",mod);
}
OUTPUT :
Enter First Number : 10
Enter Second Number : 5
Addition is : 15
Subtraction is : 5
Multiplication is : 50
Division is : 2
Modulus is : 0
b = ++y;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
}
OUTPUT :
Value of a : 10
Value of b : 11
void main()
{
int a,b,x=10,y=10;
a = x--;
b = --y;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
}
Output :
Value of a : 10
Value of b : 9
2.6.4 RELATIONAL OPERATOR:
we can compare the value stored between two variables and depending on the result we can
follow different blocks using Relational Operator in C.
In C we have different relational operators such as –
Operator Meaning
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
printf("Line 1 - a is equal to b\n" );
}
else {
&& Called Logical AND operator. If both the operands are (A && B) is false.
non-zero, then the condition becomes true.
! Called Logical NOT Operator. It is used to reverse the !(A && B) is true.
logical state of its operand. If a condition is true, then
Logical NOT operator will make it false.
#include<stdio.h>
int main()
{
int num1 = 30;
int num2 = 40;
if(num1>=40 || num2>=40)
printf("Or If Block Gets Executed");
if(num1>=20 && num2>=20)
printf("And If Block Gets Executed");
if( !(num1>=40))
printf("Not If Block Gets Executed");
}
OUTPUT :
Or If Block Gets Executed
And If Block Gets Executed
Not If Block Gets Executed
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
& Binary AND Operator copies a bit to the result if it (A & B) = 12, i.e., 0000 1100
exists in both operands.
^ Binary XOR Operator copies the bit if it is set in (A ^ B) = 49, i.e., 0011 0001
one operand but not both.
~ Binary Ones Complement Operator is unary and (~A ) = -61, i.e,. 1100 0011 in
has the effect of 'flipping' bits. 2's complement form.
<< Binary Left Shift Operator. The left operands A << 2 = 240 i.e., 1111 0000
value is moved left by the number of bits specified
by the right operand.
>> Binary Right Shift Operator. The left operands A >> 2 = 15 i.e., 0000 1111
value is moved right by the number of bits
specified by the right operand.
Expressions Validity
The control string specifies the field format which includes format specifications and optional
number specifying field width and the conversion character % and also blanks, tabs and new
lines.
The Blanks tabs and new lines are ignored by compiler. The conversion character % is followed
by the type of data that is to be assigned to variable of the assignment. The field width specifier
is optional.
The general format for reading a integer number is
%xd
Here percent sign (%) denotes that a specifier for conversion follows and x is an integer number
which specifies the width of the field of the number that is being read. The data type character d
indicates that the number should be read in integer mode.
Example:
2. PRINTF
The most simple output statement can be produced in C Language by using printf statement. It
allows you to display information required to the user and also prints the variables.
We can also format the output and provide text labels. The simple statement such as
printf (“Enter 2 numbers”);
Prompts the message enclosed in the quotation to be displayed.
A simple program to illustrate the use of printf statement:-
#include < stdio.h >
main ( )
{
printf (“Hello!”);
printf (“Welcome to the world of Engineering!”);
}
OUTPUT:
Hello! Welcome to the world of Engineering.
Both the messages appear in the output as if a single statement.
If you wish to print the second message to the beginning of next line, a new line character must
be placed inside the quotation marks.
For Example:
printf (“Hello!\n);
OR
printf (“\n Welcome to the world of Engineering”);
Conversion Strings and Specifiers:
The printf ( ) function is quite flexible. It allows a variable number of arguments, labels and
sophisticated formatting of output. The general form of the printf ( ) function is
Syntax Printf (“conversion string”, variable list);
The conversion string includes all the text labels, escape character and conversion specifiers
required for the desired output.
The variable includes all the variable to be printed in order they are to be printed. There must be
a conversion specifies after each variable.
2. putchar()
This function prints one character on the screen at a time, which is read by the standard input.
Example
putchar (ch [c] ) ;
This function is used for accepting any string through stdin (keyboard) until enter key is
pressed.The header file stdio.h is needed for implementing this function.
Example
gets(ch);
2.puts()
This function prints the string or character array.
Example puts(ch);
3.cgets()
This function reads the string from the console.
Syntaxcgets(char *st);
It requires character pointer as an argument.
4.cputs ()
This function displays the string on the screen.
Syntax cputs(char *st);
Branching
Conditinal Unconditional
Branching branching
C programming language assumes any non-zero and non-null values as true, and if it is
either zero or null, then it is assumed as false value.
1. if-else
2. else-if
3. switch
Statements and Blocks
An expression such as x = 0 or i++ or printf (...) becomes a statement when it is followed by
a semicolon
Braces { and } are used to group declarations and statements together into a compound
statement, or block
Example: braces around multiple statements after an if, else, while, for, switch, functions
IF-ELSE:
The if, if...else and nested if...else statement are used to make one-time decisions in C
programming, that is, to execute some code/s and ignore some code/s depending upon
the test expression.
Syntax:
if (expression)
statement 1
else
statement 2
The else part is optional.
The expression is evaluated; if it is true, statement 1 is executed.
If it is false and if there is an else part, statement 2 is executed
Example:
If:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
a=10;
b=5;
if(a>b)
{
printf("a is greater");
}
}
Output:
a is greater
If-Else:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("Enter a value for a:");
scanf("%d",&a);
printf("\nEnter a value for b:");
scanf("%d",&b);
if(a>b)
{
printf("\n a got greater value");
}
else
{
printf("\n b got greater value");
}
}
OUTPUT:
10 20
b got greater value
ELSE-IF LADDER
An if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.
Syntax
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
It is the general way of writing a multi-way decision.
The expressions are evaluated in order; if any expression is true, the statement associated
with it isexecuted, and this terminates the whole chain.
The code for each statement is either a single statement, or a group in braces.
The last else part handles the "none of the above" or default case where none of the other
conditions is satisfied. Sometimes the trailing else can be omitted.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("Enter a value for a,b,c:");
scanf("%d%d%d",&a,&b,&c);
if(a>b&&a>c)
{
printf("\n %d is greater number",a);
}
else if(b>c)
{
printf("\n %d is greater number",b);
}
else
{
printf("\n Both a and b are equal");
}
}
Output:
Enter a value for a,b,c:
10 20 30
20 is greater number
SWITCH:
The switch statement is a multi-way decision that tests whether an expression matches one of
a number of constant integer values, and branches accordingly.
Syntax:
switch (expression) {
case const-expr: statements
break;
case const-expr: statements
break;
default : statements
}
Each case is labeled by one or more integer-valued constants or constant expressions.
If a case matches the expression value, execution starts at that case.
The case default is executed if none of the other cases are satisfied. A default is optional; if it
isn't thereand if none of the cases match, no action at all takes place.
normally each case must end with a break to prevent falling through to the next
Example:
Develop a „C‟ program to implement a simple calculator using switch case statement. (40)
#include<stdio.h>
void main()
{
int a,b,c,d;
printf("Enter the values of a and b:");
scanf("%d%d" ,&a,&b);
while(1)
{
printf(" Enter your choice between
1.Add\n2.Subtract\n3.Multiplication\n4.Divide\n5.Reminder\n6.exit\n");
scanf("%d",&d);
switch(d)
{
case 1:
c=a+b;
printf(" Addition=%d", c);
break;
case 2:
c=a-b;
printf(" Substraction=%d" , c);
break;
case 3:
c=a*b;
printf(" Multiplication=%d", c);
break;
case 4:
c=a/b;
printf(" Divide=%d", c);
break;
case 5:
c=a%b;
printf(" Remainder=%d",c );
break;
case 6:
exit(0);
default:
printf(" Invalid Result");
break;
}
}
}
Output:
Enter the values of a and b:4 6
Enter your choice between 1.Add
2.Subtract
3.Multiplication
4.Divide
5.Reminder
6.exit
1
Addition=10
Enter your choice between 1.Add
2.Subtract
3.Multiplication
4.Divide
5.Reminder
6.exit
2
Substraction=-2
Enter your choice between 1.Add
2.Subtract
3.Multiplication
4.Divide
5.Reminder
6.exit
3
Multiplication=24
Enter your choice between 1.Add
2.Subtract
3.Multiplication
4.Divide
5.Reminder
6.exit
4
Divide=0
Enter your choice between 1.Add
2.Subtract
3.Multiplication
4.Divide
5.Reminder
6.exit
6
Flowchart:
The figure below explains the working of break statement in all three type of loops.
Example:
#include<stdio.h>
int main() {
int num, i = 1, sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
while (i < num) {
if (num % i == 0) {
sum = sum + i;
break;
}
i++;
}
if (sum == num)
printf("%d is a Perfect Number", i);
else
printf("%d is Non Perfect Number", i);
return 0;
}
Output:
Enter a number
6
6 is Non Perfect Number
Only once if condition will be executed hence sum value will be 1. And it comes out of loop and
checks 6==1. Hence it prints its a non perfect number
CONTINUE:
The continue statement can be used inside for loop, while loop and do-while loop.
Execution of these statement does not cause an exit from the loop but it suspend the
execution of the loop for that iteration and transfer control back to the loop for the next
iteration.
Syntax:
continue;
Flowchart:
Analyze the figure below which bypasses some code/s inside loops using continue
statement.
#include<stdio.h>
int main() {
int num, i = 1, sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
while (i < num) {
if (num % i == 0) {
sum = sum + i;
continue;
}
i++;
}
if (sum == num)
printf("%d is a Perfect Number", i);
else
printf("%d is Non Perfect Number", i);
return 0;
}
Output:
Nothing printed-infinite loop
When i=1, it checks if condition and calculates sum=1, then continue will take to starting of the loop
and still i value is 1 hence same will be repeated again and again. Since i++ is not executed
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("Enter 2 nos A and B one by one : ");
scanf("%d%d",&a,&b);
if(a>b)
{
goto first;
}
else
{
goto second;
}
first:
printf("\n A is greater..");
goto g;
second:
printf("\n B is greater..");
g:
getch();
}
3. do...while loop
WHILE LOOP:
Syntax:
while (condition)
{
Statement
}
Flowchart:
Here, statement(s) may be a single statement or a block of statements. The condition may
be any expression, and true is any nonzero value.
The loop iterates while the condition is true. When the condition becomes false, the
program control passes to the line immediately following the loop.
Whether to use while or for depends on personal preference. For example, if no
initialization the while is preferred.
The for is preferable when there is a simple initialization and increment since it keeps the
loop control statements close together and visible at the top of the loop
Example:
void main()
{
int i=1;
while (i<=5)
{
printf("%d\t ", i);
i++;
}
}
Output:
1 2 3 4 5
step1: first counter variable i got initialized with value 1 and then it has been tested for
the condition.
step2: If condition holds true then the body of the while loop gets executed otherwise
control come out of the loop.
step3: i value got incremented using ++ operator then it has been tested again for the
loop condition. It keeps happening until the condition returns false.
DO-WHILE LOOP
In this case the loop condition is tested at the end of the body of the loop. Hence the loop
is executed at least one.
Syntax:
do
{
Statement
} whi1e (expression) ;
Flowchart:
The block of statement following the do is executed without any condition check. After
this expression is evaluated and if it is true the block of statement in the body of the loop
is executed again. Thus the block of statement is repeatedly executed till the expression is
evaluated to false.
do-while construct is not used as often as the while loops or for loops in normal case of
iteration but there are situation where a loop is to be executed at least one, in such cases
this construction is very useful.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
do
{
printf("%d\t",i);
i++;
}while(i<=5);
}
Output:
1 2 3 4 5
The while loop is an entry controlled loop do-while is an exit controlled loop.
If the condition fails in while the statements in do..while if condition fails atleast once the
inside while will not be executed statements inside do while will be executed
FOR LOOP:
Syntax:
for(variable_initialization;condition;increment/decrement)
{
Valid C Statements;
}
In for loop first the variable is initialized and checks for the condition. If the condition is
true. The statement inside for loop will be executed.
On the next cycle the initialised variable will be either incremented or decremented and
again checks for the condition. If the condition is true, again the statement inside will be
executed.
This process will continue until the condition is true. Once the condition fails the control
jumps out of for loop.
Flowchart:
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for(i=1;i<=5;i++)
{
printf("%d\t",i);
}
}
Output:
1 2 3 4 5
i=3 j=2
i=3 j=3
Such type of nesting is often used for handling multidimensional arrays.
}
i++;
}
if (sum == num)
printf("%d is a Perfect Number", i);
else
printf("%d is Non Perfect Number", i);
}
OUTPUT:
Enter a number: 4
4 is Non Perfect Number
Enter a number: 6
6 is a Perfect Number
Enter a number: 28
28 s a Perfect Number
2. Write a c program to print first N terms of the fibonacci series assuming the first
two term as 0 and 1.
#include<stdio.h>
int main()
{
int n, first = 0, second = 1, next, c;
OUTPUT:
Enter the number of terms
8
First 8 terms of Fibonacci series are :-
0
1
1
2
3
5
8
13
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
}
OUTPUT:
Enter a positive integer: 29
29 is a prime number.
4. Write a c program to find the sum of digits of a given number using while statement
#include<stdio.h>
void main()
{
int s=0, a, r,num;
printf("Enter the number:\n");
scanf("%d",&num);
a = num;
while(a)
{
r = a%10;
s = s+r;
a = a/10;
}
printf("Sum of the digit %d is %d",num,s);
}
OUTPUT:
Enter the number:
123
6. Write a C program that takes three coefficients (a, b, and c) of a Quadratic equation
(ax2+bx+c=0) as input and compute all possible roots.
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main()
{
float a,b,c;
float disc,realpart,imgpart,x1,x2;
printf("\n\tEnter the coefficients of quadratic equation:");
scanf("%f%f%f",&a,&b,&c);
if(a == 0)
{
printf("\n\tRoots cannot be found as the equation is linear");
}
else
{
disc=b*b-4*a*c;
if(disc == 0)
{
printf("\n\tRoots are real and equal...");
x1=x2=-b/(2*a);
printf("\n\tX1=%4.2f",x1);
printf("\n\tX2=%4.2f\n",x2);
}
else if(disc > 0)
{
printf("\n\tRoots are real and distinct....");
x1=(-b+sqrt(disc))/(2*a);
x2=(-b-sqrt(disc))/(2*a);
printf("\n\tX1=%4.2f",x1);
printf("\n\tX2=%4.2f\n",x2);
}
else
{
printf("\n\tRoots are imaginary....");
realpart=-b/(2*a);
imgpart =(sqrt(fabs(disc)))/(2*a);
printf("\n\tX1=%4.2f+i%4.2f",realpart,imgpart);
printf("\n\tX2=%4.2f-i%4.2f\n",realpart,imgpart);
}
}
getch();
}
OUTPUT
1. Enter the coefficients of quadratic equation:1 2 3
Roots are imaginary....
X1=-1.00+i1.41
X2=-1.00-i1.41
scanf("%d",&num);
temp=num; /* Store the original number into temp for later use */
/* Reverse the given number */
while(num != 0)
{
rem=num%10;
rev=rev*10+rem;
num=num/10;
}
printf("\n\tReverse of number=%d",rev);
/* Check whether the reversed number is same as original number */
if(rev == temp)
{
}
else
printf("\n\tNumber is palindrome....");
{
printf("\n\tNumber is not palindrome....");
}
getch();
}
OUTPUT
1. Enter a number:1234
Reverse of number=4321
Number is not palindrome....
2. Enter a number:1221
Reverse of number=1221
Number is palindrome....
8. Design and develop a C program to read a year as an input and find whether it is leap
year or not. Also consider end of the centuries.
#include<stdio.h>
#include<conio.h>
void main()
{
int year;
printf("\nEnter a year\n");
scanf("%d",&year);
if(year%4==0 && year%100!=0)
printf("Entered year is a leap year");
else if(year%400==0)
printf("Entered year is end of century leap year");
else
printf("Entered year is not a leap year");
getch();
}
Output
1. Enter a year
2012
Entered year is a leap year
2. Enter a year
2013
Entered year is not a leap year
3. Enter a year
2000
Entered year is end of century leap year
if (n%2 == 0)
printf("Even\n");
else
printf("Odd\n");
}
OUTPUT:
1. Enter an integer
45
Odd
2. Enter an integer
34
Even
void main()
{
int n, sum = 0, c, value;
printf("Enter the number of integers you want to add\n");
scanf("%d", &n);
printf("Enter %d integers\n",n);
for (c = 1; c <= n; c++)
{
scanf("%d", &value);
sum = sum + value;
}
printf("Sum of entered integers = %d\n",sum);
}
OUTPUT:
Enter the number of integers you want to add
5
Enter 5 integers
3
6
2
9
1
Sum of entered integers = 21
}
OUTPUT:
Enter dividend: 25
Enter divisor: 4
Quotient = 6
Remainder = 1
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber%10;
result += remainder*remainder*remainder;
originalNumber /= 10;
}
if(result == number)
printf("%d is an Armstrong number.",number);
else
printf("%d is not an Armstrong number.",number);
}
OUTPUT:
Enter a three digit integer: 371
371 is an Armstrong number.