Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

UNIT I

BASICS OF C PROGRAMMING

Introduction to programming paradigms - Structure of C program - C programming: Data


Types -Storage classes - Constants - Enumeration Constants - Keywords - Operators:
Precedence and Associativity - Expressions - Input/ Output statements, Assignment
statements - Decision making statements - Switch statement - Looping statements
- Pre-processor directives - Compilation process

PART A
1. What is external storage class? [APR/MAY 2018]
An external variable definition must be defined outside the functions. That
access the external variables and usually before the function definitions. The
external variables can be accessed from the point of its definition to any within
the program.
An external variable declaration must begin with the storage class
specified extern.
2. How does the preprocessor work? [APR/MAY 2018]
Preprocessor is a program that processes the source code before it passes
through the compiler. This is known as preprocessor.
 It operates under the control of preprocessor command lines or directives.
 Preprocessor directives are placed in the source program before the main
line.
 Before the source code passes through the compiler, it is examined by the
preprocessor for any preprocessor directives.
 Preprocessor directives begin with the symbol # in column and do not
require a semicolon at the end.

3. Why C is called middle level language?


C is relatively low level or middle level language because it supports the
assembly language programming.
4. Mention some limitation of C language?
 Non uniformity in associativity.
 Wrong precedence for some operators.
 Usage of the same operator for multiple purpose.
 No direct input and output facility.
5. What is a local variable?
A local variable is a variable that is declared inside all the functions. Its value is
used only within the function.
6. What is global variable?
A global variable is a variable that is declared outside the main function. It is
used anywhere in the program.
7. What is Enumerated data type?
A enumerate data type is a set of values represented by identifiers called
enumeration constants. It is an user definied data type.
enum name {number 1, number 2, ......,number n};
8. Define type definition?
Type definition that allows user to define an identifier that would represent a data
type using an existing data type.
Syntax:
typedef type identifier;
typedef <existing_data_type> <new_user_define_data_type>;

9. What is mean by constants?


Constants are fixed values and they remain unchanged during the execution of
the program.
 Numeric constant
 Character constant
 String constant
10. What is Enumeration constant?
Enumeration constant enable you to create new types and then to define
variables of those types whose whose values are restricted to a set of possible
values.
enum COLOR { RED, BLUE, GREEN, WHITE, BLACK };
11. Define variables?
Variables are identifiers whose values change during the execution of the
program. Variable specify the name and type of information. Compiler allocates
memory for a particular variable based on the type
12. Mention the user-defined datatypes available in C?
1. Structures
2. Unions
3. Enumerated data type
4. Type definition
13. Define Sizeof operator and Ampersand operator?
The sizeof operator is not a library function but a keyword, which returns the
sizeof the operand in bytes. The Sizeof operator always procedes its operand.
The ampersand operator ‘&’ prints the address of the variable in the memory.
14. What is mean by expression?
An expression is a combination of variables and constants that are connected
with operator.
15. What is meant by Typecasting?
In arithmetic operations, the right hand side expression is computed and the
result is assigned to the left hand side variable. If the operands on both sides
have the same data type, it is called single or simple mode in C. If the operands
are of different data types, it is called mixed mode. In mixed mode, before
execution, the operands are converted into the same data types. This is called
type conversion or casting.
16. Write about the operator precedence.
 The operators within C are grouped hierarchically according to their
precedence (i.e., their order of evaluation).
 Operations with a higher precedence are carried out before operations
having a lower precedence.
 Amongst arithmetic operators * and / have precedence over + and -.
17. Define expression and compound statements.
An Expression statement consists of an expression followed by a semicolon.
When this is executed, the expression gets evaluated. An assignment statement
is a type of expression statement.
A Compound statement consists of several individual statements enclosed within
a pair of braces { }. The individual statements can be either expression
statements, compound statements and / or control statements. A compound
statement does not end with a semicolon.
18. Define assignment statement.
An assignment “statement” is not really a statement, but it is an expression. The
value of the expression is the value that is assigned to the variable.
Syntax:
variable = expression;
where variable must be declared

