Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

Module I - Basic Programming Concepts in C

1. To comprehend the basic programming concepts in C


1.1 To know the C Character Set
1.2 To describe the concept of Constants, Variable and
Keywords
1.3 To discuss C Instructions
1.4 To know Control Instructions in C
1.5 To know decision control structures
1.6 To know logical operators
1.7 To know conditional operators
1.8 To know loop Control Structures
1.9 To know Case Control Structure

1
Introduction

Communicating with computer- achieve through programs written in a


programming language

The C Character Set

A character denotes any alphabet, digit or special symbol used to represent


information. The following table represents valid alphabets, numbers and special
symbols allowed in C.

2
Constants, Variables and Keywords

The alphabets, numbers and special symbols when properly combined form
constants, variables and keywords.

A constant is an entity that doesn’t change its value whereas a variable is an


entity that may change its value during the program execution.

Types of C Constants

C constants can be divided into two major categories:

(a) Primary Constants

(b) Secondary Constants

The three primary constants and variable types in C are integer, float and
character.

Variable

An entity that may vary during program execution is called a variable.

3
Variable names are names given to locations in memory. These locations can
contain integer, real or character constants.The types of variables depend on the
types of constants that it can handle.For eg, an integer variable can hold only an
integer constant, a real variable can hold only a real constant and a character
variable can hold only a character constant.

Rules for Constructing Variable Names

• A variable name is any combination of 1 to 31 alphabets, digits or


underscores.

• Do not create unnecessarily long variable names as it adds to your typing


effort.

• The first character in the variable name must be an alphabet or underscore.

• No commas or blanks are allowed within a variable name.

• No special symbol other than an underscore (as in gross_sal) can be used in


a variable name.

Variable declaration

C compiler made it compulsory to declare the type of any variable name that you
wish to use in a program. This type declaration is done at the beginning of the
program. Following are the examples of type declaration statements:

• float bassal ;

• char code ;

C Keywords

Keywords are the words whose meaning has already been explained to the C
compiler.(or they have some predefined meaning).The keywords cannot be used
as variable names. The keywords are also called ‘Reserved words’.There are only
32 keywords available in C

4
C Instructions

C instructions are formed by combining variables, constants & keywords.By using


Instructions, C program is written.There are basically three types of instructions in
C:

1. Type Declaration Instruction

2. Arithmetic Instruction

3. Control Instruction

The purpose of each of these instructions is given below:

 Type declaration instruction − To declare the type of variables used in a C


program.

 Arithmetic instruction − To perform arithmetic operations between


constants and variables.

 Control instruction − To control the sequence of execution of various


statements in a C program.

Eg. C Program

/* Program to perform addition of two integers*/

main( )

