Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit Ii - C Programming Basics

Download as pdf or txt
Download as pdf or txt
You are on page 1of 64

Unit-II GE6151- COMPUTER PROGRAMMING

UNIT II - C PROGRAMMING BASICS


Problem formulation – Problem Solving - Introduction to „ C‟ programming –
fundamentals – structure of a „C‟ program – compilation and linking processes –
Constants, Variables – Data Types – Expressions using operators in „C‟ –
Managing Input and Output operations – Decision Making and Branching –
Looping – solving simple scientific and statistical problems.

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

ALGOL 1960 International Group

BCPL 1967 Martin Richards

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

Brain Kernighan and Dennis


K&R C 1978
Ritchie

ANSI C 1989 ANSI Committee

S.KAVITHA / AP / CSE / MSAJCE Page 1 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

Programming Development
Developed by
Language Year

ANSI/ISO C 1990 ISO Committee

Features of C Programming Language:


1 . Low Level Features :
 C Programming provides low level features that are generally provided by the Lower
level languages. C is Closely Related to Lower level Language such as “Assembly
Language“.
 It is easier to write assembly language codes in C programming.
2 . Portability :
 C Programs are portable i.e they can be run on any Compiler with Little or no
Modification
3 . Powerful
 Provides Wide verity of „Data Types„, Provides Wide verity of „Functions‟, Provides
useful Control & Loop Control Statements
4 . Bit Manipulation
 C Programs can be manipulated using bits. We can perform different operations at bit
level.
5 . High Level Features :
 It is more User friendly as compare to Previous languages
6 . Modular Programming
 Modular programming is a software design technique that increases the extent to which
software is composed of separate parts, called modules
7 . Efficient Use of Pointers
 Pointers has direct access to memory.
8 . More Efficient

S.KAVITHA / AP / CSE / MSAJCE Page 2 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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.

2.2 STRUCTURE OF A C PROGRAM:

S.KAVITHA / AP / CSE / MSAJCE Page 3 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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*/

S.KAVITHA / AP / CSE / MSAJCE Page 4 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

#define PI 3.14 /*definition section*/


float area; /*global declaration section*/
void main()
{
float r; /*declaration part*/
printf("Enter the radius of the circle\n"); /*executable part starts here*/
scanf("%f",&r);
area=PI*r*r;
printf("Area of the circle=%f",area);
getch();
}

2.3 COMPILATION AND LINKING PROCESSES


We will briefly highlight key features of the C Compilation model (Fig. 2.1) here.

Fig: The C Compilation Model


THE PRE-PROCESSOR:
The Preprocessor accepts source code as input and is responsible for
 removing comments
 interpreting special preprocessor directives denoted by #.

S.KAVITHA / AP / CSE / MSAJCE Page 5 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

S.KAVITHA / AP / CSE / MSAJCE Page 6 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

Token Example :

No Token Type Example 1 Example 2

1 Keyword do while

2 Constants -76 89

3 Identifier number sum

4 String “HTF” “PRIT”

5 Special Symbol * @

6 Operators ++ /

Basic Building Blocks and Definition :

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.

Identifier The term identifier is usually used for variable names

String Sequence of characters

S.KAVITHA / AP / CSE / MSAJCE Page 7 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

Token Meaning

Special
Symbols other than the Alphabets and Digits and white-spaces
Symbol

Operators A symbol that represent a specific mathematical or non mathematical action

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

Auto double int struct


break else long switch
Case enum register typedef
Char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

2.4.2 C CHARACTER SET :


Types Character Set
Lowercase Letters a-z
Uppercase Letters A to Z
Digits 0-9
Special Characters !@#$%^&*
White Spaces Tab Or New line Or Space

S.KAVITHA / AP / CSE / MSAJCE Page 8 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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.

Rules For Constructing Variable Name:


 Use allowed Characters Underscore(_)
 Capital Letters ( A – Z )
 Small Letters ( a – z )
 Digits ( 0 – 9 )
 Blanks & Commas are not allowed
 No Special Symbols other than underscore(_) are allowed
 First Character should be alphabet or Underscore
 Variable name Should not be Reserved Word
Variable Declaration:
 Declare is nothing but to represent a variable.

S.KAVITHA / AP / CSE / MSAJCE Page 9 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

 Memory is neither allocated to Variable nor space is Reserved after declaration.


Re-Declaration of variable will cause compile Error.
int ivar;
int ivar = 10;
 It will cause compile error. We cannot re-declare variable.

