Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

PROGRAMMING in C UNIT-2 notes

This document covers control structures in C programming, including decision statements like if and switch, loop control statements such as while, do-while, and for, as well as jump statements like break and continue. It also explains arrays, their types, and functions, detailing their declaration, calling, and definition. The document provides syntax examples and sample programs to illustrate the concepts discussed.

Uploaded by

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

PROGRAMMING in C UNIT-2 notes

This document covers control structures in C programming, including decision statements like if and switch, loop control statements such as while, do-while, and for, as well as jump statements like break and continue. It also explains arrays, their types, and functions, detailing their declaration, calling, and definition. The document provides syntax examples and sample programs to illustrate the concepts discussed.

Uploaded by

saksham2018 Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

UNIT-II

CONTROL STRUCTURES, ARRAYS, FUNCTIONS AND STRINGS

DECISION STATEMENTS
If statement:
Syntax :
if(expression) statement1;
Explanation :
 Expression is Boolean Expression
 It may have true or false value

Meaning of If Statement :
It Checks whether the given Expression is Boolean or not!
If Expression is True Then it executes the statement otherwise jumps to next instruction

CSE, MAIT
Sample Program Code :
void main()
{
int a=5,b=6,c;
c=a+b;
if (c==11)
printf("Execute me 1");
printf("Execute me 2");
}
Output :
Execute me1
If Statement:
if(conditional)
{
Statement No1
Statement No2
Statement No3
.
.
.
Statement No N
}
Note :
 More than One Conditions can be Written inside If statement.
1. Opening and Closing Braces are required only when ―Code after if statement occupies multiple
lines.
if(conditional) Statement No 1
Statement No2
Statement No3
In the above example only Statement 1 is a part of if Statement.
Code will be executed if condition statement is True.
Non-Zero Number Inside if means “TRUE Condition”

CSE, MAIT
if(100)
printf("True Condition");

if-else Statement :
We can use if-else statement in c programming so that we can check any condition and depending on
the outcome of the condition we can follow appropriate path. We have true path as well as false path.
Syntax :
if(expression)
{
statement1;
statement2;
}
else
{
statement1;
statement2;
}
next_statement;
Explanation :
If expression is True then Statement1 and Statement2 are executed Otherwise Statement3 and
Statement4 are executed.
Sample Program on if-else Statement :
void main()
{
int marks=50;
if(marks>=40)
{
printf("Student is Pass");
}
else
{

CSE, MAIT
printf("Student is Fail");
}
}
Output :
Student is Pass
Flowchart : If Else Statement

Consider Example 1 with Explanation: Consider Following Example –


int num = 20;
if(num = =20)
{
printf("True Block");
}
else
{
printf("False Block");
}
If part Executed if Condition Statement is True. if(num == 20)
{
printf("True Block");
}

CSE, MAIT
True Block will be executed if condition is True. Else Part executed if Condition Statement is False.
else
{
printf("False Block");
}
Consider Example 2 with Explanation :
More than One Conditions can be Written inside If statement.
int num1 = 20;
int num2 = 40;
if(num1 = = 20 && num2 = = 40)
{
printf("True Block");
}
Opening and Closing Braces are required only when Code after if statement occupies multiple lines.
Code will be executed if condition statement is True. Non-Zero Number Inside
if means “TRUE Condition”
If-Else Statement :
if(conditional)
{
//True code
}
else
{
//False code
}
Note :
Consider Following Example
int num = 20;
if(num = =20)
{
printf("True Block");
}

CSE, MAIT
else
{
printf("False Block");
}
If part Executed if Condition Statement is True. if(num == 20)
{
printf("True Block");
}
True Block will be executed if condition is True. Else Part executed if Condition Statement is False.
else
{
printf("False Block");
}
More than One Conditions can be Written inside If statement. int num1 = 20;
int num2 = 40;
if(num1 == 20 && num2 == 40)
{
printf("True Block");
}
Opening and Closing Braces are required only when ―Code‖ after if statement occupies multiple lines.
Code will be executed if condition statement is True. Non-Zero Number Inside if means “TRUE
Condition”

