0% found this document useful (0 votes)
11 views28 pages

Unit 1-1

The document provides a comprehensive overview of the C programming language, covering its history, characteristics, advantages, and disadvantages. It details the structure of a C program, data types, variable declarations, and input/output functions, along with examples. Additionally, it discusses constants, literals, and the significance of C in system programming and software development.

Uploaded by

krashan.042732
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views28 pages

Unit 1-1

The document provides a comprehensive overview of the C programming language, covering its history, characteristics, advantages, and disadvantages. It details the structure of a C program, data types, variable declarations, and input/output functions, along with examples. Additionally, it discusses constants, literals, and the significance of C in system programming and software development.

Uploaded by

krashan.042732
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

BCA 202-PROGRAMMING IN C Unit-1

C Basics: History of C, Characteristics of C, C Program Structure, data types, Enumerated


types, Variables, Defining Global Variables, Printing Out and Inputting Variables, Constants,
Arithmetic Operations, Comparison Operators, Logical Operators, Order of Precedence,
Escape sequence characters, Conditionals (The if statement, The switch statement) Looping
and Iteration (The for statement, The while statement, The do-while statement, break ,continue,
goto statements)
C is a mid-level structured oriented programming language, used in general-purpose
programming, developed by Dennis Ritchie at AT&T Bell Labs, the USA, between 1969 and
1973.
Facts about C
• C is the most widely used System Programming Language.
• In 1988, the American National Standards Institute (ANSI) had formalized the C
language.
• C was invented to write UNIX operating system.
• Linux OS, PHP, and MySQL are written in C.
• C has been written in assembly language.

Why to use C ?
Because it produces code that runs nearly as fast as code written in assembly language. Some
examples of the use of C might be:
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Data Bases
• Language Interpreters
• Utilities

Advantages of C
• C is the building block for many other programming languages.
• Programs written in C are highly portable.
• Several standard functions are there (like in-built) that can be used to develop programs.
• C programs are collections of C library functions, and it's also easy to add functions to
the C library.
• The modular structure makes code debugging, maintenance, and testing easier.

Disadvantages of C
• C does not provide Object Oriented Programming (OOP) concepts.
• C does not provide binding or wrapping up of data in a single unit.
• C does not provide Constructor and Destructor.

History of C Language
The programming languages that were developed before C language are as follows:-
Language Year Developed By
Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson

1
BCA 202-PROGRAMMING IN C Unit-1

Traditional C 1972 Dennis Ritchie


K&RC 1978 Kernighan & Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
C99 1999 Standardization Committee

Characteristics of C/ Features of C Language


5. Rich Library
Features of C are as follows: 6. Memory Management
1. Simple 7. Fast Speed
2. Machine Independent or Portable 8. Pointers
3. Mid-level programming language 9. Recursion
4. structured programming language 10. Extensible
1) Simple
It provides a structured approach (to break the problem into parts), the rich set of library
functions, data types, etc.

2) Machine Independent or Portable


c programs can be executed on different machines with some machine specific changes.

3) Mid-level programming language


C is intended to do low-level programming but it also supports the features of a high-level
language. That is why it is known as mid-level language.

4) Structured programming language


we can break the program into parts using functions. So, it is easy to understand and
modify.

5) Rich Library
C provides a lot of inbuilt functions that make the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation.

7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions
and hence the lesser overhead.

8) Pointer
We can directly interact with the memory by using the pointers. We can use pointers for
memory, structures, functions, array, etc.

9) Recursion
In C, we can call the function within the function.

10) Extensible
it can easily adopt new features.

Structure of C programming

2
BCA 202-PROGRAMMING IN C Unit-1

The structure of a C program means the specific structure to start the programming in the C
language. Without a proper structure, it becomes difficult to analyze the problem and the
solution. It also gives us a reference to write more complex programs.

Figure: Basic Structure Of C Program

C program is divided into different sections. There are six main sections to a basic c program.
The six sections are,
1. Documentation section
2. Pre-processor section/ link section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions/ sub program section

Documentation section
A set of comment lines giving the name of the program, the author and other details.
Example
/**
* File Name: Helloworld.c
* Author: Manthan Naik
* date: 09/08/2019
* description: a program to display hello world
* no input needed
*/

Link section
Provides instructions to the compiler to link functions from the system library.
Example
#include<stdio.h>
Definition section
defines all symbolic constants.
Example #define PI=3.14

3
BCA 202-PROGRAMMING IN C Unit-1

Global declaration section


• There are some variables that are used in more than one function.
• Such variables are called global variables.
• Global variables are declared in the global declaration section that is outside of all the
functions.
• Also declares all the user-defined functions.
Example
float area(float r);
int a=7;
Main() function
Every c program must contain main() function section.
int main(void)
{
int a=10;
printf(" %d", a);
return 0;
}
This section contains two parts
• Declaration part
• Executable part
These two parts must appear between the opening and closing braces ({ }).
Declaration part
Declares all the variables used in the executable part
Executable part
There is atleast one statement in the executable part.
The closing brace of main function sections is the logical end of the program.
All statements in the declaration and executable parts end with the semicolon (;).
Subprogram section
contains all user-defined functions that are called in the main function.
User-defined functions are generally placed immediately after the main function , although
they may appear in any order.
Example
int add(int a, int b)
{
return a+b;
}