Fundamental Attributes of C Variable :


1. Name of a Variable
2. Value Inside Variable
3. Address of Variable
4. Size of a Variable
5. Type of a Variable
1.Name of Variable
We can Give proper name to any Variable which is human readable.
2.Value inside Variable
Depending on the type of Variable we can store any value of appropriate data type inside
Variable.

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

S.KAVITHA / AP / CSE / MSAJCE Page 10 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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()

S.KAVITHA / AP / CSE / MSAJCE Page 11 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

{
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 :

Constant Type of Value Stored


Integer Constant Constant which stores integer value
Floating Constant Constant which stores float value
Character Constant Constant which stores character value
String Constant Constant which stores string value
Constant declaration:
We can declare constant using const variable. Suppose we need to declare constant of type
integer then we can have following two ways to declare it –

S.KAVITHA / AP / CSE / MSAJCE Page 12 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

const int a = 1; read as “a is an integer which is constant”

int const a = 1; read as “a is a constant integer”

2.5 DATA TYPES


 Data types are declarations for memory locations or variables that determine the
characteristics of the data that may be stored

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 −

S.KAVITHA / AP / CSE / MSAJCE Page 13 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

Type Storage size Value range

int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to


2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295

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 −

Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

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 −

S.KAVITHA / AP / CSE / MSAJCE Page 14 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

THE VOID TYPE


The void type specifies that no value is available.

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

2.6.1 ARITHMETIC OPERATORS


Arithmetic operators are used to perform arithmetic operations in c programming.

Operator Meaning Example

+ Addition Operator 10 + 20 = 30

- Subtraction Operator 20 – 10 = 10

S.KAVITHA / AP / CSE / MSAJCE Page 15 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

Operator Meaning Example

* Multiplication Operator 20 * 10 = 200

/ 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

S.KAVITHA / AP / CSE / MSAJCE Page 16 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

Subtraction is : 5
Multiplication is : 50
Division is : 2
Modulus is : 0

2.6.2 INCREMENT OPERATOR:


 Increment operator is used to increment the current value of variable by adding integer 1.
 Increment operator can be applied to only variables.
 Increment operator is denoted by ++.
Different Types of Increment Operation
1. Pre-Increment
2. Post-Increment Operator.
Pre Increment Operator
Pre-increment operator is used to increment the value of variable before using in the expression.
In the Pre-Increment value is first incremented and then used inside the expression.
b = ++y;
In this example suppose the value of variable „y‟ is 5 then value of variable „b‟ will be 6 because
the value of „y‟ gets modified before using it in a expression.
Post Increment Operator
 Post-increment operator is used to increment the value of variable as soon as after executing
expression completely in which post increment is used.
 In the Post-Increment value is first used in a expression and then incremented.
b = x++;
 In this example suppose the value of variable „x‟ is 5 then value of variable „b‟ will be 5
because old value of „x‟ is used.
Sample program
#include<stdio.h>
void main()
{
int a,b,x=10,y=10;
a = x++;

S.KAVITHA / AP / CSE / MSAJCE Page 17 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

b = ++y;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
}
OUTPUT :
Value of a : 10
Value of b : 11

2.6.3 DECREMENT OPERATOR:


 Decrement operator is used to decrease the current value of variable by subtracting integer 1.
 Like Increment operator, decrement operator can be applied to only variables.
 Decrement operator is denoted by --.
Different Types of Decrement Operation :
1. pre-decrement
2. post-decrement operator.
A. Pre Decrement Operator
 Pre-decrement operator is used to decrement the value of variable before using in the
expression. Pre-decrement value is first decremented and then used inside the expression.
b = --var;
 Suppose the value of variable var is 10 then we can say that value of variable „var‟ is firstly
decremented then updated value will be used in the expression.
Post Decrement Operator
 Post-decrement operator is used to decrement the value of variable immediatly after
executing expression completely in which post decrement is used.
 In the Post-decrement old value is first used in a expression and then old value will be
decrement by 1.
b = var--;
 Value of variable „var‟ is 5. Same value will be used in expression and after execution of
expression new value will be 4.
Example:
#include<stdio.h>

S.KAVITHA / AP / CSE / MSAJCE Page 18 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

> Greater than

>= Greater than or equal to

<= Less than or equal to

< Less than

#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 {

S.KAVITHA / AP / CSE / MSAJCE Page 19 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

printf("Line 1 - a is not equal to b\n" );


}
if ( a < b ) {
printf("Line 2 - a is less than b\n" );
}
else {
printf("Line 2 - a is not less than b\n" );
}
if ( a > b ) {
printf("Line 3 - a is greater than b\n" );
}
else {
printf("Line 3 - a is not greater than b\n" );
}