Switch statement
Why we should use Switch Case?
One of the classic problem encountered in nested if-else / else-if ladder is called problem of
Confusion.
It occurs when no matching else is available for if.
As the number of alternatives increases the Complexity of program increases drastically.
To overcome this, C Provide a multi-way decision statement called Switch Statement.

CSE, MAIT
See how difficult is this scenario?
if(Condition 1)
Statement 1 else
{
Statement 2
if(condition 2)
{
if(condition 3)
statement 3 else
if(condition 4)
{
statement 4
}
}
else
{
statement 5
}
}
First Look of Switch Case
switch(expression)
{
case value1 : body1 break;
case value2 : body2 break;
case value3 : body3 break;
default :
default-body break;
}
next-statement;
Flow Diagram:

CSE, MAIT
*Steps are Shown in Circles.
How it works?
Switch case checks the value of expression/variable against the list of case values and when
the match is found ,the block of statement associated with that case is executed
Expression should be Integer Expression / Character
Break statement takes control out of thecase.
Break Statement is Optional. #include<stdio.h>
void main()
{
int roll = 3 ; switch ( roll )
{
case 1:
printf ( " I am Pankaj "); break;
case 2:
printf ( " I am Nikhil "); break;
case 3:
printf ( " I am John "); break;
default :
printf ( "No student found"); break;
}
}
CSE, MAIT
As explained earlier –
3 is assigned to integer variable roll
On line 5 switch case decides – We have to execute block of code specified in 3rd case―.
Switch Case executes code from top to bottom.
It will now enter into first Case [i.e case 1:]
It will validate Case number with variable Roll. If no match found then it will jump to Next Case..
When it finds matching case it will execute block of code specified in that case.

LOOP CONTROL STATEMENTS


While statement:
While Loop Syntax:
initialization; while(condition)
{

incrementation;
}

Note :
For Single Line of Code – Opening and Closing braces are not needed. While (1) is used for Infinite

CSE, MAIT
Loop
Initialization , Incrementation and Condition steps are on different Line.

While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then and then only
code is executed ]
EXAMPLE:
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}
return 0;
}

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
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Do while:
Do-While Loop Syntax : initialization;

CSE, MAIT
do
{

incrementation;
}while(condition);

Note :
It is Exit Controlled Loop.
Initialization , Incrementation and Condition steps are on different Line.
It is also called Bottom Tested [i.e Condition is tested at bottom and Body has to execute at least once
]
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 < 20 );
return 0;
}

For statement:

CSE, MAIT
We have already seen the basics of Looping Statement in C. C Language provides us different kind of
looping statements such as For loop, while loop and do-while loop. In this chapter we will be learning
different flavors of for loop statement.

Different Ways of Using For Loop in C Programming


In order to do certain actions multiple times, we use loop control statements. For loop can be
implemented in different verities of using for loop –
 Single Statement inside For Loop
 Multiple Statements inside ForLoop
 No Statement inside For Loop
 Semicolon at the end of For Loop
 Multiple Initialization Statement inside For
 Missing Initialization in For Loop
 Missing Increment/Decrement Statement
 Infinite For Loop
 Condition with no Conditional Operator.

Way 1 : Single Statement inside For Loop


for(i=0;i<5;i++)
printf("Hello");

CSE, MAIT
Above code snippet will print Hello word 5 times. We have single statement inside for loop body.
No need to wrap printf inside opening and closing curly block. Curly Block is Optional.

Way2: Multiple Statements inside For Loop


for(i=0;i<5;i++)
{
printf("Statement1");
printf("Statement2");
printf("Statement3");

if(condition)
{

}
}
If we have block of code that is to be executed multiple times then we can use curly braces to wrap
multiple statement in for loop.
Way 3 : No Statement inside For Loop
for(i=0;i<5;i++)
{

}
This is body less for loop. It is used to increment value of ―i. This verity of for loop is not used
generally.
At the end of above for loop value of i will be 5.