Example
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
• The first line of the program #include <stdio.h> is a preprocessor command, which
tells a C compiler to include stdio.h file before going to actual compilation.
• The next line int main() is the main function where the program execution begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.

4
BCA 202-PROGRAMMING IN C Unit-1

• The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
• The next line return 0; terminates the main() function and returns the value 0.

EXECUTING A ‘C’ PROGRAM


Steps
1. Creating the program.
2. Compiling the program.
3. Linking the program with functions that are needed from the C library
4. Executing the program.
C Data Types
Data types refer to an extensive system used for declaring variables or functions of different
types before its use.
The type of a variable determines how much space it occupies in storage and how the bit pattern
stored is interpreted.
C Data Types are used to:
• Identify the type of a variable when it declared.
• Identify the type of the return value of a function.
• Identify the type of a parameter expected by a function.

ANSI C provides three types of data types:

1. Primary(Built-in) Data Types:


void, int, char, double and float.
2. Derived Data Types:
Array, References, and Pointers.
3. User Defined Data Types:
Structure, Union, and Enumeration.

5
BCA 202-PROGRAMMING IN C Unit-1

INTEGER TYPES
• Integer occupy one word of storage, and word sizes of machines vary (16 or 32 bits).
• The signed integer uses one bit for sign and 15 bits for the magnitude of the number.
• Smallest to largest.

FLOATING POINT TYPE


Floating point numbers are stored in 32-bits, with 6 digits of precision.

CHARACTER TYPE
A single character can be defined as a character (char) type data.
Characters are stored in 8 bits of internal storage.
The qualifier signed or unsigned may be explicitly applied to char.
VOID TYPE
has no values.
Used to specify the type of functions.
The type of function is said to be void when it does not return any value to the calling
function.
Play the role of a generic type, ie it can represent any of the other standard type.

Derived Data Types


C supports three derived data types:
Data Types Description
Arrays Arrays are sequences of data items having homogeneous values. They have
adjacent memory locations to store values.
References Function pointers allow referencing functions with a particular signature.

6
BCA 202-PROGRAMMING IN C Unit-1

Pointers used to access the memory and deal with their addresses.
User Defined Data Types
C allows the feature called type definition which allows programmers to define their identifier
that would represent an existing data type. There are three such types:
Data Types Description
Structure It is a package of variables of different types under a single name. This is done
to handle data efficiently. "struct" keyword is used to define a structure.
Union These allow storing various data types in the same memory location.
Programmers can define a union with different members, but only a single
member can contain a value at a given time.
Enum It consists of integral constants, and each of them is assigned with a specific
name. "enum" keyword is used to define the enumerated data type.

Variables in C
• Variable is a data name which is used to store data value .
• The value of the variable can be change during the execution.
• The rule for naming the variables is same as the naming identifier.
Rules :
1) They begin with a letter. Some systems permit underscore as the first character.
2) Upto 31 characters (ANSI)
3) Case Sensitive ie. Uppercase and lowercase are significant. A ≠ a
4) It should not be a keyword
5) White space is not allowed.

DECLARATION OF VARIABLES
Declaration does two things
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
Primary type declaration
A variable can be used to store a value of any data type.
data_type v1,v2,v3,….,vn;
v1,v2,v3,…vn are the name of the variables.
• Variables are separated by commas.
• Declaration statement end with a semicolon.
Example:
int count;
float total;
double ratio;

ASSIGNING VALUE TO VARIABLES


Variablename = constant;
Example:
n=5;
count=count+1;
datatype variable_name=constant;
Example:
int n=5;
float x=5.5;
User-defined type declaration

7
BCA 202-PROGRAMMING IN C Unit-1

1. “type definition” – allows users to define an identifier that would represent an existing data
type.
The user-defined data type identifier can be used to declare variables later.
typedef type identifier;
Where type refers to an existing data type, identifier refers to the new name given to the data
type.
The existing data type may belong to any class of type, including the userdefined type.
Example:
typedef int units;
typedef float marks;
Here, units symbolizes int and marks symbolizes float.
units batch1,batch2;
marks name[10];
Advantage of typedef
We can create meaningful data type names for increasing the readability of the program.
2. “enumerated”
Enum identifier (value1,value2,…..,valuen);
The ‘identifier’ is a user-defined enumerated data type which can be used to declare variables
That can have one of the values enclosed within the braces – enumerated constants.
enum identifier v1,v2,…..,vn;
The enumerated variables v1,v2,…..,vn can have one of the values value1,value2,…..,valuen.
V1=value3;
V3=value5;
Example:
Enum day(Moday,Tuesday,…..,Sunday);
Enum day week_st,week_end;
Week_st=Monday;
Week_end=Friday;

