0% found this document useful (0 votes)
45 views

Computer Is A Programmable Machine That Receives Input, Store & Manipulate Data & Provides Output in Useful Format. The

This document provides an introduction to computer programming and the C programming language. It discusses the steps involved in computer programming like understanding the problem, developing logic, coding, and running/testing the program. It also covers features of a good program like integrity, clarity, simplicity, and efficiency. The document then introduces C programming, describing its features and the typical structure of a C program which includes header files, global declarations, the main function, comments, and user-defined functions. Finally, it discusses C preprocessor directives like #define, #include, and #ifdef which are used for macro substitution, file inclusion, and compiler control.

Uploaded by

roshin_sharo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Computer Is A Programmable Machine That Receives Input, Store & Manipulate Data & Provides Output in Useful Format. The

This document provides an introduction to computer programming and the C programming language. It discusses the steps involved in computer programming like understanding the problem, developing logic, coding, and running/testing the program. It also covers features of a good program like integrity, clarity, simplicity, and efficiency. The document then introduces C programming, describing its features and the typical structure of a C program which includes header files, global declarations, the main function, comments, and user-defined functions. Finally, it discusses C preprocessor directives like #define, #include, and #ifdef which are used for macro substitution, file inclusion, and compiler control.

Uploaded by

roshin_sharo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

MODULE 1 CS100 COMPUTER PROGRAMMING

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.

I Steps in Computer Programming


Computer programming is the art and skill of creating a computer program, a defined set of instructions in source code that a
computer can execute. Creating programs has elements of art, science, mathematics, and engineering.
Creating a computer program involves:

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

3) Develop logic to work out the result

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

6) Store the program

7) Run the program and get the result.

8) If expected result is not getting, modify the logic or program depending up on the situation.

These steps are collectively known as computer programming.

II Features of a good program


1. Integrity:-

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

i) C is structured programming language


ii) C is rich in built in functions
iii) C supports assembly language features
iv) C is portable
v) It has the ability to extend itself
vi) It is case sensitive programming language

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

Include header file section

Global declaration section

Main() Function name

/*Comments*/

Declaration part

Executable part

User defined functions

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.

Consider a simple program in c

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

Syntax: #include <file_name>


Header file inclusion The source code of the file “file_name” is included in the main program at the specified place.

Syntax: #ifdef, #endif, #if, #else, #ifndef


Conditional Set of commands are included or excluded in source program before compilation with respect to the
compilation condition.

Syntax: #undef, #pragma


#undef is used to undefine a defined macro variable. #Pragma is used to call a function before and after
Other directives main function in a C program.

Mainly 3 pre-processor directives:

 Macro substitution directives



 File inclusion directives

 Compiler control directives

i) Macro Substitution Directives
It is a process where an identifier in a program is replaced by a pre-defined string composed of one or more tokens.
The pre-processor accomplishes this task under the direction of “#define‟ statement. This statement is known as macro
definition or macro.
Syntax:

4
MODULE 1 CS100 COMPUTER PROGRAMMING

#define identifier string

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

Simple string replacement is commonly used to define constants. Eg:


#define COUNT 100 #define FALSE 0


A macro definition can include more than a simple constant value.

It can include an expression as well

Eg:

#define AREA 5*12.46


 Macro with Argument

The pre-processor defines more complex and more useful form of replacement
Syntax:

#define identifier(f1, f2, ……, fn) string

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>

#define circumference(r) (2*3.141*(r))

int main()
{
int radius;
float c;
printf("Enter the radius of circle\n");
scanf("%d", &radius);

c = circumference(radius);

printf("Circumference of Circle = %f", c);


}

 Nesting of Macro
#define SQUARE(x) (x*x)

5
MODULE 1 CS100 COMPUTER PROGRAMMING

#define CUBE(x) (SQUARE(x)*x)

ii) File Inclusion

The files are included using the directive followed by „include‟ i.e.

#include. The can be done in two ways:

 # include “file_name” : search for file name in whole system

 #include <File_name> : serch for file name only in library functions



iii) Compiler Control Directives

#define - define macro

#undefine - undefine macro

#include - include file

#ifdef - test for macro definition

#endif - end if # ifdef

#ifndef - test whether a macro is not defined

#if - test compile time


#else

VI. The Character Set

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

iii) Special Symbols