Way4: Semicolon at the end of For Loop


for(i=0;i<5;i++);
Generally beginners thought that , we will get compile error if we write semicolon at the end of for
loop.

CSE, MAIT
This is perfectly legal statement in C Programming. This statement is similar to bodyless for loop.
(Way 3)

Way5: Multiple Initialization Statement inside For


for(i=0,j=0;i<5;i++)
{
statement1; statement2; statement3;
}
Multiple initialization statements must be seperated by Comma in for loop.

Way6: Missing I ncrement/Decrement Statement


for(i=0;i<5;)
{
statement1; statement2; statement3; i++;
}
however we have to explicitly alter the value i in the loop body.

Way7:Missing InitializationinFor Loop


i = 0;
for(;i<5;i++)
{
statement1; statement2; statement3;
}
we have to set value of i‘ before entering in the loop otherwise it will take garbage value of i‘.

Way8:Infinite For Loop


i = 0;
for(;;)
{

CSE, MAIT
statement1; statement2; statement3;
if(breaking condition) break;
i++;
}

Infinite for loop must have breaking condition in order to break for loop. otherwise it will cause
overflow of stack.

Summary of Different Ways of Implementing For Loop

Form Comment

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


Statement1; Single Statement

for ( i=0 ;i <10; i++) Multiple Statements within for


{
Statement1; Statement2;
Statement3;
}
for ( i=0 ; i < 10;i++) ; For Loop with no Body (Carefully Look at the
Semicolon)
for Multiple initialization & Multiple

(i=0,j=0;i<100;i++,j++) Update Statements Separated by Comma


Statement1;
for ( ; i<10 ; i++) Initialization not used

for ( ; i<10 ; ) Initialization & Update not used

for ( ; ; ) Infinite Loop, Never Terminates

CSE, MAIT
JUMP STATEMENTS:

Break statement
Break Statement Simply Terminate Loop and takes control out of the loop.

Break in For Loop :


for(initialization ; condition ; incrementation)
{
Statement1; Statement2; break;
}

Break in While Loop :


initialization ; while(condition)
{
Statement1; Statement2; incrementation break;
}

Break Statement in Do-While :


initialization ; do
{
Statement1; Statement2; incrementation break;
}while(condition);
Way 1 : Do-While Loop

CSE, MAIT
Way 2 : Nested for

Way 3 : For Loop

CSE, MAIT
Way 4 : While Loop

Continue statement:
loop
{
continue;
//code
}

Note :
It is used for skipping part of Loop.
Continue causes the remaining code inside a loop block to be skipped and causes execution to jump to
the top of the loop block

Loop Use of Continue !!

for

CSE, MAIT
while

do-while

Goto statement:

goto label;

label :

Whenever goto keyword encountered then it causes the program to continue on the line , so long as it
is in the scope .

Types of Goto Forward Backward

CSE, MAIT
ARRAYS:

What is an array?
An array is a collection of similar datatype that are used to allocate memory in a sequential manner.
Syntax : <data type><array name>[<size of an array>]
Subscript or indexing: A subscript is property of an array that distinguishes all its stored elements
because all the elements in an array having the same name (i.e. the array name). so to distinguish
these, we use subscripting or indexing option.
e.g. int ar[20];
First element will be: int ar[0]; Second element will be: int ar[1]; Third element will be: int ar[2];
Fourth element will be: int ar[3]; Fifth element will be: int ar[4]; Sixth element will be: int ar[5]; So
on……………………
Last element will be: int ar[19];
NOTE: An array always starts from 0 indexing.
Example: int ar[20];
This above array will store 20 integer type values from 0 to 19. Advantage of an array:
Multiple elements are stored under a single unit.
Searching is fast because all the elements are stored in a sequence.