19. Define loop?


A loop is defined as a block of statements which are repeatedly executed for
certain number of times. The “C” language supports three types of loop
statements.
 for statement
 while statement
 do-while statement
20. State the purpose of break and continue statement.
The break statement is used to terminates the execution of the loop and the
control is transferred to the statement immediately following the loop.
Syntax:
break;
The continue statement is used to transfer the control to the beginning of the
loop. The loop does not terminate when a continue statement is encountered.
Syntax:
continue;
21. What is the purpose of goto statement?
The goto statement is used to alter the normal sequence of the program
execution by unconditionally transferring the control to some other part of the
program
Syntax:
goto label;
22. Define pre-processor. Mention the categories of pre-processor directives?
It process our source program before it if passed to the compiler.
 Macro substitution directives
 File inclusion directives
 Compiler control directives
23. What are the different forms of macro substitution?
 Simple macro substitution
 Argument macro substitution
 Nested macro substitution
24. When conditional compilation is useful?
Conditional compilation enables the programmer to control the execution of pre-
processor directives and the compilation directives #if, #else, #endif etc.,
25. What is file inclusion?
An external file containing functions or macro definition can be included as a part
of a program so that we need rewrite those function or macro definitions. This is
achieved by the pre-processor directive.
#include “filename”
PART B
1. Explain the different types of operators used in C with necessary program.
[APR/MAY 2018] (OR) Discuss about the C operators?
Operator is a symbol that is used to perform some operation between the
operands. Eg: a +b
Operator is appearing in between operands
Types of operators:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Comma operators

Arithmetic operators:

There are two types of arithmetic operators.

 Binary operators
 Unary operators

Binary operators:

It was commonly used in most of the computer programming languages.


These operators are performed with two operands, so they are called as binary
arithmetic operators.

operator meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo operation

Example program:

#include<stdio.h>

#include<conio.h>

void main()

int a=5, b=2;

clrscr();

printf(“\n Addition=%d”,a+b);

printf(“\n Subtraction=%d”,a-b);

printf(“\n Multiplication=%d”,a*b);

printf(“\n Division=%d”,a/b);

printf(“\n Modulo=%d”,a%b);

getch();

Unary operator:

The operators that acts upon a single operand to produce a new value are
called as unary operators. Unary operators usually precede its operands, though
some unary operators are written after their operators.

+ Unary plus
- Unary minus
++ Increment
-- Decrement
sizeof Return the size of the operand
& Address operator

Example:

++x pre-increment operation

x++ post-increment operation

--x pre-decrement operation

x-- post-decrement operation

sizeof operator

The sizeof operator is not a library function but a keyword, which returns
the sizeof the operand in bytes. The Sizeof operator always procedes its
operand.

Expression Result
sizeof(char) 1
sizeof(int) 2
sizeof(float) 4
sizeof(double) 8

Ampersand operator
The ampersand operator ‘&’ prints the address of the variable in the memory.

Relational operators:
Relational operators are symbols that are used to test the relationship
between two variables or between a variable and a constant.
operator meaning
< less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== equal to
!= Not equal to

Example:

#include <stdio.h>
main() /* Program introduces the for statement, counts to ten */
{
int count;

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


printf("%d ", count );
printf("\n");
}

Logical Operator:
Operators which are used to combine two or more relational operations
called logical operators. These operators are used to test more than one
condition at a time.
Operators Meaning
&& Logical AND
|| Logical OR
! Logical NOT
#include <stdio.h>
main()
{
int number;
int valid = 0;
while( valid == 0 )
{
printf("Enter a number between 1 and 10 -->");
scanf("%d", &number);
if( (number < 1 ) || (number > 10) )
{
printf("Number is outside range 1-10. Please re-enter\n");
valid = 0;
}
else valid = 1;
}
printf("The number is %d\n", number );
}