! @ # $ % ^ & * ( ) _

+ | \ { } [ ] “ : ‘ ;

? < > / . ,

iv) White space

  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

Identifiers and Keywords

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

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

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.

Rules for identifiers


 First character must be an alphabet or underscore

 Must contain of only letters, digits or underscore.

 Cannot use a keyword.

7
MODULE 1 CS100 COMPUTER PROGRAMMING


Must not contain white space.

Some examples of identifiers are

Abc, tax_rate_temperature, Place, TABLE

VIII Data Types

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.

C supports Three classes of data types: They are


1. Primary data type
2. User-defined data type
3. Derived data type
1. Primary data type

Basic primary Data Types available in are

Data Type Description Typical Memory Requirements

Int integer quantity 2 bytes or one word

Float floating point number 1 word(4 bytes)

Double double precision number 2 words(8 bytes)

Char single character 1 byte

Void Without any type

 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

unsigned int Range of values: 0 to 65535

 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

2. User defined data type:-


The data types defined by the user .The are

 Type definition
 Enumerated data type
 Structure
 Union
 
1. Type definition: allows users to define an identifier that would represent an existing data type.

Syntax:-

typedef type identifier;

Eg:- typedef int integer;

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:

enum identifier {value1, value2,…….,valuen};


Eg:-enum day{mon,tue,wed,…….,sun}

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.

Eg:-enum digital {a=1,b};

10
MODULE 1 CS100 COMPUTER PROGRAMMING

Here a=1 and b=2.

3. Derived data type:-

 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

A[0]=12 a[1]=3 a[2]=4 …….so on

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

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

IX Data Type Qualifiers:



 Const
 Volatile

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:

const float pi=3.14159;

pi cannot be changed at a later time within the program.

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

15 750 12,000 $1000 » illegal


 
Octal Integer
It consist of any combination of digit from 0 to 7 with a leading zero
Eg:
037, 0, 0435, 0551
 
Hexa Integer
It is a sequence of digit preceded by 0X or 0x. It also include alphabets A through F representing number 10 to 15.

12
MODULE 1 CS100 COMPUTER PROGRAMMING

Eg:
0X2, 0x9F

The integer constants are appended by qualifiers such as u, l and ul to constants

u : Unsigned integer

ul : Unsigned long integer

l : Long integer

Eg: 56789U or 56789u


 
Real Constants
The numbers containing fractional part are called real constants.
Eg:
0.83, +0.95, 2.25, -215.
It can also be expressed in exponential notation:

Mantissa e exponent
Mantissa : is either real number expressed in decimal notation or integer.

Exponent: is integer number with optional ‗+‘ or ‗-‗


Eg: 2.1565 e 2» 2.1565 x 102 » 215.65

Single character constants


Single character constant contains a single character enclosed within a pair of single quote marks.
Eg: ‘5‘ ‘X‘

They have integer values knwn as ASCII value

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.

Eg: “Hello”, “1987”, “welldone”


 
Escape Sequences or Backslash Character Constants

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.

The commonly used escape sequences are listed below.

13
MODULE 1 CS100 COMPUTER PROGRAMMING

\n - stands for new line

\b - back space

\t - horizontal tab

\0 - Null

\v - Vertical Tab

\r - Carriage Return

\f - Form feed

\a - Audible Alert (bell)

\\ - Backslash

\? - Question mark

\' - Single quote

\" - Double quote

\000 - Oct Number

\xhh - Hex number

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.

Rules for constructing variable names:

 A variable name is any combination of 0 to 9 digits, alphabets and underscores.

 The first character in the variable name must be an alphabet.

 No commas or blanks all allowed within a variable name.

 No special symbol other than an underscore can be used in a variable name.


 
Variable declaration

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 variable – list;

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:

int tax, count;

float tax_rate, fahr_temp, ave;

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.

Variables are classified into three types based:



Local Variables
 Scope is within the function only
 It can‘t be accessed outside the function
 
Global Variables
 Scope is throughout the program and can be accessed from anywhere in program
 Variable is defined outside the main function

Variable initialization
Assigning value to a variable is known as variable initialization. Memory is allocated only when a variable is defined but
not during declaration.
Syntax:
Data_type variable_name = constant;

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.

XIV Symbolic Constants

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

# define name text

Where name represents symbolic name, written in uppercase letter & text does not end with semicolon.