Types of Array

CSE, MAIT
 Static Array
 DynamicArray.

Static Array
An array with fixed size is said to be a static array. Types of static array:
One Dimensional Array
Two Dimensional Array.
Multi Dimensional Array.

One Dimensional Array


An Array of elements is called 1 dimensional, which stores data in column or row form. Example: int
ar[5];
This above array is called one dimensional array because it will store all the elements in column or in
row form

Two DimensionalArray.
An array of an array is said to be 2 dimensional array , which stores data in column and row form
Example: int ar[4][5];
This above array is called two dimensional array because it will store all the elements in column and
in row form
NOTE: In above example of two dimensional array, we have 4 rows and 5 columns. NOTE: In above
example of two dimensional array, we have total of 20 elements.

Dynamic Array.
This type of array also does not exist in c and c++. Example: Program based upon array:
Question: WAP to store marks in 5 subjects for a student. Display marks in 2nd and 5thsubject.
#include<stdio.h>
#include<conio.h> void main()
{
int ar[5]; int i;
for(i=0;i<5;i++)

CSE, MAIT
{
printf(\n Enter marks in ,i, subject);
scanf(%d,&ar[i]);
}
printf(Marks in 2ndsubject is:,ar[1]);
printf(Marks in 5thsubject is:,ar[4]);
}

FUNCTIONS:

A function is itself a block of code which can solve simple or complex task/calculations.
A function performs calculations on the data provided to it is called "parameter" or "argument". A
function always returns single value result.

Types of function:
Built in functions (Library functions)
a.) Inputting Functions.
b.) Outputting functions.

User defined functions.


a.)fact();
b.) sum();

Parts of a function:
 Function declaration/Prototype/Syntax.
 Function Calling.
 Function Definition.

CSE, MAIT
1.)Function Declaration:
Syntax: <return type ><function name>(<type of argument>)
The declaration of function name, its argument and return type is called function declaration.

2.) Function Calling:


The process of calling a function for processing is called function calling. Syntax:
<var_name>=<function_name>(<list of arguments>).

3.) Function definition:


The process of writing a code for performing any specific task is called function defination. Syntax:
<return type><function name>(<type of arguments>)
{
<statement-1>
<statement-2>
return(<vlaue>)
}
Example: program based upon function:
WAP to compute cube of a no. using function.
#include<stdio.h>
#include<conio.h>
void main()
{
int c,n;
int cube(int);
printf("Enter a no.");
scanf("%d",&n);
c=cube(n);
printf("cube of a no. is=%d",c);
}

CSE, MAIT
int cube(int n)
{
Int c=n*n*n; return(c);
}

WAP to compute factorial of a no. using function:


#include<stdio.h>
#include<conio.h>
void main()
{
int n,f=1;
int fact(int);
printf("Enter a no.");

scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
}
int fact(int n);
int f=1;
{
for(int i=n;i>=n;i--)
{
f=f*i;
}
return(f);
}

Recursion
Firstly, what is nested function?
When a function invokes another function then it is called nested function. But,
When a function invokes itself then it is called recursion.
NOTE: In recursion, we must include a terminating condition so that it won't execute to infinite time.

CSE, MAIT
Example: program based upon recursion:
WAP to compute factorial of a no. using Recursion:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,f;
int fact(int) ;
printf("Enter a no.");
scanf("%d",&n);
f=fact(n);
printf("The factorial of a no. is:=%d",f);
}

int fact(int n)
int f=1;
{
if(n=0)
return(f);
else
return(n*fact(n-1));
}
Passing parameters to a function:
Firstly, what are parameters?
parameters are the values that are passed to a function for processing.

There are 2 types of parameters:


a.) Actual Parameters. b.) Formal Parameters.