Assignment operator:
Assignment operators are used to assign the result of an expression to a
variable. The equal(=) sign is used as an assignment operator. It is used to form
an assignment expression, which assigns the value of an expression to an
identifier which may be written in the form of

identifier= expression

Where identifier generally represents a variable and expression


represents a constant or a variable or a complex expression. The value valuated
from the expression is stored in the identifier.
Example:

1. a=10; /* 100 is assigned to a*/


2. b=50; /* 50 is assigned to b */
3. w=x+y; /* the value of x and y after summation are stored in w */

Short hand assignment operators

C has a set of short hand assignment operators

identifier <arithmetic operator>=expression;

they are called as Component assignment operators

Simple assignment operators Shorthand assignment operators


x=x+1 x+=1
y=y-1 y-=1
z=z*(x+y) z*=(x+y)
y=y/(x+y) y/=(x+y)
x=x%z x%=z

Increment and Decrement operator:

1. increment (++)
2. decrement (--)

Operator meaning
++x pre-increment operation
x++ post-increment operation
--x pre-decrement operation
x-- post-decrement operation
Conditional operator:

Conditional operators itself check the condition and executes the


statement depending upon the condition. It also known as ternary operator.

Syntax:

Condition ? expression1: expression2;

“? :” operator act as a ternary operator

It first evaluated the condition

If it is true then expression1 is evaluated.

If it if false then expression2 is evaluated.

Bitwise operator:

Bitwise operator is used to manipulate the date at bit level. It operates only
integers.

Operator Meaning
~ One’s Complement
<< Left Shift
>> Right Shift
& Bitwise AND
| Bitwise OR
^ Bitwise XOR

The one’s complement operator (~) is an unary operator which causes the
bits of the operand to be instead. ie., one’s become zero’s and zero’s
become one’s.
Program:

#include<stdio.h>

void main()

int a;

printf(“enter the value of a”);

scanf(“%d”,&a);

printrf(“\n the one’s complement value for a is : %d ”, ~a);

getch();

Comma operator:

The comma operator is used to separate two or more expressions. The


comma operator has the lowest priority among all the operators. It is not
essential to enclose the expression with comma operators within parenthesis.

Example:

a=2, b=5, c=a+b;

(a=2, b=5, c=a+b);

2. Write a C program to check the integer is Palindrome or not. [APR/MAY


2018]

#include <stdio.h>

void main()

{
int n, reverse = 0, t;

printf("Enter a number to check if it is a palindrome or not\n");

scanf("%d", &n);

t = n;

while (t != 0)

reverse = reverse * 10;

reverse = reverse + t%10;

t = t/10;

if (n == reverse)

printf("%d is a palindrome number.\n", n);

else

printf("%d isn't a palindrome number.\n", n);

return 0;

3. Describe the decision making statements and looping statements in C with


an example. [APR/MAY 2018] (OR) Explain about the decision making or
branching statements?

C has some kind of statements that permit the execution of a single statement ,
or a block of statements, based on the value of a conditional expression or selection
among several statements based on the value of a conditional expression or a
control variable.
i) if statement
ii) if-else statement
iii) nested if-else statement
iv) if else-if statement
v) switch case statement
i) if statement:
It is also known as one-way decisions. It is used to control the flow of
execution of the statements. The decision is based on a “test expression
or condition” that evaluates to either true or false.
 If the test condition is true, the corresponding statement is
executed.
 If the test condition is false, control goes to the next executable
statement.

Syntax:

if(expression)

block of statements;

}
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// Test expression is true if number is less than 0
if (number < 0)
{
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}

Output 1

Enter an integer: -2
You entered -2.
The if statement is easy.

Output 2

Enter an integer: 5
The if statement is easy.

ii) if –else statement:


SYNTAX:
if(expression)
{
block of statement1;
}
else
{
Block of statement2;
}