Defining Global Variables


Global variables are known throughout the program.
The variables hold their values throughout the programs execution.
Global variables are created by declaring them outside of any function.
It need not be declared in other function.
A global variable is also known as external variable.
Global variables are defined above main () in the following way:
int n, sum;
int m,l;
char letter;
main()
{
}
it is also possible to pre-initialize global variables using the = operator for assignment.
Example:
float sum = 0.0;
int n= 0;
char c=`a';
main()
{
}

8
BCA 202-PROGRAMMING IN C Unit-1

This is the same as:


float sum;
int n;
char letter;
main()
{
sum = 0.0;
n= 0;
c=`a';
}
is more efficient.
C also allows multiple assignment statements using =
Example:
a = b = 1;
This is same as
a = 1;
b = 1;
Note : The assignment is valid if all the variable types are the same data type.

Printing Out and Inputting Variables


printf() and scanf() in C
The printf() and scanf() functions are used for input and output in C language. Both functions
are inbuilt library functions, defined in stdio.h (header file).
printf() function
The printf() function is used for output. It prints the given statement to the console.
The syntax of printf() function is given below:
1. printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function
The scanf() function is used for input. It reads the input data from the console.
1. scanf("format string",argument_list);
Program to print cube of given number
Let's see a simple example of c language that gets input from the user and prints the cube of
the given number.
1. #include<stdio.h>
2. int main(){
3. int number;
4. printf("enter a number:");
5. scanf("%d",&number);
6. printf("cube of number is:%d ",number*number*number);
7. return 0;
8. }
Output
enter a number:5
cube of number is:125
The scanf("%d",&number) statement reads integer number from the console and stores the
given value in number variable.
The printf("cube of number is:%d ",number*number*number) statement prints the cube
of number on the console.

9
BCA 202-PROGRAMMING IN C Unit-1

Program to print sum of 2 numbers


1. #include<stdio.h>
2. int main(){
3. int x=0,y=0,result=0;
4.
5. printf("enter first number:");
6. scanf("%d",&x);
7. printf("enter second number:");
8. scanf("%d",&y);
9.
10. result=x+y;
11. printf("sum of 2 numbers:%d ",result);
12.
13. return 0;
14. }
15.
Output
enter first number:9
enter second number:9
sum of 2 numbers:18
C – Constants/ literals
Fixed values that do not change during the execution of a program.

Integer Constants
An integer constant refers to a sequence of digits.

10
BCA 202-PROGRAMMING IN C Unit-1

Real Constants
These numbers are decimal notation,havinfg whole number followed by a decimal point and
the fractional part.
It is possible to omit digits before the decimal part, or digits after the decimal part.
A real number may expressed in exponential notation.
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or integer.
The exponent is an integer number with an optional + or – sign.
The letter e can be written in either uppercase or lowercase.
Embedded white space is not allowed.
The e notation is called floating-point form.
Floating –point constants are represented as double-precision quantities.
f or F --- Single-precision
l or L --- Double-precision
Valid real numbers: 78688L,25636l,444.643f,321.55F,2.5e+05,374e-04
Invalid real numbers: 1.5E+0.5,$25,ox7B,7.5 e -0.5,1,00,00.00

Character Constants

Escape Sequence in C/ Backslash character constants


- used in output functions
- each one of them represents one character.
- these characters combinations are known as escape sequences
Escape Sequence Meaning
\a Alarm or Beep Escape Sequence Example
\b Backspace 1. #include<stdio.h>
\f Form Feed 2. int main(){
\n New Line 3. int number=50;
\r Carriage Return 4. printf("You\nare\nlearning\n\
\t Tab (Horizontal) 'c\' language\n\"Do you know C
\v Vertical Tab language\"");
\\ Backslash 5. return 0;
\' Single Quote 6. }
\" Double Quote Output:
You
\? Question Mark
are
\nnn octal number
learning
\xhh hexadecimal
'c' language
number
"Do you know C language"
\0 Null

11
BCA 202-PROGRAMMING IN C Unit-1

SYMBOLIC CONSTANTS
Symbolic constant is defined as follows
#define symbolic_name value-of-constant
Example:
#define PI 3.14159
#define MAXMARKS 100
Rules
1) Symbolic names have the same form as variable names.
2) No blank space between the # sign define is permitted.
3) # must be the first character in the line.
4) A blank space is required between #define and symbolic name and between the symbolic
name and constant.
5) #define statements must not end with a semicolon.
6) After definition, the symbolic name should not be assigned any other value within the
program by using an assignment statement.
7) Symbolic names are not declared for data types. Its data type depends on the type of constant.
8) #define statements may appear anywhere in the program but before it is referenced in the
program.
C - Operators
• A symbol use to perform some operation on variables, operands or with the constant is known
as operator.
•Some operator required 2 operand or Some required single operand to perform operation.
• C operators can be classified into a number of categories.
1) Arithmetic operators 5) Increment and decrement operators
2) Relational operators 6) Conditional operators
3) Logical operators 7) Bitwise operators
4) Assignment operators 8) Other operators
An expression is a sequence of operands and operators that reduces to a single value.
The value can be any type other than void.