a.) ActualParameters:
These are the parameters which are used in main() function for function calling. Syntax: <variable
CSE, MAIT
name>=<function name><actual argument>
Example: f=fact(n);
b.) Formal Parameters.
These are the parameters which are used in function defination for processing.
Methods of parameters passing:
1.) Call by reference. 2.) Call by value.
1.) Call by reference:
In this method of parameter passing , original values of variables are passed from calling program to
function.
Thus,
Any change made in the function can be reflected back to the calling program.

2.) Call by value.


In this method of parameter passing, duplicate values of parameters are passed from calling program
to function defination.
Thus,
Any change made in function would not be reflected back to the calling program.

Example: Program based upon call by value:


# include<stdio.h>
# include<conio.h>
void main()
{
int a,b;
a=10; b=20;
void swap(int,int);
printf("The value of a before swapping=%d",a);
printf("The value of b beforeswapping=%d",b);
void swap(a,b);
printf("The value of a after swapping=%d",a);
printf("The value of b after swapping=%d",b);

CSE, MAIT
}
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
}

STORAGE CLASSES
Every Variable in a program has memory associated with it.
Memory Requirement of Variables is different for different types of variables. In C, Memory is
allocated & released at different places
Term Definition

Scope Region or Part of Program in which Variable is accessible

Extent Period of time during which memory is associated with variable

Storage Class Manner in which memory is allocated by the Compiler for Variable
Different Storage Classes

Storage class of variable Determines following things


Where the variable is stored Scope of Variable
Default initial value Lifetime of variable

Where the variable is stored:


Storage Class determines the location of variable, where it is declared. Variables declared with auto

CSE, MAIT
storage classes are declared inside main memory whereas variables declared with keyword register are
stored inside the CPU Register.
Scope of Variable
Scope of Variable tells compile about the visibility of Variable in the block. Variable may have Block
Scope, Local Scope and External Scope. A scope is the context within a computer program in which a
variable name or other identifier is valid and can be used, or within which a declaration has effect.
Default Initial Value of the Variable
Whenever we declare a Variable in C, garbage value is assigned to the variable. Garbage Value may
be considered as initial value of the variable. C Programming have different storage classes which has
different initial values such as Global Variable have Initial Value as 0 while the Local auto variable
have default initial garbage value.

Lifetime of variable
Lifetime of the = Time Of variable Declaration - Time of Variable Destruction
Suppose we have declared variable inside main function then variable will be destroyed only when the
control comes out of the main .i.e end of the program.

Different Storage Classes:


 Auto Storage Class
 Static Storage Class
 Extern Storage Class
 Register Storage Class

Automatic (Auto) storage class


This is default storage class
All variables declared are of type Auto by default
In order to Explicit declaration of variable use ‘auto’ keyword auto int num1 ; // Explicit Declaration
Features:

Storage Memory

CSE, MAIT
Scope Local / Block Scope

Life time Exists as long as Control remains in the block

Default initial Value Garbage

Example
void main()
{
auto mum = 20 ;
{

auto num = 60 ;
printf("nNum : %d",num);
}
printf("nNum : %d",num);
}

Output :
Num :60
Num :20

Note :
Two variables are declared in different blocks , so they are treated as different variables
External ( extern ) storage class in C Programming
Variables of this storage class are Global variables
Global Variables are declared outside the function and are accessible to all functions in the program
Generally , External variables are declared again in the function using keyword extern In order to
Explicit declaration of variable use ‘extern’ keyword
extern int num1 ; // Explicit Declaration
CSE, MAIT
Features :
Storage Memory

Scope Global / File Scope

Life time Exists as long as variable is running


Retains value within the function

Default initial Value Zero

Example
int num = 75 ;
void display();

void main()
{
extern int num ;
printf("nNum : %d",num);
display();
}
void display()
{
extern int num ;
printf("nNum : %d",num);
}

Output :
Num :75
Num :75

Note :
Declaration within the function indicates that the function uses external variable
CSE, MAIT
Functions belonging to same source code , does not require declaration (no need to write extern) If
variable is defined outside the source code , then declaration using extern keyword is required