If the expression is true the block of statement1 will be executed, otherwise,


the block of statement2 will be executed.

#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}

Output

Enter an integer: 7
7 is an odd integer.

iii) Nested if:

SYNTAX:
if(expression1)
{
statement1:
}
else
{
If(expression2)
{
satatement2;
}
else
{
statement3;
}
}

In this statement, if expression1 is true, then statement1 is evaluated,


otherwise the inner if expression2 is true then the statement2 will be executed
otherwise inner else statement3 will be executed.
Flowchart:

// Program to relate two integers using =, > or <

#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if two integers are equal.


if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}

//checks if number1 is greater than number2.


else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}

// if both test expression is false


else
{
printf("Result: %d < %d",number1, number2);
}

return 0;
}

Output

Enter two integers: 12


23
Result: 12 < 23

iv) if else-if:

SYANTAX:
if(expression1)
{
statement1;
}
else if(expression2)
{
statement2;
}
else if(expression3)
{
Statement3;
}
else
{
statement4;
}

In this statement , if the expression1 is true, statement1 will be executed, otherwise


the expression2 is evaluated, if it is true then the statement2 is executed, otherwise the
expression3 is evaluated, if it is true then the statement3 is executed. Otherwise
statement4 is executed.

Flowchart:
Program:
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2\n");
}
else if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else if (var2 > var1)
{
printf("var2 is greater than var1\n");
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}

Output:

Input the value of var1:12


Input the value of var2:21
var1 is not equal to var2

v) switch case:
SYNTAX:
switch<exprn>
{
case 0:
{
statement ;
break;
}
case 1:
{
statement ;
break;
}
case 2:
{
statement ;
break;
}
case n:
{
statement ;
break;
}
default:
{
statement;
break;
}
}
The switch() case statement is like the if statement that allows us to make the
decision from a number of choices. The switch statements require only one
argument of any data type, which is checked with a number of case options.
The switch statement evaluates the expression and then looks for its value
among the case constants. If the value matches with a case constant, this
particular case statement is executed. If not, the default is executed .

Example:
// Program to create a simple calculator
// Performs addition, subtraction, multiplication or division depending the input
from user

# include <stdio.h>
int main()
{
char operator;
double firstNumber,secondNumber;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&firstNumber, &secondNumber);
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber+secondNumber);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-
secondNumber);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber*secondNumber);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber/firstNumber);
break;
// operator is doesn't match any case constant (+, -, *, /)
default:
printf("Error! operator is not correct");
}
return 0;
}
Output
Enter an operator (+, -, *,): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1

4. Describe the decision making statements and looping statements in C with


an example. [APR/MAY 2018] (OR) What are the loop constructs provided
C language for performing loop operations?
A loop is defined as a block of statement which are repeatedly executed for
certain number of times. There are three types of loop statement
1. for statement
2. while statement
3. do-while statement

1. for statement:

The for loop allows to execute a set of instructions until a certain condition
is satisfied.condition may be predefined or open-ended.

Syntax:

for(<initial value>;<condition>;<incrementation/decrementation>)

block of statement;

}
Here the initial value means the starting value assigned to the variable and
condition in the loop counter to determine whether the loop should continue or not.
Incrementation/ decrementation is to Increment/decrement the loop counter value each
time the program segment has been executed.

Program:

#include<stdio.h>

void main()

int i,n;

printf(“Enter the limit”);

scanf(“%d”,&n);

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

printf(“%d\n”,i;

getch;

}
Output:

Enter the limit: 5

2. while statement:

A sequence of statements are executed until some condition is satisfied.

Syntax:

while(condition)

Block of statement;

increment/decrement;

Here, statement(s) may be a single statement or a block of statements.

If the test expression is true (nonzero), codes inside the body of while loop are
executed. The test expression is evaluated again. The process goes on until the
test expression is false.

When the test expression is false, the while loop is terminated.


Program:

/* generate the evevn number to given limit */

#include<stdio.h>

void main()

int i,n;

printf(“\n Enter the limit:”);

scanf(“%d”,&n);

i=1;

while(i<=n)

if(i%2==0)

printf(“%d\t”,i);

i++;

}
getch();

Output:

Enter the limit: 10

2 4 6 8 10

3. do-while statement:
The do-while loop varies from the while loop in the checking condition. The
condition of the loop is not tested until the body of the loop has been
executed once. If the condition is false, after the first iteration the loop
terminates. The statement are executed atleast once even if the condition
fails for the first time itself. It is otherwise called as exit control loop.
Syntax:
do
{
statement;
}while(condition);
Program:

#include<stdio.h>
#include<conio.h>
void main
{
int a,b,c,r;
clrscr();
printf(“Enter the range:”);
scanf(“%d”,&r);
a=0; b=1;
printf(“%d”,a);
printf(“\n%d”,b);
printf(“\n”);
c=0;
do
{
c=a+b;
if(c<=r)
printf(“%d\n”,c);
a=b;
b=c;
}while(c<=r);
getch();
}
OUTPUT:
Enter the range: 10
0
1
1
2
3
5
8

5. Explain about the structure of a C program?

Every C program contains a number of building blocks. These building blocks


should be written in a correct order and procedure, for the C program to execute
without any errors.

documentation section
preprocessor section
definition section
global declaration section
main
{
declaration part
executable part
}
sub program
{
Body of the program
}

Documentation section

 The general comments are included in this section.


 The comments are not a part of executable programs.
 The comments are placed between delimiters (/* and */).
 The C-compiler doesn’t consider as programming code.
Example

/* Factorial of a given number */

Preprocessor section

 It provides preprocessor statements which direct the compiler to link functions


from the system library.

Example
#include<stdio.h>
#include<conio.h>
#include<string.h>

Definition section

 Definition selection defines all symbolic constants.


 It refers to assigning macros of a name to a constant.

Example

#define PI 3.41

#define x (x*x*x)

Global declaration section

 It contains variable declarations, which can be accessed anywhere within the


program.
 This variable also known as ‘ Public Variable’ or ‘ External Variable’.

Example

int a;

main()

{
………….

………….

main() function

 Each and every C program should have only one main() function.
 Without main() function, the program cannot be executed.
 The main function should be written in lowercase only.
 It should not be terminated with semicolon.

Declaration part

 Each and every variable should be declared before going to use those variables
in execution part.

Execution part

 In execution part, the logic of the program can be implemented.


 These statements are known as program statements or building blocks of
program. They provide instructions to the computer to perform a specific task.

Subprogram section

 The subprogram section contains all the 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 Program

/* Addition of two numbers */ documentation section

#include<stdio.h> preprocessor section

#define A 10 definition section


int c; global variable declaration

int sum(int,int): section

main() main() function

int b;

printf(“Enter the value of b:”);

scanf(“%d”,&b); executable part

c=sum(b);

printf(“\n Answer = %d”,c):

getch();

int sum(int y)

C=A+y; sub program

Return(c);

6. Discuss about the unformatted I/O functions?


Character oriented I/O functions:
 Reading a character
Reading a single character from the keyboard can be done by using the
function getchar(). General form of the getchar() function is
variable_name= getchar();
where variable_name is a valid variable declared as char type.when this
statement is encountered, the computer waits until a key is pressed and then
assigns this character to the variable_name on the left.
For example,
char name;
name=getchar();

The character functions are contained in the file ctype.h

#include<ctype.h>

Similarly the getc(), getch() and getche() functions can be used for reading a
character.

 Writing a character
The function putchar() is used for writing characters one at a time to the
terminal. The general form of the putchar() function is
Putchar(variable_name);
Where variable_name is a char type variable. This statement displays the
character contained in the variable at the terminal.
Similarly the putc and outch() functions can be used for writing a character.
For example,
char c;
c= ‘x’;
putchar(c);
will display the character x on the screen.
The statement
putchar(“\n”);
would cause the cursor on the screen to move to the beginning of the next
line.

Example program:

#include<stdio.h>

void main()

char c;

do

c=getchar();

putchar(c);

}while(c!=’\n’);