/* Lets change value of a and b */


a = 5;
b = 20;
if ( a <= b ) {
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a ) {
printf("Line 5 - b is either greater than or equal to b\n" );
}
}
OUTPUT:
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

S.KAVITHA / AP / CSE / MSAJCE Page 20 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

2.6.5 LOGICAL OPERATORS


 If we want to compare more than one conditions then we need to use logical operators.
 Suppose we need to execute certain block of code if and only if two conditions are satisfied
then we can use Logical Operator in C Programming.

Operator Description Example

&& Called Logical AND operator. If both the operands are (A && B) is false.
non-zero, then the condition becomes true.

|| Called Logical OR Operator. If any of the two (A || B) is true.


operands is 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

S.KAVITHA / AP / CSE / MSAJCE Page 21 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

2.6.6. CONDITIONAL OPERATORS [ ?: ] : TERNARY OPERATOR STATEMENT


They are also called as Ternary Operator .They also called as ?: operator
Ternary Operators takes on 3 Arguments
Syntax :
expression 1 ? expression 2 : expression 3
where
expression1 is Condition
expression2 is Statement Followed if Condition is True
expression 3 is Statement Followed if Condition is False
Meaning of Syntax :
 Expression1 is nothing but Boolean Condition i.e it results into either TRUE or FALSE
 If result of expression1 is TRUE then expression2 is Executed
 Expression1 is said to be TRUE if its result is NON-ZERO
 If result of expression1 is FALSE then expression3 is Executed
Expression1 is said to be FALSE if its result is ZERO
Example : Check whether Number is Odd or Even
#include<stdio.h>
void main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd");
}

2.6.7 BITWISE OPERATORS


Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is
as follows –

S.KAVITHA / AP / CSE / MSAJCE Page 22 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows −


A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and
variable 'B' holds 13, then −
Show Examples

Operator Description Example

& Binary AND Operator copies a bit to the result if it (A & B) = 12, i.e., 0000 1100
exists in both operands.

| Binary OR Operator copies a bit if it exists in (A | B) = 61, i.e., 0011 1101


either operand.

^ 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.

S.KAVITHA / AP / CSE / MSAJCE Page 23 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

<< 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.

2.6.8 ASSIGNMENT OPERATORS


Assignment Operator is Used to assign value to an variable.

Operator Description Example

= Simple assignment operator. Assigns values C = A + B will assign the value of


from right side operands to left side operand A + B to C

+= Add AND assignment operator. It adds the C += A is equivalent to C = C + A


right operand to the left operand and assign
the result to the left operand.

-= Subtract AND assignment operator. It C -= A is equivalent to C = C - A


subtracts the right operand from the left
operand and assigns the result to the left
operand.

*= Multiply AND assignment operator. It C *= A is equivalent to C = C * A


multiplies the right operand with the left
operand and assigns the result to the left
operand.

/= Divide AND assignment operator. It divides C /= A is equivalent to C = C / A


the left operand with the right operand and
assigns the result to the left operand.

S.KAVITHA / AP / CSE / MSAJCE Page 24 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

%= Modulus AND assignment operator. It takes C %= A is equivalent to C = C % A


modulus using two operands and assigns the
result to the left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment C ^= 2 is same as C = C ^ 2


operator.

|= Bitwise inclusive OR and assignment C |= 2 is same as C = C | 2


operator.

2.7 C PROGRAMMING EXPRESSION :


 In programming, an expression is any legal combination of symbols that represents a value.
 C Programming Provides its own rules of Expression, whether it is legal expression or illegal
expression. For example, in the C language x+5 is a legal expression.
 Every expression consists of at least one operand and can have one or more operators.
 Operands are values and Operators are symbols that represent particular actions.
Valid C Programming Expression :

Expressions Validity

a+b Expression is valid since it contain + operator which is binary operator

++a+b Invalid Expression

2.8 MANAGING INPUT AND OUTPUT OPERATIONS


Reading the data and displaying the result on the screen are two main tasks of any program. To
perform these tasks C has number of input and output functions.

S.KAVITHA / AP / CSE / MSAJCE Page 25 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

The I/O functions are classified into two types