Arithmetic Operators

Assume variable A holds 10 and variable B holds 20 then −


Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of after an integer division. B % A = 0
++ Increment operator increases the integer value by one. A++ = 11
-- Decrement operator decreases the integer value by one. A-- = 9
Relational Operators
Assume variable A holds 10 and variable B holds 20 then −
Operator Description Example
== Checks if the values of two operands are equal or not. If yes, then the (A == B) is not
condition becomes true. true.
!= Checks if the values of two operands are equal or not. If the values are (A != B) is true.
not equal, then the condition becomes true.
> Checks if the value of left operand is greater than the value of right (A > B) is not
operand. If yes, then the condition becomes true. true.

12
BCA 202-PROGRAMMING IN C Unit-1

< Checks if the value of left operand is less than the value of right (A < B) is true.
operand. If yes, then the condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value (A >= B) is not
of right operand. If yes, then the condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the value of (A <= B) is true.
right operand. If yes, then the condition becomes true.
Logical Operators
Assume variable A holds 1 and variable B holds 0, then −
Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then (A && B) is
the condition becomes true. false.
|| Called Logical OR Operator. If any of the two operands is non-zero, (A || B) is true.
then the condition becomes true.
! Called Logical NOT Operator. It is used to reverse the logical state of !(A && B) is
its operand. If a condition is true, then Logical NOT operator will true.
make it false.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and
^ is as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011

Assume variable 'A' holds 60 and variable 'B' holds 13, then −
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in (A & B) = 12, i.e., 0000
both operands. 1100
| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e., 0011
1101
^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) = 49, i.e., 0011
but not both. 0001
~ Binary One's Complement Operator is unary and has the (~A ) = ~(60), i.e,. -
effect of 'flipping' bits. 0111101
<< Binary Left Shift Operator. The left operands value is moved A << 2 = 240 i.e., 1111
left by the number of bits specified by the right operand. 0000
>> Binary Right Shift Operator. The left operands value is moved A >> 2 = 15 i.e., 0000
right by the number of bits specified by the right operand. 1111
Assignment Operators
The following table lists the assignment operators supported by the C language −

13
BCA 202-PROGRAMMING IN C Unit-1

Operator Description Example


= Simple assignment operator. Assigns values from C = A + B will assign the value of A
right side operands to left side operand + B to C
+= Add AND assignment operator. It adds the right C += A is equivalent to C = C + A
operand to the left operand and assign the result
to the left operand.
-= Subtract AND assignment operator. It subtracts C -= A is equivalent to C = C - A
the right operand from the left operand and
assigns the result to the left operand.
*= Multiply AND assignment operator. It multiplies C *= A is equivalent to C = C * A
the right operand with the left operand and
assigns the result to the left operand.
/= Divide AND assignment operator. It divides the C /= A is equivalent to C = C / A
left operand with the right operand and assigns
the result to the left operand.
%= Modulus AND assignment operator. It takes C %= A is equivalent to C = C % A
modulus using two operands and assigns the
result to the left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
Misc Operators ↦ sizeof & ternary
Besides the operators discussed above, there are a few other important operators
including sizeof and ? : supported by the C Language.
Operator Description Example
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.
& Returns the address of a variable. &a; returns the actual address of the variable.
* Pointer to a variable. *a;
?: Conditional Expression. If Condition is true ? then value X : otherwise value
Y

INCREMENT & DECREMENT OPERATORS


operators
1. Pre-increment & decrement-prefix ++ and --
2. Post-increment & decrement-postfix ++ andn--
Prefix operator adds 1 to the operand and then the result is assigned to the variable on left.
Postfix operator first assigns the value to the variable on left and then increments the
operator.
Rules
1. Increment and decrement operators are unary operators.
2. When postfix ++ (or --) is used with a variable in an expression, the expression is evaluated
first using the original value of the variable and then the variable is Increment (or decrement)
by one.
3. When prefix ++ (or decrement) is used in an expression, the variable is incremented (or
decremented) first and then the expression is evaluated using the new value of the variable.
4. The precedence and associatively of ++ and – operators are same as those of unary + and
unary -.

14
BCA 202-PROGRAMMING IN C Unit-1

Examples
m=5;

Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated
first.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

Conditionals (The if statement, The switch statement)


Conditional statements help you to make a decision based on certain conditions. These
conditions are specified by a set of conditional statements having Boolean expressions which
are evaluated to a Boolean value true or false. There are following types of conditional
statements in C.
1. If statement 4. If-Else If ladder
2. If-Else statement 5. Switch statement
3. Nested If-else statement

