C Language Basics
C Language Basics
C Language Basics
Introduction to Computers
Computer Systems
The term computer is derived from the word compute.A computer is an electronic device that accepts
data and instructions as an input from the user then processes the data and provides useful
information ,known as output.
Computer Hardware
Computer Software
A Computer System:
Keyboard and Mouse:These are used for receiving inputs from the user.
CHARACHTERISTICS:
Speed:The computer is a fastest electronic device that can solve large and complex problems in few
seconds.The speed of a computer generally depend on its hardware configurations.
Storage:A computer can store huge amounts of data.The storage area of computer system categorized
into 1.Main Memory 2 Secondary Memory.
Reliability:A computer produces results with no error.The computers are regarded as trustworthy
machines.
Versatility:Computers perform varied tasks and can be used for many different purposes.
Deligence:Computers can perform repetitive calculations any number of timeswith the same level of
accuracy.
Example:
Mouse: The mouse allows the user to select elements on the screen on the screen,such as
tools,icons,buttons,by pointing and clicking them.The mouse also known as a pointing device.
Scanner:A scanner is an input device that converts documents and images as the digitized images
understandable by the computer.The types of scanners are:1.Flatbed scanner 2.Drum Scanner 3.Slide Scanner
4.handheld Scanner.
PROCESSOR: It is used to perform the calculations and data processing on data that is through the input
device.It is also known as CPU.
The CPU consists of Control Unit(CU) and ALU.CU atores the instruction set ,which specifies the operations to
be performed by the computer.CU transfers the data and the instructions to the ALU for an arithmetic
operation.ALU performs arithmetical and logical operations.
Apart from CU and ALU,CPU seeks help from the following hardware devices to process data.
1.Motherboard: It refers to a device used for connecting the CPU with the input and output devices.The
componenets on the motherboard are connected to all parts of a computer and are kept insulated from each
other.These are:
a)Bus:Electrical pathways that transfer data and instructions among different parts of the computer.
b)System Clock:It is used for synchronizating the activities performed by the computer.The faster the system
clock ,the faster is the processing speed of the computer.
c)Microprocessor:CPU component that performs the processing and controls the activities performed by the
different parts of the computer.
d)ROM:It is a chip that contains the permanent memory of the computer that stores information ,which can
not be modified by the user.
Random Access Memory(RAM):It is known as primary memroty.It stores data and programs,until the
computer is used.It is a chip that cab be connected to the RAM slots in the motherboard.
Video Card:It is an interface between the monitor and CPU and used to display graphics.
Sound Card:It is a circuit board placed on the motherboard and is used to enhance the sound capabilities of
computer.
OUTPUT DEVICES:They are use for providing the output of program that is obtained after operations specified
in a program.
Example: Monitor,printer.
Monitor:It is the most commonl used output device that produces visual displays generated by the computer.
The monitor is also known as a screen.The monitors classified as Cathode ray Tube(CRT) monitors and Liquid
Crystal Display(LCD) monitors.
Printer:It is an output device that is used to produce a hardcopy of the electronic text displayed on the
screen,in the form of paper.The performance of printer is measured in terms of dots per inch(DPI) and pages
per minut(PPI).The greater the DPI parameter of a printer,the better is the quality of the output generated by
it.
Printers types are 1.Dot Matrix Printers 2.Inkjet Printers 3.Laser Printers.
Speaker:The speaker is an electromechanical tranducer that converts an electrical signal into sound.They are
attached to a computer as output devices.
Plotter:It is commonly used output device that is connected to a computer to print large documents such as
engineering or constructional drawings.
Plotters types are 1.Drum plotter 2.Flat bed Plotter 3.Inkjet Plotter 4.Electrstatic Plotter.
MEMORY:It is for storing the input data.Memory can be primary memory and seconday memory.
Primary memory includes Random Access Memory(RAM) and Secondary memory includes harddisks and
floppy disks.
Primary Memory:It is available in the computer as a built-in-unit of the computer.The primary memory is
represented as a set of locations with each location occupying 8 bits.each bit in the memory is identified a
unique address.
ROM(Read Only Memory):It is used store data and instructions,even when the computer is turned off.It is
permanent memory of the computer where the contents cannot be modified by an end user.
RAM(Random access Memory):It is the read/write memory unit in which the information is retained only as
long as there is a regular power supply.When the power supply is interrupted or switched off,the information
stored in the RAM is lost.Ram is a volatile memory.
Cache memory:It is used to store the data and the related application that was last processed by the CPU.The
cache memory is always is placed between CPU and the memory of the computer.
Secondary Memory:It is a memory which represents the external storage devices that are connected to the
computer.The devices can be classified as:
Types of Software
Computing Environments
In the early days of computers, there was only one environment, the mainframe computer hidden in a
central computing department. With the advent of minicomputers and personal computers, the
environment changed with computers on virtually every desktop. several different environments are:
Time-Sharing Environment
Client/server Environment
Distributed Computing
A personal computer is a general-purpose computer whose size, capabilities and original sale price make it useful for
individuals, and is intended to be operated directly by an end-user with no intervening computer operator.All of the
computer hardware components are tied together in our personal computer.
Time-sharing Environment:
All computing must be done by the central computer.Central computer must control the shared resources,it
must manage the shared data and printing and it must do the computing.These computer are may be
minicomputers or central mainframes.
The Client/Server Environment
A client/server computing environment splits the computing function between a central computer and user’s
computers.In this environment ,the users microcomputers or workstations are called the clients.Central
computer ,which may be powerful minicomputer or microcomputer is known as server.
Distributed Computing
This environment provides a seamless integration of computing functions between servers and clients.The
Internet provides connectivity to different servers throughout the world.This environment provides a
reliable,scalable and highly available network.
Computer Languages
To write a program for a computer, we must use a computer language. Over the years computer languages
have evolved from machine language to natural languages.
Machine Languages
Symbolic Languages
High-Level Languages
Here we explain the procedure for turning a program written in C into machine language. The process
is presented in a straightforward, linear fashion, but you should recognize that these steps are
repeated many times during development to correct errors and make improvements to the code.
Writing and Editing Programs
Compiling Programs
Linking Programs
Executing Programs.
Building a C Program
PROGRAM DEVELOPMENT
1) Statement of Problem
a) Working with existing system and using proper questionnaire, the problem should be explained
clearly.
b) What inputs are available, outputs are required and what is needed for creating workable solution
should be understood clearly.
2) Analysis
b) We also judge that which method gives best results among different methods of solution.
3) Designing
4) Implementation
The algorithms and flow charts developed in the previous steps are converted into actual programs in
the high level languages like C.
4. A) Compilation
Translate the program into machine code. This process is called as Compilation. Syntactic errors are
found quickly at the time of compiling the program. These errors occur due to the usage of wrong
syntaxes for the statements.
Eg: x=a*y+b
There is a syntax error in this statement, since, each and every statement in C language ends with a
semicolon (;).
4. B) Execution
The next step is Program execution. In this phase, we may encounter two types of errors.
Runtime Errors: these errors occur during the execution of the program and terminate the program
abnormally.
Logical Errors: these errors occur due to incorrect usage of the instructions in the program. These
errors are neither detected during compilation or execution nor cause any stoppage to the program
execution but produces incorrect output.
Problem Solving
Problems that can be solved through a computer may range in size and complexity. since computer do
not posses any common sense and cannot make any unplanned decisions, the problem whether it is
simple or complex ,has to broken into well defined set of solution steps for the computer to
implement.
Problem solving is the process of solving a problem in a computer system by following a sequence of
steps.
Algorithm: An algorithm is sequence of steps written in the form of English phrases that specify the tasks
that are performed while solving a problem. It involves identifying the variable names and types that would be
used for solving the problem
Pseudo code: is much similar to algorithms .It uses generic syntax for describing the steps that are
performed for solving a problem along with the statements written using generic syntax, pseudo code can also
use English phrases for describing action.
Flow chart: Flowchart is the graphical representation of the flow of control and logic in the solution of a
problem or the flowchart is a pictorial representation of an algorithm
ALGORITHM TO FIND ADDITION OF TWO NUMBERS
INTEGERS (SUM=NUM1+NUM2)
Step 1: START
Step 6: STOP
else
STEP 4: IF (year%400==0)
else
BEGIN
RREAD: Integer n1
READ: Integer n2
SET: r=n1+n2
DISPLAY: r
END
PSEDOCODE TO FIND average of three numbers
BEGIN
READ: m1.m2.m3
COMPUTE: avg=m1+m2+m3/3
DISPLAY: avg
END
BEGIN
DEFINE: Integer n
READ: n
IF: n% 2==0
ELSE
END IF
END
Flow chart symbols
The only language the computer can understand is machine language (binary language).
A high level language is English like language where one instruction typically translates into a series of
machine-language instructions.
A low level language corresponds closely to machine code so that a single low-level language
instruction translates to a single machine language instruction.
Structure of C program
Documentation Section
Linkage Section
Definition Section
Function1()
Function2()
……………
FunctionN()
Documentation section: It consists of a set of comment lines giving the name of the program, the
author and other details.
Link Section: It provides instructions to the compiler to link functions from system library.
Global Declaration section: Some variables are used in more than one function .Such variables are
called global variables.
Main() Function section:
Every C program have one main () function. This section contains two parts, declaration part and
executable part.
The declaration part declares all the variables used in the executable part. There is at least one
statement in the executable part. These two parts must appear between the opening and the closing
braces. The program execution begins at opening brace and ends at closing brace.
The closing brace of the main function is the logical end of the program .All statements in the
declaration and executable part ends with semicolon.
Subprogram Section:
It contains all user defined functions that are called in the main function.
All sections, except the main function section may be absent when they are not required.
C Character Set:
A programming language is designed to help process certain kinds of data containing of numbers,
characters and strings and to provide useful output known as information
The task of processing data is accomplished by executing a sequence of precise instructions called a
program.
These instructions are formed using certain symbols and words accordingly to some rigid rules known
as syntax rules.
Every program instruction must confirm precisely to the syntax rules of the program.
1. Letters.
2. Digits:- 0..9
3.Special characters:-
4.White Spaces:
Blank Space.
Horizontal tab
Vertical tab.
New Line
Form Feed
Trigraph characters:
Many non- English keywords do not support all the special characters. ANSI C introduces the
concept of trigraph sequences to provide a way to enter certain characters that are not available on
some keyboards. Each trigraph sequence consists of three characters (two question marks followed by
another character).
Trigraph Characters:
??= #
??( [
??/ \
??) ]
??‘ ^
??< {
??> }
??- ~ (Tilde)
C Tokens: Tokens are individual words and punctuation marks in passage of text. In C, program the
smallest individual units are known as C Tokens. C has six types of Tokens.
Keywords:
keywords are the words that convey a special meaning to the c compiler. The keywords cannot be used
as variable names because by doing so.
Identifiers:
Identifiers are used as the general terminology for the names of variables, functions and arrays. These
are user defined names consisting of arbitrarily long sequence of letters and digits with either a letter
or the underscore(_) as a first character.
There are certain rules that should be followed while naming c identifiers:
They must consist of only letters, digits, or underscore. No other special character is allowed.
Examples:
Name Remark
_ a9 Valid
a_b valid
x* Invalid
Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after
their definition.
Integer literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix:
0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30l /* long */
Floating-point literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. We
can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, we must include the decimal point, the exponent, or both and
while representing using exponential form; you must include the integer part, the fractional part, or
both. The signed exponent is introduced by e or E.
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */
Character constants
Character literals are enclosed in single quotes, e.g., 'x' and can be stored in a simple variable of char
type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t').
There are certain characters in C when they are preceded by a backslash they will have special meaning
and they are used to represent. Here, we have a list of some of such escape sequence codes:
\\ \ character
\‘ ' character
\“ " character
\? ? Character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
String literals
String literals or constants are enclosed in double quotes "". A string contains characters that are
similar to character literals: plain characters, escape sequences.
We can break a long line into multiple lines using string literals and separating them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
Syntax:
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
int main()
int area;
return 0;
Example :
#include <stdio.h>
void main()
Variables:
A variable is nothing but a name given to a storage area that our programs can manipulate.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-
sensitive.
TYPE DESCRIPTION
Variable Definition in C:
A variable definition means to tell the compiler where and how much to create the storage for the
variable. A variable definition specifies a data type and contains a list of one or more variables of that
type as follows:
type variable_list;
Here, type must be a valid C data type .variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here:
Examples:
int i, j, k;
char c, ch;
float f, salary;
double d;
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an
equal sign followed by a constant expression as follows:
Data Types:
In the C programming language, data types refer to an extensive system used for declaring variables or
functions of different types. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.
1. Basic Types:
2. Enumerated Type
They are again arithmetic types and they are used to define variables that can only be assigned certain
discrete integer values throughout the program.
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function
types.
Data Types :
Operators:
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C language is rich in built-in operators and provides the following types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators.
Arithmetic Operators.
3 * Multiplication
4 / Division
5 % Modulus
#include
void main()
int a=9,b=4,c;
c=a+b;
printf("a+b=%d\n",c);
c=a-b;
printf("a-b=%d\n",c);
c=a*b;
printf("a*b=%d\n",c);
c=a/b;
printf("a/b=%d\n",c);
c=a%b;
Assignment Operators.
The most common assignment operator is =. This operator assigns the value in right side to the left
side.
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Relational Operator:
Relational operators checks relationship between two operands. If the relation is true, it returns value
1 and if the relation is false, it returns value 0.
== Equal to 4==2(false)
Logical Operators:
Logical operators are used to combine expressions containing relation operators. In C, there are 3
logical operators:
&& Logical AND If c=5 and d=2 then,((c==5) && (d>5)) returns false.
Conditional Operator
Conditional operator takes three operands and consists of two symbols? And:. Conditional operators
are used for decision making in C.
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
Bitwise Operators.
A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming.
Operator Meaning
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
Other Operators
Comma Operator:
Comma operators are used to link related expressions together.
For example:
int a,c=5,d;
Program:
#include <stdio.h>
int main()
int a;
float b;
double c;
char d;
return 0;
Executing a C program.
Translators: are system software used to convert high-level language program into machine-language code.
Compiler : Coverts the entire source program at a time into object code file, and saves it in secondary
storage permanently. The same object machine code file will be executed several times, whenever needed.
Interpreter : Each statement of source program is translated into machine code and executed immediately.
Translation and execution of each and every statement is repeated till the end of the program. No object code
is saved. Translation is repeated for every execution of the source program.
/* prefix operators */
#include<stdio.h>
void main()
int a = 7, b = 12, c;
c = b * (++a) + 5 * (++a);
printf(“\n b = %d”,b);
printf(“\n c = %d”,c);
Output:
a=9
b = 12
c = 153 ( 12 * 9 + 5 * 9)
If ++ is after the operand, as in a++, the increment takes place after the expression is evaluated.
If ++ is before the operand, as in ++a, the increment takes place before the expression is evaluated.
/* prefix and postfix operators */
#include<stdio.h>
void main()
int a = 7, b = 12, c;
c = b * (a++) + 5 * (++a);
printf(“\n b = %d”,b);
printf(“\n c = %d”,c);
}
Output:
a=9
b = 12
c = 136 ( 12 * 8 + 5 * 8) .
/* postfix operators */
#include<stdio.h>
int main() {
int a = 7, b = 12, c;
c = b * (a++) + 5 * (a++);
printf(“\n b = %d”,b);
printf(“\n c = %d”,c);
}
• C Program to find area and circumference of circle
#include<stdio.h>
void main()
int rad;
float pi=3.14,area,ci;
scanf("%d",&rad);
ci = 2 * pi * rad;
Type Conversion:
The type conversion or type casting refers to the process of changing an entity of one type into
another.
1.Implicit conversion.
2.Explicit Conversion
• Implicit Conversion:
It is an automatic type conversion. In a mixed type expression ,data of one or more sub types can be
converted to a super type as needed at runtime. So the program will run correctly.
Ex: double a;
long b;
int c;
If(a>b) a=c;
If (c>b) b=c;
If(a==b) a+=2’
Although a, b, c belong to different data types, they will be automatically converted to equal data types
each time.
Data can be lost when floating point representations are converted to integral representations as the
fractional components of the floating point values will be truncated.
Conversely, converting from an integral representation to a floating point one can also lose precision,
since the floating point may be unable to represent the integer exactly.
• Explicit Conversion
The explicit conversion can be made possible to convert one data type to another by forcefully and it is
different from the implicit conversion.
int a=10;
float (a);
• Example2:
double d=6.5;
double b=8.5;
int result=(int)(d)+(int)(b)
2.By using the input/output statements several functions are available for input/output operations in
C.These functions are collectively known as the standard I/O library.
1. Unformatted Functions
Input functions:
Output Functions:
2. Formatted Functions
Input Functions:
scanf() fscanf()
Output Functions:
printf() fprintf()
getchar():
A single character can be given to the computer string using C input library function getchar().
Syantax:
char variable=getchar();
Example:
char x;
x=getchar();
The getchar() functions is written in standard I/O libray.It reads a single character from
standard input device
putchar():
The putchar() function is used to display one character at a time on the standard output device.
Syntax:
putchar(character variable);
Example
char x;
putchar(x);
getc():
getc() function is used to accept a single character from the standard input device.
Syntax:
character varavle=getc();
Example
char c;
c=getc();
putc():
Syantax:
putc(character variable);
Example:
char c;
putc(c);
Note: The getc() and putc() functions are often used in file processing
The gets() function is used to read the string from the standard input device.
Syntax:
gets(string);
Syntax:
puts(string) ;
#include<stdio.h>
#include<conio.h>
void main()
char name[25];
puts(“ENTER NAME”);
gets(name);
puts(“Display name”);
puts(name);
}
The getch() reads a single character directly from the keyboard without echoing to the screen.
The getche() reads a single character from the keyboard and echoes it to the current text window.
Syntax:
int getch(void);
int getche(void);
3 isdigit(ch) Is ch is digit
Formatted I/O refers to input and output that has been arranged in a particular format using these
statements, the user must specify the type of data that is going to be accessed.
INPUT OUTPUT
scanf() printf()
fscanf() fprintf()
The scanf() function is used to read information from the standard input devices( keyboard).scanf()
starts with a string argument and may contain additional arguments.
Syntax:
scanf(“control string”,&var1,&var2,--&varn);
The control string consists of character groups. each character group must begin with a percentage
sign ‘%’.The character group contains percentage sign, followed by conversion character.
var1,var2--- are the arguments or variables in which the data is going to be accepted.
Example:
int n;
scanf(“%d”,&n);
CONTROL STRING
It is the type of data that the user going to accept via the input statements, this can be formatted and
always preceded with a ‘%’ sign
1 %c SINGLE CHARACTER
2 %d DECIMAL INTEGER
3 %s STRING
4 %f FLOAT
6 %u UNSIGNED INTEGER
7 %o OCTAL INTEGER
8 %x HEXADECIMAL INTEGER
9 %e FLOAT
10 %h SHORT INTEGER
CONVERSION SPECIFIERS
CODE FORMAT
%c Character
%d Decimal integer
%f Floating-point numbers
%u Unsigned integer
%o Octal integer
%x Hexadecimal integer
%p Display a pointer
%n The associated argument must be a pointer to integer, This sepecifier causes the
number of characters written in to be stored in that integer
The scanf() control string consists of ‘%’ at the beginning and type indicator at the end.Apart from that
it can have *,a maximum field width indicator and a type indicator modified.
Example:
%10.2f
%10d
Example:
%*d.
If input consists of 6 values and we want to ignore the middle 3 values we can write:
scanf(“%d%d%*d%*d%*d%d”,&a,&b,&c,);
RULES:
1.The control string must be preceded with sign and must be within quotations.i.e the address of the
variable should be passed.
2.If there is a number of input data items ,items must be separated by commas and must be preceded
with(&) sign except for string input.
3.The control string and the variables going to input should match with other.
5.The scanf() reads the data values until the blank space in numeric input or maximum number of
character have been read,or an error is detected.
Syntax:
Example: printf(“RESULT=%d”,n);
Field width plays an important role in printf statements while producing reports in a formatted
manner. Field width indicates the least number of columns that will be located to the output.
Example:
i=29;
OUTPUT:
SPACE SPACE 2 9
If the value is more than specified columns, field width is ignored and number of column used is equal
to the number of column required by the arguments.
Example:
i=12345;
Control Statements
In a program all the instructions are executed sequentially by default. In some situation we may have
to change the execution order of statements based on condition or to repeat a set of statements until
certain conditions are met .In such situations conditional and control statements are very useful.
Example:
i=i+1;
j=j+1;
2) Selection statements: Here the sequence of the instructions are determined by using the result of
the condition.
Example:
if(x>y)
i=i+1;
else
j=j+1
3) Iteration Structure: In which statements are repeatedly executed .These forms program loops.
Example:
for(i=0;i<=9;i++)
i=i+1;
If Statement:
The if staement is a decision making statement.It is used to control the flow of execution of statements
and also used to test logically whether the condition is true or false .It is always used in conjunction
with condition .The statement is used when a question require answer.
Syntax1:
if(condition)
statement;
Syntax2:
if(condition)
statements;
If the condition is true, then the statements are executed. The statements may be a single or group of
statements.
If-else Statement:
It is two way decision making statement and always used in conjunction with condition .It is used to
control the flow of execution and also used to carry out the logical test and then pickup one of the two
possible actions on the logical test.
It is used to execute some statements when the condition is true and execute some other statements,
when the condition is false.
Syntax:
if(condition)
statements;
else
statements;
When a series of if-else statements are occurred in a program. we can write an entire if-else statement
in another if-else statement called nesting and the statement is called nested if.
Syntax: if(condition)
{ if(condition)
{ statement2;
else {
statement3; }
} else
statement1;
If–else ladder:
Nested if statements can become complex if there are more than 3 alternatives and indentation is not
consistent, it may be different for us to determine the logical structure of the if statement. In this
situation we can use the nested if as the else if ladder.
Syantax: if(condition1)
{ staement1;
else if(condition2)
{ statement2;
else if(condition3)
{ staement3;
Flowchart:
simple if:
int main()
{
int age;
scanf(“%d”,&age);
getch();
int main()
int number;
scanf(“%d”, &number);
if((number %2) == 0)
printf(“%d is even number.”,number);
else
void main()
int year;
scanf("%d",&year);
if((year %100) == 0)
if((year % 400) == 0)
else
else
if((year % 4) == 0)
else
getch();
voidmain()
int marks;
scanf("%d", &marks);
if(marks >= 75)
printf("Distinction");
printf("First class");
printf("Second class");
printf("Third class");
else
printf("Failed");
#include<conio.h>
#include<math.h>
void main()
float a,b,c,root1,root2;
clrscr();
scanf("%f%f%f",&a,&b,&c);
/*checking condition*/
if(b*b>4*a*c)
root1=-b+sqrt(b*b-4*a*c)/2*a;
root2=-b-sqrt(b*b-4*a*c)/2*a;
printf("\n*****ROOTS ARE*****\n");
printf("\n root1=%f\n root2=%f",root1,root2);
else
getch();
SWITCH CASE:
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each switch case.
SYNTAX:
switch(expression)
default : statement(s);
The expression used in a switch statement must have an integral or enumerated type, or be of
a class type in which the class has a single conversion function to an integral or enumerated
type.
You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the switch,
and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.
void main()
float a,b;
char opr;
scanf("%f %c %f",&a,&opr,&b);
switch(opr)
case '+':
printf("Sum : %f",(a + b));
break;
case '-':
break;
case '*':
break;
case '/':
break;
default:
printf("Invalid Operation!");
/* Write a C program, which takes two integer operands and one operator form the
user, performs the operation and then prints the result. (Consider the operators +,-,*,
/, % and use Switch Statement) */
#include<stdio.h>
#include<conio.h>
void main()
int a,b,res,ch;
clrscr();
printf("\t *********************");
printf("\n\tMENU\n");
printf("\t********************");
printf("\n\t(1)ADDITION");
printf("\n\t(2)SUBTRACTION");
printf("\n\t(3)MULTIPLICATION");
printf("\n\t(4)DIVISION");
printf("\n\t(5)REMAINDER");
printf("\n\t(0)EXIT");
printf("\n\t********************");
scanf("%d",&ch);
scanf("%d%d",&a,&b);
switch(ch)
case 1:
res=a+b;
printf("\n Addition:%d",res);
break;
case 2:
res=a-b;
printf("\n Subtraction:%d",res);
break;
case 3:
res=a*b;
printf("\n Multiplication:%d",res);
break;
case 4:
res=a/b;
printf("\n Division:%d",res);
break;
case 5:
res=a%b;
printf("\n Remainder:%d",res);
break;
case 0:
exit();
break;
default:
getch();
LOOPS:
There may be a situation, when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages:
FOR LOOP
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax:
statement(s);
The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of
the loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement.
This statement allows you to update any loop control variables. This statement can be left blank, as
long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false, the
for loop terminates.
• FLOWCHART
FORLOOP
int main()
int n,i,factors = 0;
scanf("%d",&n);
{
if((n % i)==0) ++factors;
if (factors == 2)
else
/* Write a C program to generate all the prime numbers between 1 and n, where n is a value
supplied by the user. */
#include <stdio.h>
void main()
int no,counter,counter1,check;
clrscr();
scanf("%d",&no);
check = 0;
if(counter%counter1 == 0)
{
check++; // INCREMENT CHECK IF NO. IS NOT A PRIME NO.
break;
if(check == 0)
printf("%d\t",counter);
getch();
Sum=1-x2/2! +x4/4!-x6/6!+x8/8!-x10/10! */
#include <stdio.h>
#include <math.h>
void main()
int counter,f_coun;
float sum=0,x,power,fact;
clrscr();
scanf("%f",&x);
fact=1;
fact *= f_coun;
sum=sum+(pow(-1,counter)*(pow(x,power)/fact));
printf("SUM : %f",sum);
getch();
int main ()
#include <math.h>
void main()
clrscr();
scanf("%d",&tim_intrval);
scanf("%d",&time);
scanf("%f",&velos);
scanf("%f",&accl);
getch();
/*Write a C program to read in two numbers, x and n, and then compute the sum of this geometric
progression:1+x+x2+x3+………….+xn For example: if n is 3 and x is 5, then the program computes
1+5+25+125.Print x, n, the sum Perform error checking. For example, the formula does not make
sense for negative exponents - if n is less than 0. Have your program print an error message if n<0,
then go back and read in the next pair of numbers of without computing the sum.Are any values of x
also illegal ? If so, test for them too. */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
int s_sum,i,x,n;
clrscr();
printf("Enter the values for x and n:");
scanf("%d %d",&x,&n);
if(n<=0 || x<=0)
else
printf("Value is valid\n");
s_sum=1;
for(i=1;i<=n;i++)
s_sum=s_sum+pow(x,i);
printf("Sum of series=%d\n",s_sum);
getch();
WHILE LOOP
A while loop statement in C programming language repeatedly executes a target statement as long as a
given condition is true.
Syntax:
while(condition)
statement(s);
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, program control passes to the line immediately following the loop
FLOW CHART
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the
result is false, the loop body will be skipped and the first statement after the while loop will be executed
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
scanf("%d",&num);
while(num!=0)
k=num%10;
sum=sum+k;
k=num/10;
num=k;
}
printf("Sum of the digits:%d",sum);
getch();
#include <stdio.h>
void main ()
int a = 0;
while( a <=10 )
a++;
DO WHILE:
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C
programming language checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax:
do
statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.
PROGRAM TO DISPLAY 10 NUMBERS
#include <stdio.h>
int main ()
int a = 0;
do
a = a + 1;
while( a < 9 );
break Statement
In C programming, break is used in terminating the loop immediately after it is encountered. The break
statement is used with conditional if statement.
break;
continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements
are used.
continue;
goto Statement
In C programming, goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.
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/s after it.