Static Storage Class


The static storage class instructs the compiler to keep a local variable in existence during the life-time
of the program instead of creating and destroying it each time it comes into and goes out of scope.
Therefore, making local variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable's
scope to be restricted to the file in which it is declared.
In C programming, when static is used on a class data member, it causes only one copy of that
member to be shared by all the objects of its class.

#include <stdio.h>

/* function declaration */ void func(void);

static int count = 5; /* global variable */ main() {


while(count--) {
func();
}

return0;
}

/* function definition */ void func( void ) {

static int i = 5; /* local static variable */


i++;

printf("i is %d and count is %d\n", i, count);


}
When the above code is compiled and executed, it produces the following result − i is 6 and count is 4
i is 7 and count is 3 i is 8 and count is 2 i is 9 and count is 1 i is 10 and count is 0
CSE, MAIT
Register Storage Class
register keyword is used to define local variable. Local variable are stored in register instead of RAM.
As variable is stored in register, the Maximum size of variable = Maximum Size of
Register unary operator [&] is not associated with it because Value is not stored in RAM
instead it is stored in Register.
This is generally used for faster access. Common use is ―Counter―
Syntax
{
register int count;
}
Register storage classes example
#include<stdio.h>
int main()
{

int num1,num2;
register int sum;

printf("\n Enter the Number 1 : ");


scanf("%d",&num1);
printf("\n Enter the Number 2 : ");
scanf("%d",&num2);
sum = num1 +num2;

printf("\nSum of Numbers : %d",sum);

return(0);
}
Explanation of program
Refer below animation which depicts the register storage classes –

CSE, MAIT
In the above program we have declared two variables num1,num2. These two variables are stored in
RAM.
Another variable is declared which is stored in register variable. Register variables are stored in the
register of the microprocessor. Thus memory access will be faster than other variables.
If we try to declare more register variables then it can treat variables as Auto storage variables as
memory of microprocessor is fixed and limited.

Why we need Register Variable ?


Whenever we declare any variable inside C Program then memory will be randomly allocated at
particular memory location.
We have to keep track of that memory location. We need to access value at that memory location
using ampersand operator/Address Operator ie (&).
If we store same variable in the register memory then we can access that memory location directly
without using the Address operator.
Register variable will be accessed faster than the normal variable thus increasing the operation and
program execution. Generally we use register variable as Counter.
Note : It is not applicable for arrays, structures or pointers.
Summary of register Storage class

Keyword Register

Storage Location CPU Register

Keyword Register

Initial Value Garbage

CSE, MAIT
Life Local to the block in which variable is declared.

Scope Local to the block.

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 language offers.

S.no Preprocessor Syntax Description

This macro defines


constant value and can be
any of the basic data
types.

1 Macro #define
The source code of the
file ―file_name‖ is
included in the main
program at the specified
place
Header file #include
inclusion <file_name>
2

CSE, MAIT
Set of commands are
included or excluded in
source program before
compilation with respect
#ifdef, #endif, #if,
to the condition
#else,#ifndef
Conditional
compilation
3
#undef is used to
undefine a defined
macro variable.
#Pragma is used to
call a function before
and after main
Other function in a C
4 directives #undef, #pragma program

A program in C language involves into different processes. Below diagram will help you to
understand all the processes that a C program comes across.

EXAMPLE PROGRAM FOR #DEFINE, #INCLUDE PREPROCESSORS IN C:


#define – This macro defines constant value and can be any of the basic data types.
#include<file_name>– The source code of the file ―file_name‖ is included in the main C program
where ―#include <file_name> is mentioned.
#include <stdio.h> #define height 100
#define number 3.14 #define letter 'A'
#define letter_sequence "ABC" #define backslash_char '\?'