If statement
The single if statement in C language is used to execute the code if a condition is true. It is also
called one-way selection statement.

15
BCA 202-PROGRAMMING IN C Unit-1

Syntax
if(expression)
{
//code to be executed
}

How "if" statement works..


• If the expression is evaluated to nonzero (true) then if block statement(s) are
executed.
• If the expression is evaluated to zero (false) then Control passes to the next statement
following it.
Note
"Expression must be scalar type" i.e evaluated to a single value.
if Statement Example
1. #include<stdio.h> 8. if(n%2==0)
2. #include<conio.h> 9. {
3. void main() 10. printf("%d number in even",num);
4. { 11. }
5. int num=0; 12. getch();
6. printf("enter the number"); 13. }
7. scanf("%d",&num);

Example
1. main() 8. c=a-b;
2. { 9. printf(“the difference is%d”,c);
3. int a,b,c; 10. }
4. printf(“enter the value of a and 11. }
b\n”); Output
5. scanf(“%d%d”,&a,&b); enter the value of a and b
6. if (a-b!=0) 53
7. { the difference is 2

If-else statement
The if-else statement in C language is used to execute the code if condition is true or false. It
is also called two-way selection statement.
Syntax
if(expression)
{
//Statements
}
else
{
//Statements
}

16
BCA 202-PROGRAMMING IN C Unit-1

How "if..else" statement works..


• If the expression is evaluated to nonzero (true) then if block statement(s) are
executed.
• If the expression is evaluated to zero (false) then else block statement(s) are
executed.
if..else Statement Example
1. #include<stdio.h> 10. printf("%d number in even", num);
2. #include<conio.h> 11. }
3. void main() 12. else
4. { 13. {
5. int num=0; 14. printf("%d number in odd",num);
6. printf("enter the number"); 15. }
7. scanf("%d",&num); 16. getch();
8. if(n%2==0) 17. }
9. {

Example
1. main() 8. printf(“a is positive”);
2. { 9. }
3. int a; 10. else
4. printf(“Enter the value of a \n”); 11. {
5. scanf(“%d%d”,&a,&b); 12. printf(“a is negative”);
6. if (a>=0) 13. }
7. { 14. }
Output
Enter the value of a 5
a is positive
Enter the value of a -12
a is negative

Nested If-else statement


The nested if...else statement is used when a program requires more than one test expression.
It is also called a multi-way selection statement. When a series of the decision are involved in
a statement, we use if else statement in nested form.
Syntax
if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else
{
statement-block 3;
}

17
BCA 202-PROGRAMMING IN C Unit-1

Example
1. #include<stdio.h> 17. printf("c is greatest");
2. #include<conio.h> 18. }
3. void main( ) 19. }
4. { 20. else
5. int a,b,c; 21. {
6. clrscr(); 22. if(b>c)
7. printf("Please Enter 3 number"); 23. {
8. scanf("%d%d%d",&a,&b,&c); 24. printf("b is greatest");
9. if(a>b) 25. }
10. { 26. else
11. if(a>c) 27. {
12. { 28. printf("c is greatest");
13. printf("a is greatest"); 29. }
14. } 30. }
15. else 31. getch();
16. { 32. }

If..else If ladder
The if-else-if statement is used to execute one code from multiple conditions. It is also called
multipath decision statement. It is a chain of if..else statements in which each if statement is
associated with else if statement and last would be an else statement.

Syntax
if(condition1)
{
//statements
}
else if(condition2)
{
//statements
}
else if(condition3)
{
//statements
}
else
{
//statements
}
If..else If ladder Example
1. #include<stdio.h> 9. {
2. #include<conio.h> 10. printf("divisible by both 5 and 8");
3. void main( ) 11. }
4. { 12. else if( a%8==0 )
5. int a; 13. {
6. printf("enter a number"); 14. printf("divisible by 8");
7. scanf("%d",&a); 15. }
8. if( a%5==0 && a%8==0) 16. else if(a%5==0)

18
BCA 202-PROGRAMMING IN C Unit-1

17. { 22. printf("divisible by none");


18. printf("divisible by 5"); 23. }
19. } 24. getch();
20. else 25. }
21. {

Example
• Program to read the customer number and power consumed and prints the amount o
be paid by the customer. Consumption rate of charges units
0-200 Rs. 0.50 per unit
201-400 Rs. 100+0.65 per unit excess of 200
401-600 Rs. 230+0.80 per unit excess of 400
601 and above Rs 390+Rs.1 per unit excess of 600
Program
1. main() 14. charge=390+(units-600);
2. { 15. printf(“\n Customer No:%d”,num);
3. int units,num; 16. printf(“\nUnits Consumed
4. float charge; :%d”,units);
5. printf(“enter the customer no and 17. printf(“\n Charge : Rs.
units consumed\n”); %.2f”,charge);
6. scanf(“%d%d”,&units,&num); 18. }
7. if (units<=200) Output
8. charge=units*0.50; Enter customer no units consumed
9. else if (units<=400) 1
10. charge=100.00+0.65*(units-200); 500
11. else if 9units<=600) Customer No:1
12. charge=230+0.80*(units-400); Units Consumed :500
13. else Charge: Rs. 310.00

Switch Statement
switch statement acts as a substitute for a long if-else-if ladder that is used to test a list of cases.
A switch statement contains one or more case labels which are tested against the switch
expression. When the expression match to a case then the associated statements with that case
would be executed.
Syntax
Switch (expression)
{
case value1:
//Statements
break;
case value 2:
//Statements
break;
case value 3:
//Statements
case value n:
//Statements
break;
Default:
//Statements
}

19
BCA 202-PROGRAMMING IN C Unit-1

switch statement Example


1. #include<stdio.h> 15. {
2. #include<conio.h> 16. printf("You passed");
3. void main( ) 17. }
4. { 18. else if (grade == 'F')
5. char grade = 'B'; 19. {
20. printf("Better try again");
6. if (grade == 'A') 21. }
7. { 22. else
8. printf("Excellent!"); 23. {
9. } 24. printf("You Failed!");
10. else if (grade == 'B') 25. }
11. { 26. }
12. printf("Well done"); 27. getch();
13. } 28. }
14. else if (grade == 'D')
RULES FOR SWITCH STATEMENT
1. The switch expression must be an integral type.
2. Case labels must be constants or constants expressions.
3. Case labels must be unique. no two labels can have same value.
4. Case labels must end width colon.
5. The break statement transfers the control out of the switch.
6. The break statement is optional. Ie, two or more case labels may belong to the same statements.
7. The default label is optional. If present then it will executed when the expression
does not find the matching case label.
8. There can be at most one default label.
9. The default may be placed anywhere but usually placed at the end.
10. It is permitted to nest switch statement.

