Computer Is A Programmable Machine That Receives Input, Store & Manipulate Data & Provides Output in Useful Format. The
Computer Is A Programmable Machine That Receives Input, Store & Manipulate Data & Provides Output in Useful Format. The
Introduction
Computer is a programmable machine that receives input, store & manipulate data & provides output in useful format. The
components of computer are: input, memory, CPU and output.
1) Understand the problem thoroughly. Decide the actual outputs required, and the format in which it is required.
2) Analyze the problem and find out what are the input data provided
4) Draw flow chart and write algorithms steps to formulate the logic.
5) Translate the logic set in to program steps using the character set, keywords, allowed variable names and grammatical rules
of the programming language. -coding, or programming
8) If expected result is not getting, modify the logic or program depending up on the situation.
This refers to the accuracy of the calculations. It should be clear that all other program enhancements will be
meaningless if the calculations are not carried out correctly.
2. Clarity:-
This refers to the overall readability of the program, with particular emphasis on its underlying logic. If a program is
clearly written it should be possible for another programmer to follow the program logic without undue effort.
3. Simplicity:-
The clarity and accuracy of a program are usually enhanced by keeping things as simple as possible, consistent with the
overall program objectives.
4. Efficiency:-
It is concerned with execution speed and efficient memory utilization.
5. Modularity:-
Many programs can be broken down into a series of identifiable subtasks. It is good programming practice to
implement each of these subtasks as a separate program module.
6. Generality:
Programs should be as general as possible, within reasonable limits. For example, we may design a program to read in
the values of certain key parameters rather than placing fixed values into the program.
1
MODULE 1 CS100 COMPUTER PROGRAMMING
III .Introduction to C
C is a general purpose, structured programming language. C was developed and first implemented by Dennis Ritchie at
Bell Laboratories in the 1970‘s.
C is often called a middle level computer language.
It is because it combines the best elements of high level languages with the control and flexibility of assembly
language.
C programs are efficient, fast and highly portable.
Portability means that C programs written on one computer can be run on another with little or no modification.
C is a structured language.
A structured language allows variety of programs in small modules. It is easy for debugging, testing and maintenance if
a language is a structured one.
Features of C
IV Structure of a C Program
Every C program consists of one or more functions, one of which must be main().
Function name is always followed by a pair of parenthesis, as in the case of main().
The program execution begins in main() function. The statements within a function are always enclosed within a pair of
{}. The braces may contain combinations of elementary statements (called expression statements) and other compound
statements. Each expression statement must end with a semicolon(;). Comments may appear anywhere within a
program, as long as they are place within the delimiters /* and */.These are used in a program to enhance its readability
and understanding. Comments do not affect the execution speed and the size of a program.
/* Comments*/
/*Comments*/
Declaration part
Executable part
2
MODULE 1 CS100 COMPUTER PROGRAMMING
Include header file section
C program depends upon some header files for function definition that are used in program. Each header file by default is
extended with .h. The file should be included using #include directive as given below.
Eg:-#include<stdio.h>or #include”stdio.h”.
Global declaration
This section declares some variables that are used in more than one function. These variables are known as global
variables.These variables must be declared outside of all the functions.
Function main
Every program written in C language must contain main() function. Empty parenthesis after main is necessary. The function
main() is the starting point of every C program.
Declaration part
The declaration part declares the entire variables that are used in executable part.
The initialization means providing initial value to the variables.
Executable part
This part contains the statements following the declaration of the variables. This part contains a set of statements or a single
statement. These statements are enclosed between the braces.
User-defined function
The functions defined by the user are called user-defined functions. These functions are generally after the main() function. They
can also be defined before main() function.
Comments
Comments are not necessary in the program. However, to understand the flow of program the programmer can include comments
in the program. Comments are to be inserted by the programmer. It is useful for documentation.
#include<stdio.h>
void main()
{
printf(―Hello Students‖);/* print statement*/
}
The output will be : ―Hello Students‖
V. C PREPROCESSOR DIRECTIVES:
Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. This process is called
preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol.
Below is the list of preprocessor directives that C programming language offers.
3
MODULE 1 CS100 COMPUTER PROGRAMMING
Preprocessor Syntax/Description
Syntax: #define
Macro This macro defines constant value and can be any of the basic data types.
4
MODULE 1 CS100 COMPUTER PROGRAMMING
If this statement is included in program at the beginning, the pre-processor replaces every occurrence of identifier in source code
by string. There are different forms of macro substitution:
Simple macro substitution
Argumented macro substitution
Nested macro substitution
Simple Macro Substitution
Eg:
The pre-processor defines more complex and more useful form of replacement
Syntax:
No space between macro identifier & left parenthesis. The identifiers f1, f2,…., fn are formal macro arguments. Only difference
is that subsequent occurrence of macro with argument is known as macro call. When a macro is called, the pre-processor
substitutes the string replacing the formal parenthesis with actual. Eg:
#define CUBE(x) (x*x*x)
volume= CUBE(side);
volume= side*side*side;
For Example
#include <stdio.h>
#include <conio.h>
int main()
{
int radius;
float c;
printf("Enter the radius of circle\n");
scanf("%d", &radius);
c = circumference(radius);
Nesting of Macro
#define SQUARE(x) (x*x)
5
MODULE 1 CS100 COMPUTER PROGRAMMING
The files are included using the directive followed by „include‟ i.e.
The character set can be used to form words, numbers & expression. It consists of upper
& lower case alphabets, digits, special character and white space. The alphabets & digits are together called alphanumeric
character.
i) Alphabets
A B…. . Z a …. z
ii) Digits
0 1 2 …… 9
! @ # $ % ^ & * ( ) _
+ | \ { } [ ] “ : ‘ ;
? < > / . ,
Blank Space
New line
Carriage return
Form Feed
Horizontal tab
6
MODULE 1 CS100 COMPUTER PROGRAMMING
Vertical tab
VII C Tokens
The smallest individual units in C are known as tokens. They are of 6 types:
Keywords
Constants
Identifiers
String
Special symbols
Operators
Every C word is either classified as keywords and identifiers. Keywords are the basic building block for program statements.
They have a certain & pre-defined meaning that can‘t be changed and must be written in lowercase. These keywords cannot be
used as identifiers in the program
Do If Static While
In C, the names of the variables, functions and arrays and various other user – defined items are called identifiers. The first
character of an identifier must be a letter or an underscore and subsequent characters must be either letter, digits or underscore.
Both upper case and lower case letters are permitted.
7
MODULE 1 CS100 COMPUTER PROGRAMMING
Must not contain white space.
C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage
for the variable and define the type of data that will be held in the location.
int - data type : int is used to define integer numbers. Integers are whole numbers with a
range of values supported by a particular machine. The size of integer value is limited to the range -32768 to 32767. A signed
integer uses one bit for sign and 15 bits for the magnitude of the number.
Eg: {
int Count;
Count = 5;
}
long int-data type: long integers require twice the same in memory than ordinary integers.Long integers could occupy
4 bytes of memory. Long integer can be declared as:
long int a,b,c;
short int-data type: short integer need less space in memory and thus help to speed up the program execution. short int
variables are declared as:
short int a,b,c;
Integers signed and unsigned:-If the value stored in an integer variable will always be
+ve ,in such situation we can declare the variable as :
8
MODULE 1 CS100 COMPUTER PROGRAMMING
float - data type : float is used to define floating point numbers. A float occupies 4 bytes in memory and range from -
3.4e38 to 3.4e38.Floating point numbers are stored in 32 bits, with 6 digits of precision.
Eg:
{
float Miles;
Miles = 5.6;
}
double - data type: double is used to define BIG floating point numbers. It reserves twice the storage for the number.
When the accuracy provided by a float number is not
sufficient, the type double can be used to define the number a double data type number. It uses 64 bits giving a precision of 14
digits. These are known as double precision numbers.
Eg:
{
double Atoms;
Atoms = 2500000;
}
char - data type : char defines characters. The char type will generally require only 1 byte of internal storage. Each
char type has an equivalent integer interpretation, so it is a special kind of short integer.
Eg:
{
char Letter;
Letter = 'x';
}
character signed and unsigned:-There are signed and unsigned characters both occupying one byte each but having
different range. A signed char is same as ordinary char and has a range from -128 to 127 where as an unsigned char has a range
from 0 to 255.
9
MODULE 1 CS100 COMPUTER PROGRAMMING
Type definition
Enumerated data type
Structure
Union
1. Type definition: allows users to define an identifier that would represent an existing data type.
Syntax:-
integer a,b,c;
2. Enumerated data type: is used to declare variables that can have one of the values enclosed within the braces. Enumerated
which provides a way for attaching names to numbers. An identifier can be declared as enumerated using the keyword
data type,
enum.
Syntax:
The enum keyword automatically enumerates a list of words by assigning values 0, 1, 2, 3…. and so on. Compiler assign integer
digits beginning with 0 to all the enumeration constant . ie,mon=0,tue=1,wed=2 and so on.
The automatic assignment can be over hidden by assigning values explicitly to the enumerated constants.
10
MODULE 1 CS100 COMPUTER PROGRAMMING
Array
Functions
Pointers
common characteristic. It is a group of related data items which shares
1. Array is the processing of multiple data items that have
a common name and all data items are same data type.
Syntax:-
datatype array-name[size];
Eg:-int a[10];
a is an integer array which can store 10 integers. The index of an array always starts with 0.
12 3 4 5 6
2. Function is a self-contained program that carries out some specific, well-defined task. Every c program consists of one or
more functions. One of these functions must be called main().Program execution will always begin by carrying out the
instructions in main. Functions are of two types:
Library functions
3 Pointer is a variable which contains address of another variable.A pointer enables to access a variable that is defined outside
the function. Pointers reduce the length and complexity of a program. Pointers increase the execution speed.
1. CONST KEYWORD:
Constants are also like normal variables. But, only difference is, their values can’t be modified by the program once they are
defined.
They refer to fixed values. They are also called as literals.
They may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Eg:
2. VOLATILE KEYWORD:
When a variable is defined as volatile, the program may not change the value of the variable explicitly.
11
MODULE 1 CS100 COMPUTER PROGRAMMING
But, these variable values might keep on changing without any explicit assignment by the program. These types of qualifiers are
called volatile.
For example, if global variable’s address is passed to clock routine of the operating system to store the system time, the value in
this address keep on changing without any assignment by the program. These variables are named as volatile variable.
Syntax:
volatile data_type variable_name; (or) volatile data_type *variable_name;
X Constants
Constants are fixed values that do not change during expression
Integer Constants
It refers to a sequence of digits. They are of 3 types : decimal integer, octal integer and octal integer
Decimal Integer
It consist of set of digit 0 to 9 preceded by an optional – or + sign. Space, comma, & non-digits characters are not permitted
between digits.
Eg:
123 -123 0 +78 6532 » legal
12
MODULE 1 CS100 COMPUTER PROGRAMMING
Eg:
0X2, 0x9F
u : Unsigned integer
l : Long integer
Mantissa e exponent
Mantissa : is either real number expressed in decimal notation or integer.
a……..z » 097……….122
A…….Z » 065……….090
Since each character constant represent an integer value, it is possible to perform arithmetic operations on character constants.
String Constants
A string constant is a sequence of character enclosed in double quotes. The character may be letter, number, special character &
blank space. It does not have an equivalent integer. Further a single character string constant does not have an equivalent integer
value while a character has an integer value. Each string constant always ends with a special character ‘\0‘. This character acts as
a string terminator. The string of character used in a string constant is always stored in an adjacent memory location.
C supports some back slash character constants that are used in output functions like printf. Certain nonprinting characters, as
well as the back slash(\) and the apostrophe(‗), can be expressed in terms of escape sequences. An escape sequence always
begins with a backward slash and is followed by one or more special characters.
13
MODULE 1 CS100 COMPUTER PROGRAMMING
\b - back space
\t - horizontal tab
\0 - Null
\v - Vertical Tab
\r - Carriage Return
\f - Form feed
\\ - Backslash
\? - Question mark
Each one of these represents one character, although they consists two characters. These combinations are called escape
sequences.
XI Variable
Variables are data name that may be used to store data value. They take different value at different time of execution. The
variable name will be chosen by the programmer.
14
MODULE 1 CS100 COMPUTER PROGRAMMING
After designing suitable variable name, we must declare them to compiler. The variable must be declared before using in
program.
Need of declaration:
It tell the compiler what the variable name is
It specifies what type of data variable will hold
Variables can be declared at the start of any block of code, but most are found at the start of each function.
Syntax:
Data type must be a valid data type and variable list may consist of one or more identifier names separated by commas. Here are
some declarations
Eg:
double sine,cosine;
Variable can be declared in three places, inside functions, in the definition of function parameters, and outside of all functions.
These positions are corresponding to local variables, formal parameters and global variables respectively.
Eg:
int i;
i=5;
or
int i=5;
Multiple declaration : int i=0,j=1;
XII Expression
Expression is a statement that has a value. It is a combination of values, constants, variables, operators and functions arranged as
per syntax of language. Every expression consists of at-least one operand and can have one or more operators. The operands are
15
MODULE 1 CS100 COMPUTER PROGRAMMING
values and operators are symbols that represent particular action. All variables in expression must have assigned value before
evaluation attempted. The expression are evaluated using the assignment operator.
Syntax:
Variable_name = expression;
Eg:
i=i+1;
c=a+b;
f=3;
Expression can also represent logical conditions that are either true or false. In C, the conditions true & false are represented by
integer values 1 & 0.
Type conversion in expression
When a constant & variable are of different type in an expression, they all are converted to same type. The compiler converts all
operands upto the type of largest operand called type promotion i.e all char & int vales are automatically evaluated as int. This is
called integral promotion.
XIII Statements
A statement causes the computer to carry out some actions. There are mainly three class of statements:
Expression
statements
Compound
statements
Control statements
Expression Statements
The expression statement consists of an expression followed by semicolon. Its execution causes the expression to be evaluated.
Eg:
a=3;
c=a+b;
Compound Statements
A compound statement consists of several individual statements enclosed within a pair of braces { }. Each individual statement
may be expression statement, compound statement or control statement. It does not end with a semicolon and can embed
statements within other statements.
Eg:
{
pi=3.14;
c=2*pi*r;
area=pi*r*r;
}
Control Statements
The control statements are used to create special program feature such as logical test, loop and branches.
It is the name that substitutes for a sequence of character. The character may be a numeric, a character or string constant i.e a
symbolic constant allow name to appear in place of a numeric constant, a character or a string. When the program is compiled,
each occurrence of symbolic constant will be replaced by its corresponding character sequence.They are defined at beginning of a
program.
Syntax:
16
MODULE 1 CS100 COMPUTER PROGRAMMING
Where name represents symbolic name, written in uppercase letter & text does not end with semicolon.
Eg:
# define TRUE 1
XV Operators
C is very rich in built – in – operators. It places more significance on operators than do most other computer languages. C
includes a large number of operators, which fall in several different categories.
1. Arithmetic Operator
2. Logical Operator
6. Conditional
7. Relational
8. Assignment
In addition to this classification, operators can also be designated as unary, binary or ternary depending on whether they operate
on one, two or three operators respectively. The data items that operators act upon are called operands.
Arithmetic Operators
There are four arithmetic operators in C. They are
Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
17
MODULE 1 CS100 COMPUTER PROGRAMMING
The operands acted up on by arithmetic operators must represent numeric values. Thus the operands can be integer quantities,
floating point quantities or character. The division operator(/) requires the second operand be non zero, though the operand needs
the integers.
Increment and Decrement Operators
C offers two special operators ++ and – called increment and decrement operators respectively. These are unary operators since
they operate on only one operand. The operand has to be variable, not a constant. Thus the expression a++ is valid where as 5++
is not. The operator ++ adds 1 to the operand while -- subtracts 1. ++a and a++ mean the same thing when they are used alone in
statements. But they behave differently when they are used in expressions on the right hand side of an assignment statement.
x=100;
y=++x;
If we rewrite it as,
x=100
y=x++
A prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left. On the other hand, a postfix
operator first assigns the value to the variable on left and then increments the operand.
Modulo Division Operator
C provides one more arithmetic operator % called modulo division operator. This operator yields the remainder of an integer
division. We cannot use it on floating point numbers. Consider the expression 6/4, the result is one. To find the remainder,
modulo division operator is used, 6%4. Note that 6%4 yields 2 whereas 4%6 4. This operator works only with ints and chars and
not on floats or doubles.
Relational Operator
Relational operators refer to the relationships that values can have with one another. They are used to compare two operands to
see whether they are equal to each other, unequal or whether one is greater than other. The value of the relational expression is
either one or zero. It is one if the specified relation is true, zero if the relation is false. The following figure shows these operators
along with their meanings.
Relational expression are used in decision statements such as if and while to decide the course of action of a running program.
18
MODULE 1 CS100 COMPUTER PROGRAMMING
Logical Operators
Logical operators deals with the ways the relationships can be connected. C has the following three logical operators
Operator Purpose
|| logical or
! logical not
The logical operators && and || are used when we want to test more than one condition and make decision
An example is
Truth table for the logical operators is shown here using 1 and 0.
P Q P&&Q P||Q !P
0 0 0 0 1
1 0 0 1 0
0 1 0 1 1
1 1 1 1 0
Conditional Operator
Simple conditional operator can be carried out with the conditional operators (? And :). An expression that makes use of the
conditional operator is called a conditional expression. The conditional operators, ? and : are sometimes called ternary operators
since they take three operands. This general form is
Syntax:
This form says that if expression 1 is true then the value returned will be expression 2 otherwise the value returned will be
expression 3. This expression can be written in place of traditional if statement.
Example
y=(x<5?3:4);
19
MODULE 1 CS100 COMPUTER PROGRAMMING
Assignment Operators
The assignment operators are used to assign a value to the variable and is represented by equal to (=) sign.
Syntax:
identifier = expression;
Where identifier represents a variable and expression represents a constant, a variable or an arithmetic expression.
C has some operators, which allow abbreviation of certain types of arithmetic assignment statements. These operations are
usually very efficient. They can be combined with another expression.
Versions where the operator occurs before the variable name change the value of the variable before evaluating the expression, so
These can cause confusion if you try to do too many things on one command line. You are recommended to restrict your use of
++ and -- to ensure that your programs stay readable.
Another shorthand notation is listed below
i += 10; i=i+10;
i *= 10; i=i*10;
i -= 10; i=i-10;
i /= 10; i=i/10;
Bitwise Operators
C has distinction of supporting special operators known as bit wise operators for manipulation of data at bit level. These
operators are used for testing the bits or shifting from left to right. Bitwise operators may not be applied to float and double.
Bitwise Operators
Like other operators bitwise operators have rules of precedence and associativity that determine how expressions involved them
are evaluated.
One's Complement Operator: ~
20
MODULE 1 CS100 COMPUTER PROGRAMMING
The one's complement operator, sometimes called the "bitwise complement" or "bitwise NOT" operator, produces the bitwise
one's complement of its operand. The operand must be of integral type. This operator performs usual arithmetic conversions; the
result has the type of the operand after conversion.
x ~x
0 1
1 0
In the following example, the new value assigned to y is the one's complement of the original unsigned short value:
Example of the one's complement operator
unsigned short y = 0xAAAA; // value of y is 0xAAAA
y = ~y;
// value of y is 0x5555
Bitwise Left Shift and Right Shift Operators: <<, >>
The bitwise shift operators shift their first operand left (<<) or right (>>) by the number of positions the second operand specifies.
In the following example, the right shift operator moves the data bits two positions to the right, thus changing the value of
nNumA:
nNumA >> 2; //
ending value is 2
Bitwise-AND Operator: &
The bitwise-AND operator (&) compares each bit of its first operand to the corresponding bit of its second operand. If both bits
are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
x y x&y
0 0 0
0 1 0
1 0 0
1 1 1
In the following example, the bitwise-AND operator (&) compares the bits of two integers, nNumA and nNumB:
// nNumC is now 1
Bitwise-Exclusive-OR Operator: ^
The bitwise-exclusive-OR operator (^) compares each bit of its first operand to the corresponding bit of its second operand. If one
bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
x y x^y
0 0 0
0 1 1
1 0 1
21
MODULE 1 CS100 COMPUTER PROGRAMMING
1 1 0
In the following example, the bitwise-exclusive-OR operator (^) compares the bits of two integers, nNumA and nNumB:
x Y x|y
0 0 0
0 1 1
1 0 1
1 1 1
In the following example, the bitwise-inclusive-OR operator (|) compares the bits of two integers, nNumA and nNumB:
C Operator Precedence
22
MODULE 1 CS100 COMPUTER PROGRAMMING
An input and output function can be accessed from anywhere within a program simply by writing the function name, followed by
a list of arguments enclosed in parenthesis.
Output Functions
printf()
The printf() function prints output to STDOUT, according to format and other arguments passed to printf(). The string format
consists of two types of items - characters that will be printed to the screen, and format commands that define how the other
arguments to printf() are displayed
Code Format
23
MODULE 1 CS100 COMPUTER PROGRAMMING
Example:
char name[20] = "Bob";
int age = 21;
printf( "Hello %s, you are %d years old\n", name, age );
24
MODULE 1 CS100 COMPUTER PROGRAMMING
puts():-
. In puts() function, we cannot pass more than one argument. So it can display one string at a time.
Eg:-
putchar(): putchar is a function in the C programming language that writes a single character to the standard output stream,
stdout. Its prototype is as follows:
syntax:
eg:-putchar( c);
Input functions
scanf()
scanf is a function that reads data with specified format from a given string stream source. The scanf function is found in C, in
which it reads input for numbers and other data-types from standard input.
Syntax
#include <stdio.h>
main()
{
char name[40];
int rollno;
char grade;
scanf("%s %d %f", name, &rollno, &grade);
}
A sample data input could be - Sanjay 12345 A
The following data input is incorrect, and will give error - Sanjay Kumar 12345 A
25
MODULE 1 CS100 COMPUTER PROGRAMMING
Note: The variable name being a string (an array of characters) is not preceded by &, but the numerical variables rollno and grade
are preceded by &. This is because, in case of an array type variable, the variable name itself represents its address in the
memory. Also note that while providing data values they must be separated by whitespace character s blank space, tab space, new
line character (enter key), etc. which act as de-limiters of individual data items.
Avoid using a new line character (i.e. enter key) to de-limit input values as it can create problems when one or more of the data
items is a single character. For instance, in this example, if you typed Sanjay, then pressed enter key, then typed 12345, pressed
enter key, and then typed A and pressed enter key, then while name and rollno would get read correctly, grade will take in the \n
character (corresponding to the enter key following value 12345) and so A will not get read.
The format specifier can be additionally pre-fixed with a number to indicate the width of the associated data field. See example
below:
#include <stdio.h>
main()
{
int x, y, z;
float u, v, w;
char a, b, c;
scanf("%3d %4f %c", &x, &u, &c);
}
If the data items provided are 105 40.36 A, then the variables get values x = 105, u = 40.3, c = 6. Note that the character A is
ignored.This is because the field width for u is 4 which can accommodate 40.3 (the decimal point is also counted). The next
character in the input steam is character 6, which gets assigned to c and A is left un-read.
printf(): The printf function is used to output data onto the standard output device. In general, the printf function is written as
where the <control string> refers to a string containing required formatting information as in scanf, and arg1, arg2, ..., argn are
individual data variables whose values are to be printed. However, unlike scanf, these data variable names are not preceded by
the & symbol. This is because printf is expected to only output the values of these variables and not their addresses.
Examples:
#include <stdio.h>
main()
{
printf("Our first program in C\n");
}
Output: Our first program in C
#include <stdio.h>
main()
{
int n;
n = 25;
printf("The value of n = %d\n", n); //note the usage of format specifier %d
26
MODULE 1 CS100 COMPUTER PROGRAMMING
}
Output: The value of n = 25
#include <stdio.h>
main()
int n;
printf("Integer read is %d\n", n); //note the absence of & symbol before variable n
#include <stdio.h>
main()
{
float x = 2.0;
int y = 4;
char c = 'A';
printf("%f%d%c\n", x, y, c);
}
Output: 2.0000004A
As you notice, the printf statement prints the data values x, y, and c all sticking to each other, followed by a blank line (due to \n
at the end of the control string). For clarity of data output, you may separate the format specifiers with blank space or comma (,).
So, a better way of writing would be -
printf("%f %d %c\n",x,y,z);
We mentioned earlier that you can also pre-fix the format specifier character with a numeric qualifier to indicate the width of
field (precision) to be printed. let us look at some example usage of this.
#include <stdio.h>
main()
float x = 453.7869;
int y = 243;
char c = 'B';
27
MODULE 1 CS100 COMPUTER PROGRAMMING
Note that due to the precision specification the floating point variable x has been rounded to fit the specified field width. Also,
note that the field width of 2 specified for y is too small as compared to the specified field width supported for integer data items
(which is normally 8 digits). When such a precision is specified, it is ignored and the entire integer value is displayed.
#include <stdio.h>
int main()
{
int number;
Output
Enter an Integer:8
8 is even
Output
Enter a character: G
ASCII value of G = 71
28
MODULE 1 CS100 COMPUTER PROGRAMMING
Decision control statement is deciding what actions to take and looping is deciding how many times to take a certain action.
In decision control statements (if-else and nested if), group of statements are executed when condition is true. If condition is
false, then else part statements are executed.
For these situation C provides decision making statements also know as control statements. C has following control statements:
If statement
Switch statement
Conditional operator
goto statement
1. if statement
it is a powerful decision making statement and is used to control the flow of execution of statements. It is basically a two way
decision statement and is used in conjunction with an expression. It takes the following form:
if (Text expression)
It allows the computer to evaluate the expression first and then, depending on whether the value of the expression is ‘true’ (or
non zero) or ‘false’ (zero) , it transfer the control to a particular statement. The if statement may be implemented in different
forms depending on the complexity of conditions to be tested. The different forms are:
Simple if statement
if …..else statement.
Nested if …..else statement.
else if ladder.
Simple if statement
if (testExpression)
{
Statements;
}
29
MODULE 1 CS100 COMPUTER PROGRAMMING
If test expression is evaluated to true (nonzero), statements inside the body of if is executed.
If test expression is evaluated to false (0), statements inside the body of if is skipped.
To learn more on when test expression is evaluated to nonzero (true) and 0 (false), check out relational and logical operators.
Flowchart of if statement
For example,
if (x < 0)
{
x = 0;
}
The braces indicate a block of statements. If there is only one statement, the braces may be omitted; however, it is good style to
always include the braces
In “if” control statement, respective block of code is executed when condition is true.
#include<stdio.h>
int main()
{
int m=40,n=40;
if (m == n)
{
printf("m and n are equal");
}
}
Output:
30
MODULE 1 CS100 COMPUTER PROGRAMMING
2. if-else statement
The if-else statement is used to carry out a logical test and then take one of two possible actions depending on the
outcome of the test (ie, whether the outcome is true or false). Here, we have two block of statements. If condition results
true then if block gets execution otherwise statements in else block executes. else cannot exist without if statement. In
this tutorial, I have covered else-if statements too.
Syntax
if (expression)
{
Block of statements;
}
else
{
Block of statements;
}
Flow Chart
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
if( (c>='a' && c<='z') || (c>='A' && c<='Z'))
printf("%c is an alphabet.",c);
else
31
MODULE 1 CS100 COMPUTER PROGRAMMING
Output
Enter a character: *
* is not an alphabet
#include <stdio.h>
int main()
{
int year;
Output 1
Output 2
3. Nested if statement
Nested if else statement provides us the facility to write more than one statement in a single program.
if(test_condition1)
{
if(test_condition2)
{
Statements1 Or True Block;
}
else
{
32
MODULE 1 CS100 COMPUTER PROGRAMMING
if (n1>=n2)
{
if(n1>=n3)
printf("%d is the largest number.", n1);
else
printf("%d is the largest number.", n3);
}
else
{
if(n2>=n3)
printf("%d is the largest number.", n2);
else
printf("%d is the largest number.",n3);
}
}
Output
Enter three numbers: 4
3
5
5 is the largest number.
4. 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.
When using if...else if..else statements, there are few points to keep in mind −
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
33
MODULE 1 CS100 COMPUTER PROGRAMMING
Syntax
if(boolean_expression 1) {
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2) {
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3) {
/* Executes when the boolean expression 3 is true */
}
else {
/* executes when the none of the above condition is true */
}
5. 'switch' Statements
The alternative of nested 'if' statement is called 'switch' statement, which has different statement blocks for different cases.
'switch' statement tries to match evaluated value of an expression against different cases. Syntax of 'switch' statement is as
follows.
switch(expression)
{
case value 1:
statement block 1;
break;
case value 2:
statement block 2;
break;
...
...
case value n:
statement block n;
break;
default:
default statement block;
break;
}
The expression 'expression' is evaluated first and the value is checked with different case values (value 1, value 2, ... etc.
If one of the case values matches the result of expression, then respective statement block is executed. If none is matched, then
the statement block of 'default' case is executed.
If break keyword is omitted, all the the statements after that will be executed even if the corresponding case values do not match
the value of expression.
This is called a 'fall through' statement. For example, if 'break' is omitted and say, case 'value 1' is matched, then after execution
of 'statement block 1' the code will execute statement block 2, 3 and so on until a 'break' statement is reached.
The values of case label must be unique, else complier will throw error.
34
MODULE 1 CS100 COMPUTER PROGRAMMING
The values of case should be an integral constant (integer or character). If any variable is specified as part of a case, compiler will
throw error, but a 'const' variable is allowed.
The 'default' case is optional and it can be placed anywhere in the switch block.
'switch' statements can be nested; that means you can have another 'switch' statement as part of a statement block associated with
a case.
The statement block of a case is optional and it can be shared by more than one cases.
Example of 'switch' Statement
1. program to check if a number is even or odd using switch statement as given below.
#include <stdio.h>
int main(void) {
int i = 5;
switch(i % 2)
{
case 0:
printf("%d is even number", i);
break;
case 1:
printf("%d is odd number", i);
break;
// We do not need default case here as there can only be two cases 0 or 1.
}
return 0;
}
Output:
5 is odd number
6. goto statement in C
The goto statement is used to alter the normal sequence of program execution by transferring control to some other part
of the program unconditionally.
goto label;
where the label is an identifier that is used to label the target statement to which the control is transferred. Control may be
transferred to anywhere within the current function. The target statement must be labeled, and a colon must follow the label.
Thus the target statement will appear as
label:statement;
Each labeled statement within the function must have a unique label, i.e., no two statement can have the same label.
Syntax
goto label;
..
.
label: statement;
35
MODULE 1 CS100 COMPUTER PROGRAMMING
Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto
statement.
Flow Diagram
Example
#include <stdio.h>
int main () {
value of a: 11
value of a: 12
value of a: 13
value of a: 14
II. LOOP
1. while loop
A while loop in C programming repeatedly executes a target statement as long as a given condition is true.
36
MODULE 1 CS100 COMPUTER PROGRAMMING
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, the program control passes to the line immediately following the loop.
Flow Diagram
Here, the key point to note is that a while loop might not execute at all. 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.
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 15 ) {
printf("value of a: %d\n", a);
a++;
}
}
Output
value of a: 10
value of a: 11
37
MODULE 1 CS100 COMPUTER PROGRAMMING
value of a: 12
value of a: 13
value of a: 14
while(n!= 0)
{
n = n/10;
count++;
}
The integer entered by the user is stored in variable n. Then the while loop is iterated until the test expression n != 0 is evaluated to
0 (false).
After first iteration, the value of n will be 345 and the count is incremented to 1.
After second iteration, the value of n will be 34 and the count is incremented to 2.
After third iteration, the value of n will be 3 and the count is incremented to 3.
After fourth iteration, the value of n will be 0 and the count is incremented to 4.
Then the test expression is evaluated to false and the loop terminates.
In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number itself. For example:
#include <stdio.h>
int main()
{
int number, originalNumber, remainder, result = 0;
38
MODULE 1 CS100 COMPUTER PROGRAMMING
remainder = originalNumber%10;
result =result+ remainder*remainder*remainder;
originalNumber = originalNumber/10;
}
if(result == number)
printf("%d is an Armstrong number.",number);
else
printf("%d is not an Armstrong number.",number);
return 0;
}
Output
2. 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
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 the 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.
39
MODULE 1 CS100 COMPUTER PROGRAMMING
Flow Diagram
Example
#include <stdio.h>
int main ()
{
int a;
/* for loop execution */
for( a = 10; a < 15; a = a + 1 )
{
Example
// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
40
MODULE 1 CS100 COMPUTER PROGRAMMING
Output
Explanation
The value entered by the user is stored in variable num. Suppose, the user entered 10.
The count is initialized to 1 and the test expression is evaluated. Since, the test expression count <= num (1 less than or equal to 10)
is true, the body of for loop is executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and count will equal to 2. Again, the test expression is evaluated. Since, 2 is also
less than 10, the test expression is evaluated to true and the body of for loop is executed. Now, the sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11, the test expression is evaluated to 0 (false) as 11 is not less than or equal to 10. Therefore, the loop
terminates and next, the total sum is printed.
Example
#include <stdio.h>
int main()
{
int n, i, flag = 0;
41
MODULE 1 CS100 COMPUTER PROGRAMMING
else
printf("%d is not a prime number.",n);
}
Output
If the for loop terminates when the test expression of loop i <= n/2 is false, the entered number is a prime number. The value of flag
is equal to 0 in this case.
If the loop terminates because of break statement inside the if statement, the entered number is a nonprime number. The value of
flag is 1 in this case.
3. do-while loop
Do-while loop is an exit controlled loop i.e. the condition is checked at the end of loop.
It means the statements inside do-while loop are executed at least once even if the condition is false.
Do-while loop is an variant of while loop. In order to exit a do-while loop either the condition must be false or we should use
break statement.
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its
condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it 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 executes 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 executes again. This process
repeats until the given condition becomes false.
Flow Diagram
42
MODULE 1 CS100 COMPUTER PROGRAMMING
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 15 );
}
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
43
MODULE 1 CS100 COMPUTER PROGRAMMING
Output
Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control directly jumps to
the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body for the current iteration.
for (int j=0; j<=8; j++)
{
if (j==4)
{
continue;
}
01235678
When j’s value is 4, the program encountered a continue statement, which makes it to jump at the beginning of for loop for next
iteration, skipping the statements for current iteration.
Break Statement
The break statement terminates the loop (for, while and do...while loop) immediately when it is encountered and the
The break statement is used with decision making statement such as if...else.
44
MODULE 1 CS100 COMPUTER PROGRAMMING
45