1. Formatted functions
2. Unformatted functions.

Formatted functions Unformatted functions.


Can read and write all types of data values Can work only with character data type
Require conversion symbol to identify data Do not require conversion symbol to
type identify data type
Return the values after execution (value = Return the values after execution.But the
no of variables successfully read/written) return value is always the same

2.8.1 FORMATTED FUNCTIONS


1. scanf()
 Input values are generally taken by using the scanf function. The scanf function has the
general form.
scanf (“control string”, arg1, arg2, arg3 ………….argn);
The format field is specified by the control string and the arguments
arg1, arg2, …………….argn specifies the address of location where data is to be stored.

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:

S.KAVITHA / AP / CSE / MSAJCE Page 26 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

scanf (“%3d %4d”, &sum1, &sum2);


If the values input are 175 and 1342 here value 175 is assigned to sum1 and 1342 to sum2.
Suppose the input data was follows 1342 and 175.
The number 134 will be assigned to sum1 and sum2 has the value 2 because of %3d the number
1342 will be cut to 134 and the remaining part is assigned to second variable sum2.
If floating point numbers are assigned then the decimal or fractional part is skipped by the
computer.
To read the long integer data type we can use conversion specifier % ld & % hd for short integer.
Format specifiers
Format specifiers defines the type of data to be printed on standard output. Whether to print
formatted output or to take formatted input we need format specifiers. Format specifiers are also
called as format string.

Here is a complete list of all format specifiers used in C programming language.


Format specifier Description Supported data types
char
%c Character
unsigned char
short
unsigned short
%d Signed Integer
int
long
float
%e or %E Scientific notation of float values
double
%f Floating point float
%lf Floating point double
%Lf Floating point long double
unsigned int
%lu Unsigned integer
unsigned long
short
%o Octal representation of Integer.
unsigned short

S.KAVITHA / AP / CSE / MSAJCE Page 27 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

Format specifier Description Supported data types


int
unsigned int
long
%s String char *
unsigned int
%u Unsigned Integer
unsigned long
short
unsigned short
%x or %X Hexadecimal representation of Unsigned Integer int
unsigned int
long

Floating point numbers:


Field specifications are not to be use while representing a real number therefore real numbers are
specified in a straight forward manner using % f specifier.
The general format of specifying a real number input is
scanf (% f “, &variable);
Example:
scanf (“%f %f % f”, &a, &b, &c);
With the input data 321.76, 4.321, 678.The values 321.76 is assigned to a , 4.321 to b & 678 to
C.
If the number input is a double data type then the format specifier should be % lf instead of %f.

Input specifications for a character.


Single character or strings can be input by using the character specifiers.
The general format is
% xc or %xs
Where c and s represents character and string respectively and x represents the field width.

S.KAVITHA / AP / CSE / MSAJCE Page 28 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

The address operator need not be specified while we input strings.


Example:
scanf (“%c %15c”, &ch, name):
Here suppose the input given is a, Robert then a is assigned to ch and Robert will be assigned to
name.

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:

S.KAVITHA / AP / CSE / MSAJCE Page 29 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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.8.2 UNFORMATTED FUNCTIONS


1. getchar()
This function reads the character data type from the standard input. It reads one character at a
time till the user presses enter key.
Example
while ((ch[c] = getchar() ) ! = „\n‟)

2. putchar()
This function prints one character on the screen at a time, which is read by the standard input.
Example
putchar (ch [c] ) ;

3. getch() and getche()


These functions read any alphanumeric characters from the standard input device. The character
entered is not displayed by getch() function.
Example
ch = getch( );
4. putch()
This function prints any alphanumeric characters taken by the standard input device.
Example
putch(ch) ;
String I/O
1.gets()

S.KAVITHA / AP / CSE / MSAJCE Page 30 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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);

2.9 DECISION MAKING AND BRANCHING


 Decision making is about deciding the order of execution of statements based on certain
conditions or repeat a group of statements until certain specified conditions are met.
 It is broadly classified into two as shown below:

Branching

Conditinal Unconditional
Branching branching

2.9.1 CONDITIONAL BRANCHING:


Conditional branching is used to execute a statement or a group of statement based on certain
conditions. The branching will be taken or not depends on the condition.

S.KAVITHA / AP / CSE / MSAJCE Page 31 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

 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;

S.KAVITHA / AP / CSE / MSAJCE Page 32 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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);

S.KAVITHA / AP / CSE / MSAJCE Page 33 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

