Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 61

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
• Communicating with computer- achieve thru
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.
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.
Types of C Constants
Variable

• An entity that may vary during program execution is


called a variable.
• 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:
• Ex.: int si, m_hra ;
• 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
C Keywords.
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
C Instructions cont..
• 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( )
{
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.
Rules that are applicable to all C
programs cont..
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.
Rules that are applicable to all C
programs cont..
9. Any variable used in the program must be declared
before using it. For example,
int p, n ;
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
Control Instructions in C cont..
• 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.
Decision Making Statements

• A decision control instruction can be


implemented in C using:
 if statement
 if-else statement
 if- else-if statement
 Nesting of if-else statements
 Switch statements
The if Statement
• If statement is used to test a condition, if
condition is true then the code inside the if
statement is executed otherwise that code is
not executed.
• Syntax:
if(Boolean_expression)
{ // Body of if
}
if example
/* 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
• 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.
• The group 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’.
Syntax
if(Boolean_expression) {
// Body of if statement
}else {
// Body of 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" ) ;
}
if-elseif –else statement
• After if statement else if is used to check the multiple
conditions.
Syntax:
If (Boolean_expression1){
// Body of if statement
}
else if(Boolean_expression2){
//Body of else if } else {
// Body of else statement
}
/* Demonstration of if – else if -else statement */

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" ) ;
}
}
Nested if Statement
 It contains multiple if else condition. It is used to check the
multiple conditions. This statement is like executing an if
statement inside an else statement.
Syntax
if(Boolean_expression1) {
//Body of if statement
if(Boolean_expression2)
{ //Body of nested if
}
}…
else
{ //Body of else statement
}
/* Demonstration of Nested if statement */

if ( i< 30 )
{ printf ("Value of i is less than 30");
if ( j == 10 )
{ printf ("Value of j is equal to 10");
}
}else
{ printf ("Value of i is not less than 30");
}
getch();
}
switch Statement
• It contains a number of cases with different conditions.
When a variable value is matched with the case, then that
case is executed.
Syntax
switch(expression)
{ case value1 : //Statements
break;
case value2 : //Statements
break;
casevaluen : //Statements
break;
default : //Optional
//Statements
}
/* Demonstration of Switch statement */

char grade ='B';


Switch (grade) {
case'A': printf("Excellent!\n");
break;
case'B':
case'C': printf("Well done\n");
break;
case'D': printf("You passed\n"); break;
case'F':printf("Better try again\n"); break;
default: printf("Invalid grade\n");
}
Logical Operators

 An expression containing logical operator returns either 0 or


1 depending upon whether expression results true or false.
 Logical operators are commonly used in
decision making in C programming .
 C allows three logical operators:
 Logical AND ( &&)
 Logical OR (||)
 Logical NOT (!)

 The first two operators (&& and ||) allow two or more
conditions to be combined in an if statement.
Operator Meaning of Operator Example

If c = 5 and d = 2 then,
Logial AND : True only if
&& expression ((c == 5) &&
all operands are true
(d > 5)) equals to 0.
Logical OR : True only if If c = 5 and d = 2 then,
|| either one operand is expression ((c == 5) || (d
true > 5)) equals to 1.

Logical NOT : True only if If c = 5 then, expression !


!
the operand is 0 (c == 5) equals to 0.
Hierarchy of logical operators

Operator precedence

! High

&& Medium

|| Low
Conditional Operators
 A conditional operator is a ternary operator, that is, it
works on 3 operands.
 It used in decision making process.
 In C Programming, Conditional Operator returns the
statement depends upon the given expression result.
Syntax
ConditionalExpression ? Expression 1 : Expression 2
 This means “if conditional expression is true, then the
value returned will be expression 1, otherwise the value
returned will be expression 2”.
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;
Looping Control Structures
 Loop is used to repeat a block of code until the specified condition is
met.
 It allows to execute a statement or group of statements multiple
times.

 C programming has three types of loops:


1. while loop
2. do - while loop
3. for loop
while Loop
 The while loop is constructed of a condition or expression and a
single command or a block of commands that must run in a loop.
 It repeats a statement or group of statements while a given
condition is true.
 It tests the condition before executing the loop body.
 It is an entry control loop.
Syntax
while (expression)
{
Block of statements
}
Example – Program to print first 10 natural
numbers

# include <stdio.h>
int main()
{ int x;
x = 1;
while (x <= 10)
{
printf(“%d \n”, x);
x = x + 1;
}
return 0;
}
for Loop

 for loop is similar to while loop but it is more complex.


 for loop is used to execute a set of statements repeatedly until
a particular condition is satisfied.
 It is an open ended loop
 for loop is constructed from a control statement that
determines how many times the loop will run and a command
section.
 Command section is either a single command or a block of
commands.
 Control statement itself has three parts: for ( initialization;
test condition; run every time command )
for Loop …….

Syntax
for(initialization; condition; increment/decrement)
{
statement – block;
}
The for loop is executed as :
1. It first evaluates the initialization code.
2. Then it checks the condition expression
3. If it is true, it executes the for-loop body.
4. Then it evaluate the increment/decrement condition and again
follows from step 2.
5. When the condition is false, it exits the loop.
Example – Program to print even numbers from 10
to 50
# include <stdio.h>
int main()
{ int x;
for(x = 10; x <=50; x = x +2)
{
printf(“%d \n”, x);
}
return 0;
}
do - while Loop
 It is similar to while statement, except that it test the
condition at the end of the loop body. So, it is called exit
control loop.
 The body of the loop is executed at least once, then the test