Looping and Iteration


Iteration is the process where a set of instructions or statements is executed repeatedly for a specified
number of time or until a condition is met. These statements also alter the control flow of the program
and thus can also be classified as control statements in C Programming Language.
Iteration statements are most commonly know as loops.

A sequence of statement executed until some conditions for termination of the


loop are satisfied.
A program loop consists of two segments , body of the loop and control statement.
The control statement tests certain conditions and then directs the repeated execution of the statements
contained in the body of the loop.
Depending on the position of the control statement in the loop, control structures may classified as
the entry-control loop and exit-control loop.
Entry-control loop
In the entry-control loop, the control condition is tested before the start of the loop execution. If the
condition is not satisfied then the body of the loop will not be executed.
It is known as pre-test loops
Exit-control loop
The control condition is tested at the end of the body of the loop and therefore the
body is executed unconditionally for the first time.
It is known a s post-test loops.

20
BCA 202-PROGRAMMING IN C Unit-1

A looping process would include the following tour steps.


1. Setting and initialization of a condition variable.
2. Execution of the statements in the loop
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable.
Looping statements
1. The while statement
2. The do statement
3. The for statement.
Based on the nature of control variable and the kind of value assigned to it for testing the control
expression, the loops may be two types.
I. Counter-controlled loops
II. Sentinel-controlled loops
i. Counter-controlled loop (repetition loop)
No. of times the loop will be executed known in advance then we may use counter-control loop.
A control variable as counter
The counter must be initialized, tested and updated.
No. of times the loop will be executed may be a constant or a variable that is assigned a value.
.
ii. Sentinel-controlled loop(indefinite loop)
A special value called sentinel value is used to change the loop control expression from true or false.
The control variable is called sentinel value.
The no. of repetitions is not known before the loop begins executing

WHILE STATEMENT
while is entry-control loop.
Syntax
while (test condition)
{
Body of the loop
}

The test condition is evaluated and if the condition is true then the body of the loop is
executed.
After execution of the body, the testcondition is once again evaluated and if it is true then
the body of the loop is executed once again.
The process of repeated execution of the body continues until the testcondition becomes
false and the control is transferred out of the loop.
On exit, the program continues with the statement immediately after the body of loop.
The body of the loop may have one or more statements.

21
BCA 202-PROGRAMMING IN C Unit-1

The body of the loop may not be executed at all if the condition is not satisfied at very first
attempt.

Example 1
1. main() 9. {
2. { 10. sum = sum + i;
3. int i, n, sum; 11. i = i+1;
4. printf(“Enter the value of n\n”); 12. }
5. scanf(“%d”, &n); 13. printf(“sum of natural numbers up to %d
6. i=1; = %d”, n, sum);
7. sum=0; 14. }
8. while(i<=n)
Example2
Program to evaluate the equation y=xn
Program
1. main() 9. while(count<=n)
2. { 10. {
3. int count,n; 11. y=y*x;
4. float x,y; 12. count++;
5. printf(“enter the value of x and n” ); 13. }
6. scanf(“%f %d”, &x ,&n); 14. printf(“\nx= %f; = %d; x to power n =
7. y=1.0; f\n”,x,n,y);
8. count=1; 15. }