5
{

int num1, num2 , res ; /*Type declaration instruction*/

num1= 200; /* assign constant values*/

num2=500;

res= num1 + num2; /* arithmetic instruction*/

printf ( "%d" , res) ;

/* Display the value of variable res on screen*/

Rules that are applicable to all C programs:

1. Each instruction in a C program is written as a separate statement.


Therefore a complete C program would comprise of a series of statements.

2. The statements in a program must appear in the same order in which we


wish them to be executed

3. No blank spaces are allowed within a variable, constant or keyword.

4. All statements are entered in small case letters.

5. C has no specific rules for the position at which a statement is to be written.


That’s why it is often called a free-form language.

6. Every C statement must end with a ; Thus ; acts as a statement terminator.

7. Comment about the program should be enclosed within /* */.

8. main( ) is a function included in every C program.

9. Any variable used in the program must be declared before using it. For
example,

int p, n ;

6
float r, si ;

10 printf( ) outputs the values of variables to the screen whereas scanf( )


receives them from the keyboard.

Note: The ampersand (&) before the variables in the scanf( ) function is a must.
& is an ‘Address of’ operator. It gives the location number used by the variable
in memory. When we say &a, we are telling scanf( ) at which memory location
should it store the value supplied by the user from the keyboard.

Control Instructions in C

• The control instructions determine the ‘flow of control’ in a program. There


are four types of control instructions in C. They are:

1. Sequence Control Instruction

2. Selection or Decision Control Instruction

3. Repetition or Loop Control Instruction

4. Case Control Instruction

The Sequence control instruction ensures that the instructions are executed in
the same order in which they appear in the program.

Decision and Case control instructions allow the computer to take a decision as
to which instruction is to be executed next.

The Loop control instruction helps computer to execute a group of statements


repeatedly.

The Decision Control Structure

A decision control instruction can be implemented in C using:

 The if statement

 The if-else statement

7
 switch statement.

 The conditional operators

The if Statement

• The general form of if statement looks like this:

if ( condition )

statement ;

• The condition following the keyword if is always enclosed within a pair of


parentheses. If the condition, is true, then the statement is executed. If the
condition is not true then the statement is not executed;

• we express a condition using C’s ‘relational’ operators.

/* Demonstration of if statement */

main( )

int num ;

printf ( "Enter a number " ) ;

scanf ( "%d", &num ) ;

if ( num > 0 )

printf ( “ You entered a positive number" ) ;

The if-else Statement

we execute one group of statements if the expression evaluates to true and


another group of statements if the expression evaluates to false.The group

8
of statements after the if up to and not including the else is called an ‘if
block’. Similarly, the statements after the else form the ‘else block’.

if ( condition )

statement ;

else

statement ;

if - else Example

/* Demonstration of if - else statement */

main( )

int num ;

printf ( "Enter a number " ) ;

scanf ( "%d", &num ) ;

if ( num > 0 )

printf ( “ You entered a positive number" ) ;

else

printf ( “ You entered a negative number" ) ;

Nested if-elses

if we write an entire if-else construct within either the body of the if statement or
the body of an else statement , it is called ‘nesting’of ifs.

/* Demonstration of Nested if else statement */

9
main( )

int num ;

printf ( "Enter a number " ) ;

scanf ( "%d", &num ) ;

if ( num > 0 ) /*outer if*/

printf ( “ You entered a positive number" ) ;

else

if(num == 0) /*inner if*/

printf ( “ You entered zero" ) ;

else

printf ( “ You entered a negative number" ) ;

Logical Operators

• C allows usage of three logical operators:

1. && ( AND)

2. || ( OR)

3. ! (NOT)

( Don’t use the single symbol | and &. These single symbols also have a
meaning.)

10
The first two operators, && and ||, allow two or more conditions to be combined
in an if statement.The ! operator reverses the result of the expression it operates
on. For example, if the expression evaluates to a non-zero value, then applying !
operator to it results into a 0 and Vice versa.

Eg: ! ( y < 10 ) means “not y less than 10”. if y is less than 10, the expression will
be false. We can express the same condition as ( y >= 10 ).

The Conditional Operators

The conditional operators ? and : are sometimes called ternary operators since
they take three arguments.In fact, they form a kind of foreshortened if-then-else.
Their general form is,

expression 1 ? expression 2 : expression 3

This means “if expression 1 is true, then the value returned will be expression 2,
otherwise the value returned will be expression 3”.

Conditional Operator : Example

int x, y ;

scanf ( "%d", &x ) ;

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.

The equivalent if statement will be,

if ( x > 5 )

y=3;

else

y=4;

11
Loop Control Structures

Loop is the mechanism to execute a set of instructions repeatedly inorder to


perform some actions over and over.This involves repeating some portion of the
program either a specified number of times or until a particular condition is being
satisfied.This repetitive operation is done through a loop control instruction.There
are three methods by way of which we can repeat a part of a program. They are:

1. Using a for statement

2. Using a while statement

3.Using a do-while statement

WHILE LOOP

The while loop is ideally suited to do something a fixed number of times.The


general form of while is as shown below:

initialise loop counter ;

while ( test loop counter using a condition )

statement1 ;

…….

Statement n;

increment loop counter ;

The statements within the while loop would keep on getting executed till the
condition being tested remains true. When the condition becomes false, the
control passes to the first statement that follows the body of the while loop.

12
The condition being tested may use relational or logical operators as shown in the
following examples:

while ( i <= 10 )

while ( i >= 10 && j <= 15 )

Example - while loop

Example1

i=1;

while ( i <= 5 )

printf ( “ \nProgramming in C”);

i = i +1;

The output will be as follows:

Programming in C

Programming in C

Programming in C

Programming in C

Programming in C

Example2

i=0;

while ( i <= 10 )

13
printf ( "%d\t”, i);

i = i +1;

The output will be

0 1 2 3 4 5 6 7 8 9 10

The flowchart –while loop

Do while Loop

Using the do-while loop, we can repeat the execution of statements within the
loop .The do while loop is a post tested loop. That is the condition is tested after
executing the body of the loop. The do-while loop is mainly used in the case
where we need to execute the loop at least once.

Syntax

do

14
{

Statement 1;

…..

Statement n;

increment loop counter ;

} while ( test loop counter using a condition );

main()

int count=1;

do

printf(“hello”);

count++;

} while ( count <= 3 );

Difference between while and dowhile loops

There is a minor difference between the working of while and do while loops. This
difference is the place where the condition is tested. The while tests the condition
before executing any of the statements within the while loop. As against this, the
do-while tests the condition after having executed the statements within the
loop. This means that do-while would execute its statements at least once, even if
the condition fails for the first time. The while, on the other hand will not execute
its statements if the condition fails for the first time.

Eg. difference between while and dowhile

15
int i=10;
While( i<=5)
{
printf(“loop
executed”);
}
printf(“program over”);

int i=10;
do
Here the output will be:
{
program over
printf(“loop
executed”);
}
While( i<=5);
printf(“program over”);
Here the output will be:
loop executed
program over
This means that the
body of the loop is
16

executed once even


The for Loop

• The general form of for Loop

for ( initialize counter ; test counter ; increment counter )

statement 1;

statement 2;

………

statement n;

When the for statement is executed for the first time, the value of count is set to
an initial value 1.Now the condition is tested and if it is satisfied, the body of the
loop is executed for the first time.Upon reaching the closing brace of for, control
is sent back to the for statement, where the value of count gets incremented by
1.Again the test is performed to check whether the new value of count satisfies
the condition.The process is repeated and when the condition becomes false,
control exits from the loop and is transferred to the statement (if any)
immediately after the body of for.

The for loop allows us to specify three things about a loop in a single line:

1. Setting a loop counter to an initial value.

2. Testing the loop counter to determine whether its value has reached the no
of repetitions required.

3. Increasing the value of loop counter each time the program statements
within the loop has been executed.

17
Explanation for- with EXAMPLE

main()

int count;

for(count=1; count <= 3;count++)

printf(“hello”);

When the for statement is executed for the first time, the value of count is set to
an initial value 1.Now the condition count <= 3 is tested. Since count is 1 the
condition is satisfied and the body of the loop is executed for the first time.Upon
reaching the closing brace of for, control is sent back to the for statement, where
the value of count gets incremented by 1.Again the test is performed to check
whether the new value of count exceeds 3.If the value of count is still within the
range 1 to 3, the statements within the braces of for are executed again.The body
of the for loop continues to get executed till count doesn’t exceed the final value
3.When count reaches the value 4 the control exits from the loop and is
transferred to the statement (if any) immediately after the body of for.

18
• Eg:2

main( )

int i ;

for ( i = 1 ; i <= 10 ; i + + )

printf ( "%d\t", i ) ;

The output will be :

1 2 3 4 5 6 7 8 9 10

The break Statement

Break statement is used in situations when we want to jump out of a loop


instantly, without waiting to get back to the conditional test.When break is
encountered inside any loop, control automatically passes to the first
statement after the loop. A break is usually associated with an if.

• Eg.. Jump out of the loop when we enter a 0.

Eg. Break statement

main( )

int num, i ;

while(1)

printf ( "Enter a number " ) ;

scanf ( "%d", &num ) ;

19
if ( num == 0 )

printf ( “zero …..loop terminated" ) ;

break ;

The continue Statement

In some programming situations we want to take the control to the beginning of


the loop, bypassing the statements inside the loop, which have not yet been
executed. The keyword continue allows us to do this. When continue is
encountered inside any loop, control automatically passes to the beginning of
the loop.

Case Control Structure

Decisions Using switch

• The control statement that allows us to make a decision from the number
of choices is called a switch. Syntax and Eg are as follows:

switch ( integer expression )

case constant 1 :

do this ;

case constant 2 :

do this ;

case constant 3 :

20
do this ;

default :

do this ;

main( )

{ char c ;

Scanf(“%c”,&c);

switch ( c )

case ‘R’ :

printf ( “Colour is RED" ) ;

case ‘G’ :

printf ( " Colour is GREEN" ) ;

case ‘B’ :

printf ( " Colour is BLUE" ) ;

default :

printf(" Any colour other than RGB" ) ;

What happens when we run a program containing a switch?

First, the expression following the keyword switch is evaluated.The value it gives
is then matched, one by one, against the constant values that follow the case

21
statements. When a match is found, the program executes the statements
following that case. If no match is found with any of the case statements, only
the statements following the default are executed.

Nested Loops- Loops within a loop

The way if statements can be nested, similarly whiles and fors can also be
nested.

• eg,.

for(i=1;i<=5;i++) The output will be:

{ 1

for(j=1;j<=i;j++) 12

{ printf(“%d ”,j);} 123

printf(“\n”); 1 2 3 4

} 12345

Working: in the outer for loop, set i=1 at the first time and the first statement
within this loop is another for loop. Now the inner for loop works completely
until its condition gets false. Then comes to the printf statement and then again
goes to the second execution of outer for loop. That is i=2. The above process is
repeated until the condition of outer for loop gets false .

22

You might also like