Eg:

# define TRUE 1

# define TAXRATE 0.23

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.

Depending on the function performed, the operator can be classified as

1. Arithmetic Operator

2. Logical Operator

3. Increment and Decrement Operator

4. Bit wise Operator

5. Modulo Division 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.

Consider the following

x=100;

y=++x;

In this case, the value of X and Y would be 101.

If we rewrite it as,

x=100

y=x++

, then the value of x=101 and y=100.

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 and

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

(p<q) && (r==5)

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:

expression 1? expression 2 : expression 3

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

This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.

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.

x = a * b++; is equivalent to x = a*b; b = b+1;

Versions where the operator occurs before the variable name change the value of the variable before evaluating the expression, so

x = --i * (a+b); is equivalent to i=i-1; x = i * (a+b);

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

Short hand Equivalent

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:

Example of the bitwise right shift operator

int nNumA=8; // beginning value is 8

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:

Example of the bitwise-AND operator

int nNumA=1, nNumB=3, nNumC; // 00000001, 00000011

nNumC = nNumA & 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:

Example of the bitwise-exclusive-OR operator

int nNumA=9, nNumB=3, nNumC; // 00001001, 00000011

nNumC = nNumA ^ nNumB; // nNumC is now 10: 00001010


 
Bitwise-Inclusive-OR Operator: ||
The bitwise-inclusive-OR operator (||) compares each bit of its first operand to the corresponding bit of its second operand. If
either 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
1 1 1

In the following example, the bitwise-inclusive-OR operator (|) compares the bits of two integers, nNumA and nNumB:

Example of the bitwise-inclusive-OR operator

int nNumA=9, nNumB=3, nNumC; // 00001001, 00000011

nNumC = nNumA | nNumB; // nNumC is now 11: 00001011



 
Operator Precedence
The operators within C are grouped hierarchically according to their precedence (i.e., order of evaluation). Operations with a
higher precedence are carried out before operations having a lower precedence. The natural order of evaluation can be altered,
however, through the use of parentheses. Among the arithmetic operators, *,/ and % fall into one precedence group, and + and –
fall into another. The first group has a higher precedence than the second. Thus multiplication, division and remainder operations
will be carried out before addition and subtraction. Another important consideration is the order in which consecutive operations
within the same precedence group are carried out. This is known as associativity.

C Operator Precedence

22
MODULE 1 CS100 COMPUTER PROGRAMMING

XVII Data Input and Output Functions

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

OUTPUT: Hello Bob, you are 21 years old

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

puts ( "Welcome to codesnipr.....");


Output is :welcome to codesnipr.....


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:

int putchar (int character);

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

int scanf(const char *format, ...);


Eg:-
#include <stdio.h>
void main()
{
int n;
while (scanf("%d", & n))
printf("%d\n", n);
return 0;
}
 
gets()
The gets() function shall read bytes from the standard input stream, stdin, into the array pointed to by s, until a <newline> is read
or an end-of-file condition is encountered.
 getchar()
The getchar() function is used to read a single character from the keyboard.
key=getchar();

Let us look at an example to understand the format specification better

#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

printf(<control string>, arg1, arg2, . . . , argn);

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("Give an integer: ");

scanf("%d",&n); //note usage of & before n

fflush(stdin); //flushes the standard input buffer

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, c); or

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

printf("%6.2f %2d %c\n", x, y, c);

Output: 453.79 243 B

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.

Program to Check Odd or Even Using Conditional Operator

#include <stdio.h>
int main()
{
int number;

printf("Enter an integer: ");


scanf("%d", &number);

(number % 2 == 0) ? printf("%d is even.", number) : printf("%d is odd.", number);

Output
Enter an Integer:8
8 is even

C Program to Find ASCII Value of a Character


#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");

// Reads character input from the user


scanf("%c", &c);

// %d displays the integer value of a character


// %c displays the actual character
printf("ASCII value of %c = %d", c, c);
}

Output

Enter a character: G
ASCII value of G = 71

28
MODULE 1 CS100 COMPUTER PROGRAMMING

flow control Statement

XVIII Control Statement

C provides two sytles of flow control:

 Decision control statement


 Looping

Decision control statement is deciding what actions to take and looping is deciding how many times to take a certain action.

I. C – Decision Control statement

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