void main()
{
printf("value of height : %d \n", height ); printf("value of number : %f \n", number ); printf("value of
letter : %c \n", letter );

CSE, MAIT
printf("value of letter_sequence : %s \n", letter_sequence); printf("value of backslash_char : %c \n",
backslash_char);

} OUTPUT:

value of height : 100


value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?

EXAMPLE PROGRAM FOR CONDITIONAL COMPILATIONDIRECTIVES:


EXAMPLE PROGRAM FOR #IFDEF, #ELSE AND #ENDIF INC:
#ifdef directive checks whether particular macro is defined or not. If it is defined, ―If clause
statements are included in source file.
Otherwise, ―else clause statements are included in source file for compilation and execution.

#include <stdio.h> #define RAJU 100

int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \ "this C file\n");
#else
printf("RAJU is not defined\n"); #endif
return0;
}
OUTPUT:

RAJU is defined. So, this line will be added in this C file

CSE, MAIT
EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF INC:
#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, ―If clause
statements are included in source file.
Otherwise, else clause statements are included in source file for compilation and execution.

#include <stdio.h> #define RAJU 100


int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \ "define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program‖);
#endif return0;
}

OUTPUT:

SELVA is not defined. So, now we are going to define here

EXAMPLE PROGRAM FOR #IF, #ELSE AND #ENDIF INC:


―If clause statement is included in source file if given condition is true.
Otherwise, else clause statement is included in source file for compilation and execution.

#include <stdio.h> #define a 100


int main()
{
#if (a==100)
printf("This line will be added in this C file since " \ "a \= 100\n");
#else
CSE, MAIT
printf("This line will be added in this C file since " \ "a is not equal to 100\n");
#endif return0;
}

OUTPUT:

This line will be added in this C file since a = 100

EXAMPLE PROGRAM FOR UNDEF IN C:


This directive undefines existing macro in the program. #include <stdio.h>
#define height 100 void main()
{
printf("First defined value for height : %d\n",height);
#undefheight // undefiningvariable
#defineheight600 // redefining the same for new value printf("value of height after undef
\&redefine:%d",height);
}

OUTPUT:

First defined value for height : 100


value of height after undef & redefine : 600

EXAMPLE PROGRAM FOR PRAGMA IN C:


Pragma is used to call a function before and after main function in a C program. #include <stdio.h>
void function1( ); void function2( );

#pragma startup function1 #pragma exit function2

int main()
{
printf ( "\n Now we are in main function" ); return0;

CSE, MAIT
}

void function1( )
{
printf("\nFunction1 is called before main function call");
}

void function2( )
{
printf ( "\nFunction2 is called just before end of " \ "main function" ) ;"
}

OUTPUT:

Function1 is called before main function call


Now we are in main function
Function2 is called just before end of main function

MORE ON PRAGMA DIRECTIVE IN C:

S.no Pragma command Description

#Pragma startup This directive executes function named


1 <function_name_1> ―function_name_1‖ before

This directive executes function named


#Pragma exit ―function_name_2‖ just before
<function_name_2> termination of the program.

CSE, MAIT
If function doesn‘t return a value, then
warnings are suppressed by this
directive while compiling.

3 #pragma warn – rvl


If function doesn‘t use passed function
parameter , then warnings are
suppressed

4 #pragma warn – par


If a non reachable code is written
inside a program, such warnings are
suppressed by this directive.

5 #pragma warn – rch

STRINGS
What is String?
A string is a collection of characters.
A string is also called as an array of characters.
A String must access by %s access specifier in c andc++.
A string is always terminated with \0 (Null) character.

Example of string:
A string always recognized in double quotes.
A string also consider space as acharacter.
Example: Priyank Saxena
The above string contains 14 characters.
Example: Char ar[20]
The above example will store 19 character with 1 null character. Example: Program based
upon String.
WAP to accept a complete string (first name and last name) and display hello message in the
output.
CSE, MAIT
# include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char str1[20];
char str2[20];
printf(“Enter First Name”);
scanf(“%s”,&str1);
printf(“Enter last Name”);
scanf(“%s”,&str2);
puts(str1);
puts(str2);
}