S.KAVITHA / AP / CSE / MSAJCE Page 34 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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()

S.KAVITHA / AP / CSE / MSAJCE Page 35 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

{
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;

S.KAVITHA / AP / CSE / MSAJCE Page 36 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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:

S.KAVITHA / AP / CSE / MSAJCE Page 37 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

S.KAVITHA / AP / CSE / MSAJCE Page 38 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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:

S.KAVITHA / AP / CSE / MSAJCE Page 39 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

2.9.2 UNCONDITIONAL BRANCHING STATEMENTS:


The control-flow statements of a language specify the order in which computations are
performed. It changes the program from normal sequence of execution
1. break
2. continue
3. goto
BREAK:
 The break statement provides an early exit from for, while, and do, just as from switch. A
break causes the innermost enclosing loop or switch to be exited immediately.
Syntax:
break;
Flowchart:

The figure below explains the working of break statement in all three type of loops.

S.KAVITHA / AP / CSE / MSAJCE Page 40 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

S.KAVITHA / AP / CSE / MSAJCE Page 41 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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.

S.KAVITHA / AP / CSE / MSAJCE Page 42 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

#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;
}

S.KAVITHA / AP / CSE / MSAJCE Page 43 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

GOTO AND LABELS


 goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.
Syntax:
goto label;
.............
.............
label:
statement;
 In this syntax, label is an identifier. When, the control of program reaches to goto
statement, the control of the program will jump to the label: and executes the code
below it.

The use of goto statement should be reduced as much as possible in a program.


Reasons to avoid goto statement
 using goto statement makes the logic of the program complex and tangled. goto
statement is considered a harmful construct and a bad programming practice.
 The goto statement can be replaced in most of C program with the use of break and
continue statements.
Example:

S.KAVITHA / AP / CSE / MSAJCE Page 44 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

#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();
}

2.10 LOOPING STATEMENTS


 Looping statements are used to execute a statement or a group of statements repeatedly until
the condition is true
 There are 3 types of loops in C programming:
1. while loop
2. for loop

S.KAVITHA / AP / CSE / MSAJCE Page 45 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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);

S.KAVITHA / AP / CSE / MSAJCE Page 46 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

S.KAVITHA / AP / CSE / MSAJCE Page 47 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

Difference between while and do..while


While Do..While

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)

S.KAVITHA / AP / CSE / MSAJCE Page 48 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

{
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;

S.KAVITHA / AP / CSE / MSAJCE Page 49 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

for(i=1;i<=5;i++)
{
printf("%d\t",i);
}
}
Output:
1 2 3 4 5

NESTED FOR LOOPS


 These loops are the loops which contain another looping statement in a single loop. These
types of loops are used to create matrix. Any loop can contain a number of loop
statements in itself.
Example:
main()
{
for (int i=0; i<=3; i++)
{
for (int j=0; j<=3; j++)
{
printf("i=%d j= %d\n",i ,j);
}
}
}
Output:
i=1 j=1
i=1 j=2
i=1 j=3
i=2 j=1
i=2 j=2
i=2 j=3
i=3 j=1

S.KAVITHA / AP / CSE / MSAJCE Page 50 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

i=3 j=2
i=3 j=3
Such type of nesting is often used for handling multidimensional arrays.

Multiple initialization inside for Loop


for (i=1,j=1;i<10 && j<10; i++, j++)
The difference between above for loop and a simple for loop:
a) It is initializing two variables. Note: both are separated by comma (,).
b) It has two test conditions joined together using AND (&&) logical operator. Note: You cannot
use multiple test conditions separated by comma, you must use logical operator to join
conditions.
c) It has two variables in increment part. Note: Should be separated by comma.

The Infinite Loop


 A loop becomes an infinite loop if a condition never becomes false.
for (;;) {
......
}
is an "infinite" loop, it can be broken by break or return.

2.14 SOLVING SIMPLE SCIENTIFIC AND STATISTICAL


PROBLEMS.
1. Write a c program to find whether a given number is perfect or not
#include<stdio.h>
void main() {
int num, i = 1, sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
while (i < num) {
if (num % i == 0) {
sum = sum + i;

S.KAVITHA / AP / CSE / MSAJCE Page 51 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

}
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;

printf("Enter the number of terms\n");


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
{

S.KAVITHA / AP / CSE / MSAJCE Page 52 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

next = first + second;


first = second;
second = next;
}
printf("%d\n",next);
}
return 0;
}