DO STATEMENT
Do statement is exit-controlled loop.
Syntax
do
{
body of the loop
} while (test condition);

The program proceeds to evaluate the body of the loop first.


At the end of the loop, test condition in the while statement is evaluated.
If the condition is true then the program continues to evaluate the body of the loop once again.
This process continues as long as the condition is true.
When the condition becomes false then the loop will be terminated and the control goes to the
statement that appears immediately after the while statement.
The body of the loop is always executed at least once.
Example
1. main() 9. {
2. { 10. sum = sum + i;
3. int i, n, sum; 11. i = i+1;
4. printf(“Enter the value of n\n”); 12. } while(i<=n);
5. scanf(“%d”, &n); 13. printf(“sum of natural numbers up to %d
6. i=1; = %d”, n,
7. sum=0; 14. sum);
8. do 15. }

22
BCA 202-PROGRAMMING IN C Unit-1

FOR STATEMENT
For statement is entry-controlled loop.
Syntax
for(initialization;test-condition,increment)
{
body of the loop;
}

The execution of the for statement is as follows


1. Initialization of the control variable is done first, using assignment statement.
2. The value of the control variable is tested using the test-condition. The test-condition is a relational
expression. If the condition is true then body of the loop is executed. Otherwise, the lopp is terminated
and the execution continues with the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for statement after
evaluating the last statement in the loop. The control variable is incremented using the assignment
statement and the new value of the control variable is again tested to see whether it satisfies the loop
condition. If the condition is true then the body of the is executed. This process is continues till the value
of the control variable fails to satisfies the test-condition.
Example
1. main() 8. {
2. { 9. sum = sum + i;
3. int i, n, sum; 10. }
4. printf(“Enter the value of n\n”); 11. printf(“sum of natural numbers up
5. scanf(“%d”, &n); 12. to %d = %d”, n, sum);
6. sum=0; 13. }
7. for (i=1;i<=n;i++)
The for statement allows the negative increments.
Example
for(x=9;x>=0;x--)
printf(“%d”,x);
printf(“\n”);
The above loop is executed 10 times, but the output would be from 9 to 0 instead of 0 to 9.
Since the conditional test is always performed at the beginning of the loop, the body of the loop may
not be executed at all, if the condition fails at the start.
Example
for(x=9;x<9;x--)
printf(“%d”,x);
The above loop never executed because the test condition fails at the beginning itself.

23
BCA 202-PROGRAMMING IN C Unit-1

Example
#include <stdio.h> When the above code is compiled and
executed, it produces the following result
int main () { −
value of a: 10
int a; value of a: 11
value of a: 12
/* for loop execution */ value of a: 13
for( a = 10; a < 20; a = a + 1 ){ value of a: 14
printf("value of a: %d\n", a); value of a: 15
} value of a: 16
value of a: 17
return 0; value of a: 18
} value of a: 19
Example
#include <stdio.h>
When the above code is compiled and
int main () { executed, it produces the following result

/* local variable definition */ value of a: 10
int a = 10; value of a: 11
value of a: 12
/* while loop execution */ value of a: 13
while( a < 20 ) { value of a: 14
printf("value of a: %d\n", a); value of a: 15
a++; value of a: 16
} value of a: 17
value of a: 18
return 0; value of a: 19
}
Example
#include <stdio.h> }
When the above code is compiled and
int main () { executed, it produces the following result

/* local variable definition */ value of a: 10
int a = 10; value of a: 11
value of a: 12
/* do loop execution */ value of a: 13
do { value of a: 14
printf("value of a: %d\n", a); value of a: 15
a = a + 1; value of a: 16
}while( a < 20 ); value of a: 17
value of a: 18
return 0; value of a: 19
Example1:Program to generate prime numbersnbetween 1 and n.
1. #include<stdio.h> 4. {
2. #include <conio.h> 5. int i,j,n;
3. void main() 6. lbl: printf(“enter the value of n\n”);

24
BCA 202-PROGRAMMING IN C Unit-1

7. scanf(“%d”,&n); 19. for (i=3;i<=n;i++)


8. if (n <1) 20. {
9. { 21. for (j=2;j<i;j++)
10. printf(“invalid no. try again”); 22. {
11. goto lbl; 23. if (i %j ==0)
12. } 24. goto m;
13. printf(“prime numbers are \n”); 25. }
14. if (n>0 && n <=2) 26. printf(“%d”,i);
15. { 27. m:
16. printf(“the prime no is 2”); 28. }
17. goto end; 29. end: getch();
18. } 30. }