expression is evaluated.
Syntax
do
{
statements;
} while (expression);
Do - while Loop …..

 The statement is executed, then the expression is evaluated.


 If it is true, statement is executed again, and so on.
 When the expression becomes false, the loop terminates.
 A do-while loop is used to ensure that the statements within
the loop are executed at least once.
Example – Program to print first 10 multiples of 5.
#include <stdio.h>
int main()
{ int a, i;
a = 5;
i = 1;
do
{ printf("%d\t", a*i);
i = i + 1;
} while(i <= 10);
return 0;
}
Compare while and do-while Loop
While Loop Do- while Loop
Entry controlled loop Exit controlled loop
In while loop the controlling condition In 'do-while' loop the controlling
appears at the start of the loop condition appears at the end of the loop.
The iterations do not occur if, the The iteration occurs at least once even if
condition at the first iteration, appears the condition is false at the first iteration.
false.
Syntax : Syntax :
while ( condition) { do{
statements; //body of loop
} statements; // body of loop.

} while( Condition);
while loop can execute 0 to N times do-while loop executes 1 to N times.
Break & Continue Statement
• "break" statement is used inside loops to terminate a loop
and exit it (with a specific condition).
• In below example loop execution continues until
either num>=20 or entered score is negative.
while(num<20)
{
printf("Enter score: ");
scanf("%d",&scores[num]);
if(scores[num]<0)
break;
}
Break & Continue Statement ….
• Continue statement can be used in loops. Like break
command continue changes flow of a program.
• It does not terminate the loop however.
• It just skips the rest of current iteration of the loop and
returns to starting point of the loop.
Example:
while((ch=getchar())!='\n')
{
if(ch=='.')
continue;
putchar(ch);
}
Operators in C
• C language offers many types of operators.
They are,
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
ARITHMETIC OPERATORS IN C:

• C Arithmetic operators are used to perform mathematical


calculations like addition, subtraction, multiplication, division
and modulus in C programs.

Arithmetic Example
Operators/Operation

+ (Addition) A+B
– (Subtraction) A-B
* (multiplication) A*B
/ (Division) A/B
% (Modulus) A%B
EXAMPLE PROGRAM FOR C ARITHMETIC OPERATORS
int a=40, b=20, add, sub, mul, div, mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n", mul);
printf("Division of a, b is : %d\n", div);
printf("Modulus of a, b is : %d\n", mod);
ASSIGNMENT OPERATORS IN C

• In C programs, values for the variables are assigned using


assignment operators.
• There are 2 categories of assignment operators in C language.
• They are,
1. Simple assignment operator ( Example: = )
2. Compound assignment operators
( Example: +=, -=, *=, /=, %=, &=, ^= )
ASSIGNMENT OPERATORS IN C…..

Operators Example/Description
= sum = 10; 10 is assigned to variable sum

+= sum += 10; This is same as sum = sum + 10

-= sum -= 10; This is same as sum = sum – 10

*= sum *= 10; This is same as sum = sum * 10

/= sum /= 10; This is same as sum = sum / 10

%= sum %= 10; This is same as sum = sum % 10

&= sum&=10; This is same as sum = sum & 10

^= sum ^= 10; This is same as sum = sum ^ 10


RELATIONAL OPERATORS IN C

• Relational operators are used to find the relation between


two variables. i.e. to compare the values of two variables in a
C program.
Operators Example/Description

> x > y (x is greater than y)


< x < y (x is less than y)
>= x >= y (x is greater than or equal to y)
<= x <= y (x is less than or equal to y)
== x == y (x is equal to y)
!= x != y (x is not equal to y)
LOGICAL OPERATORS IN C
• These operators are used to perform logical operations on the given
expressions.
• There are 3 logical operators in C language. They are, logical AND (&&),
logical OR (||) and logical NOT (!).

Operators Example/Description
&& (logical (x>5)&&(y<5)
AND) It returns true when both conditions are true
|| (logical OR) (x>=10)||(y>=10)
It returns true when at-least one of the condition is true
! (logical NOT) !((x>5)&&(y<5))
It reverses the state of the operand “((x>5) && (y<5))”
If “((x>5) && (y<5))” is true, logical NOT operator makes
it false
BIT WISE OPERATORS IN C:

• These operators are used to perform bit operations. Decimal


values are converted into binary values which are the
sequence of bits and bit wise operators work on these bits.
• Bit wise operators in C language are :
• & (bitwise AND)
• | (bitwise OR)
• ~ (bitwise NOT)
• ^ (XOR)
• << (left shift) and
• >> (right shift)
TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:
CONDITIONAL OR TERNARY OPERATORS
IN C:
• Conditional operators return one value if
condition is true and returns another value is
condition is false.
• This operator is also called as ternary operator.
• Syntax : (Condition? true_value:
false_value);
• Example : (A > 100 ? 0 : 1);
• In above example, if A is greater than 100, 0 is
returned else 1 is returned. This is equal to if
else conditional statements.
Increment/decrement Operators

• Increment operators are used to increase the value of


the variable by one and decrement operators are used
to decrease the value of the variable by one in C
programs.
• Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
• Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
SPECIAL OPERATORS IN C:

• Below are some of the special operators that


the C programming language offers.
Operators Description
& This is used to get the address of the variable.
Example : &a will give address of a.
* This is used as pointer to a variable.
Example : * a where, * is pointer to the variable
a.
Sizeof () This gives the size of the variable.
Example : size of (char) will give us 1.
#include<stdio.h>
int main(){
int n,i,m=0,flag=0;
printf("Enter the number to check prime:");
scanf("%d",&n);
m=n/2;
for(i=2;i<=m;i++)
{
if(n%i==0)
{
printf("Number is not prime");
flag=1;
break;
}
}
if(flag==0)
printf("Number is prime");
return 0;
}

You might also like