OUTPUT:
Enter the number of terms
8
First 8 terms of Fibonacci series are :-
0
1
1
2
3
5
8
13

3. Program to Check Prime Number


#include <stdio.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i<=n/2; ++i)
{
if(n%i==0)
{

S.KAVITHA / AP / CSE / MSAJCE Page 53 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

S.KAVITHA / AP / CSE / MSAJCE Page 54 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

Sum of the digit 123 is 6

5. To develop a c program to print first N numbers that is divisible by 5


#include<stdio.h>
void main()
{
int i,n;
printf("Enter a number:\n");
scanf("%d",&n);
printf("\nFirst %d numbers which are divisible by 5",n);
for(i=1;i<=n;i++)
{
if(i%5==0)
printf("\n%d",i);
}
}
OUTPUT:
Enter a number:
20
First 20 numbers which are divisible by 5
5
10
15
20

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()

S.KAVITHA / AP / CSE / MSAJCE Page 55 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

{
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);

S.KAVITHA / AP / CSE / MSAJCE Page 56 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

2. Enter the coefficients of quadratic equation:1 3 1


Roots are real and distinct....
X1=-0.38
X2=-2.62

3. Enter the coefficients of quadratic equation:1 2 1


Roots are real and equal...
X1=-1.00
X2=-1.00

4. Enter the coefficients of quadratic equation:0 2 5


Roots cannot be found as the equation is linear

7. Write a C program to check whether the given number is palindrome or not


#include<stdio.h>
#include<conio.h>
void main()
{
int num,rev=0,rem,temp;
printf("\n\tEnter a number:");

S.KAVITHA / AP / CSE / MSAJCE Page 57 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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()

S.KAVITHA / AP / CSE / MSAJCE Page 58 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

{
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

9. C program to check odd or even using modulus operator


#include <stdio.h>
void main()
{
int n;
printf("Enter an integer\n");
scanf("%d", &n);

S.KAVITHA / AP / CSE / MSAJCE Page 59 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

if (n%2 == 0)
printf("Even\n");
else
printf("Odd\n");
}

OUTPUT:
1. Enter an integer
45
Odd
2. Enter an integer
34
Even

10. Factorial program in c using for loop


#include <stdio.h>
void main()
{
int c, n, fact = 1;
printf("Enter a number to calculate it's factorial\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
fact = fact * c;
printf("Factorial of %d = %d\n", n, fact);
}
OUTPUT:
Enter a number to calculate it's factorial
5
Factorial of 5 = 120
11. C program to add n numbers
#include <stdio.h>

S.KAVITHA / AP / CSE / MSAJCE Page 60 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

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

12. C program to swap two numbers


#include <stdio.h>
void main()
{
int x, y, temp;
printf("Enter the value of x and y\n");

S.KAVITHA / AP / CSE / MSAJCE Page 61 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

scanf("%d%d", &x, &y);


printf("Before Swapping\nx = %d\ny = %d\n",x,y);
temp = x;
x = y;
y = temp;
printf("After Swapping\nx = %d\ny = %d\n",x,y);
}
OUTPUT:
Enter the value of x and y
3
6
Before Swapping
x=3
y=6
After Swapping
x=6
y=3

13. Program to Compute Quotient and Remainder


#include <stdio.h>
void main(){
int dividend, divisor, quotient, remainder;
printf("Enter dividend: ");
scanf("%d", &dividend);
printf("Enter divisor: ");
scanf("%d", &divisor);
quotient = dividend/divisor;
remainder = dividend%divisor;
printf("Quotient = %d\n",quotient);
printf("Remainder = %d",remainder);

S.KAVITHA / AP / CSE / MSAJCE Page 62 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

}
OUTPUT:
Enter dividend: 25
Enter divisor: 4
Quotient = 6
Remainder = 1

14. C Program to Check Armstrong Number


A positive integer is called an Armstrong number of order n if
abcd... = an + bn + cn + dn + ...
In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the
number itself. For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
#include <stdio.h>
void main()
{
int number, originalNumber, remainder, result = 0;
printf("Enter a three digit integer: ");
scanf("%d", &number);

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);

S.KAVITHA / AP / CSE / MSAJCE Page 63 of 64


Unit-II GE6151- COMPUTER PROGRAMMING

}
OUTPUT:
Enter a three digit integer: 371
371 is an Armstrong number.

S.KAVITHA / AP / CSE / MSAJCE Page 64 of 64

You might also like