Example2:
Program To Print N Fibonacci Number
1. #include <stdio.h> 10. for(i=1;i<=n-2;i++)
2. #include <conio.h> 11. {
3. void main() 12. fib=n1=+n2;
4. { 13. printf(“\t%d”,fib);
5. int n1=0,n2=1,n,i,fib; 14. n1=n2;
6. clrscr(); 15. n2=fib;
7. printf (“enter the value of n\n”); 16. }
8. printf(“%d”,&n) 17. getch();
9. printf(“%d\t%d”,n1,n2); 18. }
Additional features of for loop
1. More than one variable can be initialized at a time in the for statement. Example
p=1;
for(n=0;n<10;n++)
Can be written as
for(p=1,n=0;n<10;n++)
2. The increment section may also have more than one part. Example
for (n=0;n<10;n++,m--)
3. Test condition may have any compound relation and the testing need not be limited
only to the loop control variable. Example
sum=0
for (i=0;i<10&& sum <100;i++)
{
sum=sum+i;
}
4. Expression can be used in the assignment statements of initialization and increment
section. Example
for(x=(m+n)/2;x>0;x=x/2)
5. One or more section can be omitted in for loop.----
m=5;
for(;m<10;)
{
printf(“%d\n”,m);
m=m+2;
}
6. We can set up the time delay loops using for statement. Example
for(j=1;j<1000;j++);

25
BCA 202-PROGRAMMING IN C Unit-1

Nesting of for loops


One for statement within another for statement is called nesting of for. Example
----------
----------
for (i=0;i<n;i++)
{
for(j=1;j<m;j++)
{
----------
----------
}
----------
----------
}
----------
----------
Example
Program to read the marks by n students in various subject and print the total.
1. #include<stdio.h> 13. printf(“Enter marks of %d subjects for
2. #include<conio.h> roll
3. void main() 14. no %d\n”, m, rno);
4. { 15. for(j=1;j<=m;j++)
5. int n, m, i, j, rno, marks, total; 16. {
6. printf(“Enter the no. of students & 17. scanf(“%d”,&marks);
subjects\n”); 18. total= total+marks;
7. scanf(“%d%d”,&n,&m); 19. }
8. for(i=1;i<=n;i++) 20. printf(“total marks =%d” ,total);
9. { 21. }
10. printf(“Enter the roll no. :”); 22. getch();
11. scanf(“%d”,&rno); 23. }
12. total=0;
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves
a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements.
Sr.No. Control Statement & Description
1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.
3 goto statement
Transfers control to the labeled statement.

break statement in C
The break statement in C programming has the following two usages −
• When a break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops, the break statement will stop the execution of the innermost
loop and start executing the next line of code after the block.

26
BCA 202-PROGRAMMING IN C Unit-1

Syntax
The syntax for a break statement in C is as
follows −
break;

1. #include <stdio.h> 9. if( a > 15) {


2. int main () { 10. /* terminate the loop using break
3. /* local variable definition */ statement */
4. int a = 10; 11. break;
5. /* while loop execution */ 12. }
6. while( a < 20 ) { 13. }
7. printf("value of a: %d\n", a); 14. return 0;
8. a++; 15. }

When the above code is compiled and value of a: 12


executed, it produces the following result value of a: 13
− value of a: 14
value of a: 10 value of a: 15
value of a: 11
continue statement in C
The continue statement in C programming works somewhat like the break statement. Instead
of forcing termination, it forces the next iteration of the loop to take place, skipping any code
in between.
For the for loop, continue statement causes the conditional test and increment portions of the
loop to execute. For the while and do...while loops, continue statement causes the program
control to pass to the conditional tests.
Syntax
The syntax for a continue statement in C
is as follows −
continue;

Example
1. #include <stdio.h> 12. printf("value of a: %d\n", a);
2. int main () { 13. a++;
3. /* local variable definition */ 14. } while( a < 20 );
4. int a = 10; 15. return 0;
5. /* do loop execution */ 16. }
6. do {
Output −
7. if( a == 15) {
value of a: 10
8. /* skip the iteration */ value of a: 11
9. a = a + 1; value of a: 12
10. continue; value of a: 13
11. } value of a: 14

27
BCA 202-PROGRAMMING IN C Unit-1

value of a: 16 value of a: 18
value of a: 17 value of a: 19

goto statement in C
A goto statement in C programming provides an unconditional jump from the 'goto' to a
labeled statement in the same function.
NOTE − Use of goto statement is highly discouraged in any programming language because
it makes difficult to trace the control flow of a program, making the program hard to
understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.
Syntax
The syntax for a goto statement in C is as
follows −
goto label;
..
.
label: statement;

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.

Example
1. #include <stdio.h> 14. }while( a < 20 );
2. int main () { 15. return 0;
3. /* local variable definition */ 16. }
4. int a = 10; Output −
5. /* do loop execution */ value of a: 10
6. LOOP:do { value of a: 11
7. if( a == 15) { value of a: 12
8. /* skip the iteration */ value of a: 13
9. a = a + 1; value of a: 14
10. goto LOOP; value of a: 16
11. } value of a: 17
12. printf("value of a: %d\n", a); value of a: 18
13. a++; value of a: 19

28

You might also like