Character Library Functions:

“ctype.h” header file support all the below functions in C language. Click on each function name
below for detail description and example programs.

Functions Description

isalpha() checks whether character is alphabetic

isdigit() checks whether character is digit

CSE, MAIT
isalnum() Checks whether character is alphanumeric

isspace() Checks whether character is space

islower() Checks whether character is lower case

isupper() Checks whether character is upper case

isxdigit() Checks whether character is hexadecimal

iscntrl() Checks whether character is a control character

isprint() Checks whether character is a printable character

ispunct() Checks whether character is a punctuation

isgraph() Checks whether character is a graphical character

tolower() Checks whether character is alphabetic & converts to lower case

toupper() Checks whether character is alphabetic & converts to upper case

String Functions in C:
Our c language provides us lot of string functions for manipulating the string. All the string functions
are available in string.h header file.

These String functions are:


 strlen()
 strupr()
 strlwr()

CSE, MAIT
 strcmp()
 strcat()
 strcpy()
 strrev()

strlen()
This string function is basically used for the purpose of computing the ength of string.

Example: char str “Gaurav Arora”;


int length= strlen(str);
printf(The length of the string is =,str);

strupr()
This string function is basically used for the purpose of converting the case sensitiveness of the string
i.e. it converts string case sensitiveness into uppercase.

Example: char str=―gaurav


strupr(str);
printf(The uppercase of the string is :%s,str);

strlwr()
This string function is basically used for the purpose of converting the case sensitiveness of the string
i.e it converts string case sensitiveness into lowercase.

Example: char str=―gaurav


strlwr(str);
printf(The Lowercase of the string is:%s ,str);

CSE, MAIT
strcmp()
This string function is basically used for the purpose of comparing two string. This string function
compares two strings character by characters.
Thus it gives result in three cases:
Case 1: if first string > than second string then, result will be true.
Case 2: if first string < than second string then, result will be false.
Case 3: if first string = = to second string then, result will be zero.

Example:
char str1=―Gaurav;
char str2=―Arora;
char str3=strcmp(str1,str2);
printf(―%s,str3);

strcat()
This string function is used for the purpose of concatenating two strings ie.(merging two or more
strings)

Example:
char str1 = ―Gaurav;
char str2 = ―Arora;
char str3[30];
str3=strcat(str1,str2);
printf(%s,str3);

strcpy()
This string function is basically used for the purpose of copying one string into another string. char
str1= ―Gaurav;

CSE, MAIT
char str2[20];
str2 = strcpy(str2,str1);
printf(%s,str2);

strrev()
This string function is basically used for the purpose of reversing the string.
char str1= ―Gaurav;
char str2[20];
str2= strrev(str2,str1);
printf(%s,str2);

Example: Program based upon string functions.


WAP to accept a string and perform various operations:
To convert string into uppercase.
To reverse the string.
To copy string into another string.
To compute length depending upon user choice.
# include<stdio.h>
# include<conio.h>
#include<string.h>
void main()
{
char str[20];
char str1[20];
int opt,len;
printf(\n MAIN MENU‖);
printf(\n 1. Convert string into uppercase‖);

printf(\n 2. Reverse the string‖);


printf(\n 3. Copy one string into another string‖);
printf(\n 4.Compute length of string‖);
printf(Enter string‖);

CSE, MAIT
scanf(%s, &str);
printf(Enter your choice);
scanf(%d,&opt);
switch(opt)
{
case1: strupr(str);
printf(The string in uppercase is :%s ,str);
break;

case2:
strrev(str);
printf(―The reverse of string is : %s‖,str); break;
case3: strcpy(str1,str);
printf(―New copied string is : %s‖,str1); break;
case4: len=strlen(str);
printf(―The length of the string is : %s‖,len); break;
default: printf(―Ypuhave entered awrongchoice.‖);
}

CSE, MAIT

You might also like