The if statement evaluates the test expression inside parenthesis.

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 above if statement resets x to zero if it has become negative.

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

Example program for if statement in C:

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:

m and n are equal

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

C Program to Check Whether a Character is an Alphabet or not

#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

printf("%c is not an alphabet.",c);


}

Output

Enter a character: *
* is not an alphabet

Program to Check Leap Year

#include <stdio.h>

int main()
{
int year;

printf("Enter a year: ");


scanf("%d",&year);
if((year%4 == 0)|| (( year%100 == 0)&& ( year%400 == 0)))
{
printf("%d is a leap year.", year );
}
else
printf("%d is not a leap year.", year);

Output 1

Enter a year: 1900


1900 is not a leap year.

Output 2

Enter a year: 2012


2012 is a leap year.

3. Nested if statement
Nested if else statement provides us the facility to write more than one statement in a single program.

Syntax Of Nested If Else Statement:

if(test_condition1)
{
if(test_condition2)
{
Statements1 Or True Block;

}
else
{

32
MODULE 1 CS100 COMPUTER PROGRAMMING

Statements2 Or False Block;


}
}
else {
Statement 3 or false block code for test_condition1.
}
The above syntax execution goes as follows: if test condition 1 is true than test condition 2 is evaluated. If it is true then the
statement 1 is executed. If the test condition 2 is false, statement 2 is executed. And if test condition 1 is false then statement 3 is
executed.

Program to find maximum from 3 numbers


#include <stdio.h>
int main()
{
int n1, n2, n3;

printf("Enter three numbers: ");


scanf("%d %d %d", &n1, &n2, &n3);

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

The syntax of an if...else if...else statement in C programming language is −

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.

Rules for Writing 'switch' Statements in C Language

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

 In its general form, the goto statement is written as

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

/* local variable definition */


int a = 10;
/* do loop execution */
LOOP:
if( a < 15)
{
a = a + 1;
printf("value of a: %d\n", a);
goto LOOP;
}
else
{
printf(“End of goto statement”);
}
}
When the above code is compiled and executed, it produces the following result −

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

The syntax of a while loop in C programming language is −

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

C Program to Count Number of Digits in an Integer


#include <stdio.h>
int main()
{
int count = 0,n;

printf("Enter an integer: ");


scanf("%d", &n);

while(n!= 0)
{
n = n/10;
count++;
}

printf("Number of digits: %d", count);


}
Output
Enter an integer: 3452
Number of digits: 4

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.

C Program to Check Armstrong Number

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.


Program

#include <stdio.h>
int main()
{
int number, originalNumber, remainder, result = 0;

printf("Enter a three digit integer: ");


scanf("%d", &number);
originalNumber = number;
while (originalNumber != 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

Enter a three digit integer: 371


371 is an Armstrong number.

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 syntax of a for loop in C programming language is –

for ( init; condition; increment )


{
statement(s);
}
Here is the flow of control in a 'for' loop −

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

printf("value of a: %d\n", a);


}
}
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14

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

printf("Enter a positive integer: ");


scanf("%d", &num);

// for loop terminates when n is less than count


for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
}

Output

Enter a positive integer: 10


Sum = 55

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

Program to Check Prime Number

#include <stdio.h>
int main()
{
int n, i, flag = 0;

printf("Enter a number: ");


scanf("%d",&n);
for(i=2; i<=n/2; i++)
{
// condition for nonprime number
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);

41
MODULE 1 CS100 COMPUTER PROGRAMMING

else
printf("%d is not a prime number.",n);
}

Output

Enter a positive integer: 29


29 is a prime number.

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

The syntax of a do...while loop in C programming language is −

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

Program to add numbers until user enters zero


#include <stdio.h>
int main()
{
float number, sum = 0;

// loop body is executed at least once


do
{
printf("Enter a number: ");
scanf("%f", &number);
sum =sum+ number;
}
while(number != 0.0);
printf("Sum = %f",sum);
}

43
MODULE 1 CS100 COMPUTER PROGRAMMING

Output

Enter a number: 1.5


Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70

Continue Statement In C With Example

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

printf("%d ", j);


}
Output:

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

program control resumes at the next statement following the loop.

 It can be used to terminate a case in the switch statement.

 The break statement is used with decision making statement such as if...else.

44
MODULE 1 CS100 COMPUTER PROGRAMMING

45

You might also like