getch();

Input: Good morning

Output: Good morning

String oriented I/O functions:


The gets() function is used to read the string ( a string is a group of characters)
from the standard input device (keyboard).
Syntax:
gets(char type of array variable);
The puts() function is used to display /write the string to the standard output
device (monitor).
Syntax:
puts(char type of array variable);
Example program:

/* program using the gets() and puts() function */

#include<stdio.h>

void main()

char a[10];

puts(“\n Enter the string:”);

gets(a);

puts(“\n The given string is:”);

gets(a);

getch();

Output:

Enter the string: dhivi

The given string is:dhivi

The gets() and puts() functions are similar to the scanf() and printf() function but
the difference is in scanf() input statements. When there is a blank space in tnput
text, then it takes the space as encoding the string, the remaining string is not taken.

7. Explain about formatted input and output function?


Formatted input function:
Input data can be entered into the computer form a standard input device using
the ‘C’ library function scanf().the function is used for passing mixed input.scanf()
function is mainly used to read information from the standard input device.
the general form of scanf() function is
scanf(“Control String”,arg1,arg2,…..);
basic control string:
%c -Read a single character
%d -Read a decimal integer
%f -Read a floating point value
%s -Read a string
%ld -Read a long integer
%i -Read a decimal integer
%o -Read a octal integer

Example program:

#include<stdio.h>

void main()

int a,b,c;

scanf(“%d%d%d”,&a,&b,&c);

Rules for scanf() function:

 The control string should be used that are relevant to corresponding variable.
 The control strings are enclosed with double quotes.
 No.Of input variables are used that are separated by comma.
 Variable are preceded with (&) sign except string variable.
 The control strings and variables should match with each other.
 Scanf() statement should terminated with semi-colan(;).

Formatted output function:

Output data can be written from the computer on to a standard output


device using the library function printf().The general form of printf() function is
Printf(“Control String”,arg1,arg2,…..);

Where the control strings consist of three types,

 Characters that will be printed on the screen as they appear.


 Format specification that define the output format for the display of each
item.
 Escape (Esc) sequence characters such as \n(New line),\t(Space) and
\b(Bold).
Example program:
#include<stdio.h>
void main()
{
printf(“Hai Sridhar and Baala \n”);
getch();
}
Output:Hai Sridhar and Baala

Rules for printf() function:

 Printf() function is used to print the character, string, float, integer, octal
and hexa decimal values on to the output screen.
 We use printf() function with %d format specifier to display the value of an
integer variable
 Similarly %c is used to display the character, %f for float variable, %s for
string variable, %1f for double and %x for hexadecimal variable.
 To generate a newline, we use “\n” in C printf() statement.
8. Explain about Pre-processor and its directives?
Preprocessor is a program that processes the source code before it passes
through the compiler. This is known as preprocessor.
 It operates under the control of preprocessor command lines or directives.
 Preprocessor directives are placed in the source program before the main
line.
 Before the source code passes through the compiler, it is examined by the
preprocessor for any preprocessor directives.
 Preprocessor directives begin with the symbol # in column and do not
require a semicolon at the end.

Rules for defining preprocessor

 Every preprocessor must start with # symbol.


 The preprocessor is always placed before main() function
 The preprocessor cannot have termination with semicolon.
 There is no assignment operator in #define statement.
 The conditional macro must be terminated (#ifdef, #endif).

Directives are divided into three categories.

i) Macro substitution directives


ii) File inclusion directives
iii) Compiler control directives

Macro substitution directives:

It is also called as #define preprocessor directives.

Syntax:

#define identifier string

There are different forms of macro substitution

4. Simple macro substitution


5. Argument macro substitution
6. Nested macro substitution

Simple macro substitution:

Simple string replacement is commonly used to define constants.

Examples of definition of constants are:

#define COUNT 50

#define FALSE 0

#define SUBJECTS 4

#define PI 3.14

#define CAPITAL “DELHI”

A macro definition can include more than a simple constant value

#define AREA 5*12.46

#define SIZE sizeof(int) *7

#define TWO-PI 2.0 * 3.14

#define A (55-33)

#define B (55+33)\

Simple Macro sub for creating C sentences

#define TEST if(x>y)

#define AND

#define PRINT printf(“success”)

Macro with Arguments

 More complex and more useful form of replacement


 #define identifier(f1,f2,….,fn) string
 No space between identifier and the left parenthesis
 Subsequent occurrence of a macro with arguments is known as a macro
call.
 When a macro is called , the preprocessor substitutes replacing formal
with actual parameters.

A simple example of a macro argument is

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

volume= CUBE(side) // (side*side*side)

volume= (side*side*side)

Nesting of macro:

We can also use one macro in the definition of another macro. That is
macro definition may be nested.

#define M 5

#define N M+1

#define SUQARE ((x) * (x))

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

#define SIXTH(x) (CUBE (x)* CUBE (x))

Undefining a macro

A defined macro can be undefined, using the statement

#undef identifier

This is useful when we want to restrict the definition only to a particular


part of the program.
File inclusion directives

An external file containing function or macro definition can be included as the


part os a program. This is achieved by the preprocessor directive

#include “filename” or #include<filename>

Where the file name is the name of the file containing the required definitions or
functions.

Example:

#include<stdio.h>

#include<conio.h>

#include “SYNTAX.C”

Main()

………….

…………..

Compiler control directives

These are the directives meant for controlling the compiler actions. A
preprocessor offers a feature known as conditional compilation, which can be used to
switch off or on a particular line or group of lines in a program.

#ifdef and #ifndef are mostly used in these directives.


9. Describe about the compilation process?

The execution of a C program involves four stages using different compiling/


executing tool, those tools are set of programs which help to complete the C
program’s execution process.

 Preprocessor
Preprocessor processes the program before compilation. Preprocessor
include header files, expand the macros.
 Compiler
The generated output files after preprocessing (with source code) will be
passed to the compiler for compilation. Compiler will compile the program,
checks the errors and generates the object file (this object file contains
assembly code).
 Linker
Linker links the more than one object files or libraries and generates the
executable file.
 Loader
Loader loads the executable file into the main/ primary memory and program
run.

Different files during the process of execution


Suppose , you save a C program with sample.c – here .c is the extension
of C code, sample.c file contain the program (source code of a C program).
Execution of C program

Preprocessor reads the file and generates the sample.i file, this file
contains the preprocessed code (expanded source code).

Compiler reads the sampli.i file and converts into assemply code and
generates sample.s and then finally generates object code in sample.o file.
Linker reads sample.o file and links the other assemply/object code or
library files and generates executable file named sample.exe.
Loader loads the sample.exe file into the main/primary memory and then
it is executed. After the execution, output is sent to console. One more file is
created that contains the source code named sample.bak; it’s a backup file of the
program files.

10. Write the program to find the given number is even or odd?

#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.

11. Write the program to find the Fibonacci serious for the given range?
#include<stdio.h>
#include<conio.h>
void main
{
int a,b,c,r;
clrscr();
printf(“Enter the range:”);
scanf(“%d”,&r);
a=0; b=1;
printf(“%d”,a);
printf(“\n%d”,b);
printf(“\n”);
c=0;
do
{
c=a+b;
if(c<=r)
printf(“%d\n”,c);
a=b;
b=c;
}while(c<=r);
getch();
}
OUTPUT:
Enter the range: 5
0
1
1
2
3
5

You might also like