Sunteți pe pagina 1din 19

Unit 1

How a Preprocessor works in C?


Compiling a C program – Behind the Scene

A Preprocessor is a system software (a computer program that is designed to run on


computer’s hardware and application programs). It performs preprocessing of the High Level
Language(HLL). Preprocessing is the first step of the language processing system. Language
processing system translates the high level language to machine level language or absolute
machine code(i.e. to the form that can be understood by machine).

• The preprocessor doesn’t know about the scope rules of C. Preprocessor directives
like #define come into effect as soon as they are seen and remain in effect until the
end of the file that contains them; the program’s block structure is irrelevant.

A Preprocessor mainly performs three tasks on the HLL code :

1. Removing comments : It removes all the comments. A comment is written only for
the humans to understand the code. So, it is obvious that they are of no use to a
machine. So, preprocessor removes all of them as they are not required in the
execution and won’t be executed as well.
2. • File inclusion : Including all the files from library that our program needs. In HLL
we write #include which is a directive for the preprocessor that tells it to include the
contents of the library file specified. For example, #include will tell the preprocessor
to include all the contents in the library file stdio.h.
This can also be written using double quotes – #include “stdio.h”
Note: If the filename is enclosed within angle brackets, the file is searched for in the
standard compiler include paths. If the filename is enclosed within double quotes, the
search path is expanded to include the current source directory.
3. • Macro expansion : Macros can be called as small functions that are not as
overhead to process. If we have to write a function (having a small definition) that
needs to be called recursively (again and again), then we should prefer a macro over a
function.
So, defining these macros is done by preprocessor.
#define SI 1000 is a simple example of a macro.

Unit 2
Operators in C / C++
Operators are the foundation of any programming language. Thus the functionality of C/C++
programming language is incomplete without the use of operators. We can define operators
as symbols that help us to perform specific mathematical and logical computations on
operands. In other words we can say that an operator operates the operands.
For example, consider the below statement:

c = a + b;

Here, ‘+’ is the operator known as addition operator and ‘a’ and ‘b’ are operands. The
addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.

C/C++ has many built-in operator types and they can be classified as:

1. Arithmetic Operators: These are the operators used to perform


arithmetic/mathematical operations on operands. Examples: (+, -, *, /, %,++,–).
Arithmetic operator are of two types:
I. Unary Operators: Operators that operates or works with a single operand are
unary operators.
For example: (++ , –)
II. Binary Operators: Operators that operates or works with two operands are
binary operators.For example: (+ , – , * , /)

To learn Arithmetic Operators in details visit this link.

2. Relational Operators: Relational operators are used for comparison of the values of
two operands. For example: checking if one operand is equal to the other operand or
not, an operand is greater than the other operand or not etc. Some of the relational
operators are (==, >= , <= ). To learn about each of these operators in details go to
this link.

• Logical Operators: Logical Operators are used to combine two or more


conditions/constraints or to complement the evaluation of the original condition in
consideration. The result of the operation of a logical operator is a boolean value either true
or false. To learn about different logical operators in details please visit this link.
• Bitwise Operators: The Bitwise operators is used to perform bit-level operations on the
operands. The operators are first converted to bit-level and then calculation is performed on
the operands. The mathematical operations such as addition , subtraction , multiplication etc.
can be performed at bit-level for faster processing. To learn bitwise operators in details, visit
this link.
• Assignment Operators: Assignment operators are used to assign value to a variable. The
left side operand of the assignment operator is a variable and right side operand of the
assignment operator is a value. The value on the right side must be of the same data-type of
variable on the left side otherwise the compiler will raise an error.
Different types of assignment operators are shown below:

• “=”: This is the simplest assignment operator. This operator is used to assign the
value on the right to the variable on the left.
For example:
• a = 10;
• b = 20;
• ch = 'y';
• “+=”:This operator is combination of ‘+’ and ‘=’ operators. This operator first adds
the current value of the variable on left to the value on right and then assigns the
result to the variable on the left.
Example:
• (a += b) can be written as (a = a + b)

If initially value stored in a is 5. Then (a += 6) = 11.

• “-=”:This operator is combination of ‘-‘ and ‘=’ operators. This operator first
subtracts the value on right from the current value of the variable on left and then
assigns the result to the variable on the left.
Example:
• (a -= b) can be written as (a = a - b)

If initially value stored in a is 8. Then (a -= 6) = 2.

• “*=”:This operator is combination of ‘*’ and ‘=’ operators. This operator first
multiplies the current value of the variable on left to the value on right and then
assigns the result to the variable on the left.
Example:
• (a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.

• “/=”:This operator is combination of ‘/’ and ‘=’ operators. This operator first divides
the current value of the variable on left by the value on right and then assigns the
result to the variable on the left.
Example:
• (a /= b) can be written as (a = a / b)

If initially value stored in a is 6. Then (a /= 2) = 3.

• Other Operators: Apart from the above operators there are some other operators available
in C or C++ used to perform some specific task. Some of them are discussed here:

• sizeof operator: sizeof is a much used in the C/C++ programming language. It is a


compile time unary operator which can be used to compute the size of its operand.
The result of sizeof is of unsigned integral type which is usually denoted by size_t.
Basically, sizeof operator is used to compute the size of the variable. To learn about
sizeof operator in details you may visit this link.
• Comma Operator: The comma operator (represented by the token ,) is a binary
operator that evaluates its first operand and discards the result, it then evaluates the
second operand and returns this value (and type). The comma operator has the lowest
precedence of any C operator. Comma acts as both operator and separator. To learn
about comma in details visit this link.
• Conditional Operator: Conditional operator is of the form Expression1 ?
Expression2 : Expression3 . Here, Expression1 is the condition to be evaluated. If the
condition(Expression1) is True then we will execute and return the result of
Expression2 otherwise if the condition(Expression1) is false then we will execute and
return the result of Expression3. We may replace the use of if..else statements by
conditional operators. To learn about conditional operators in details, visit this link.

Operator precedence chart

The below table describes the precedence order and associativity of operators in C / C++ .
Precedence of operator decreases from top to bottom.

Operator Description Associativity


() Parentheses (function call) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++/– Postfix increment/decrement
++/– Prefix increment/decrement right-to-left
+/- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
*,/,% Multiplication/division/modulus left-to-right
+/- Addition/subtraction left-to-right
<< , >> Bitwise shift left, Bitwise shift right left-to-right
< , <= Relational less than/less than or equal to left-to-right
> , >= Relational greater than/greater than or equal to left-to-right
== , != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= , -= Addition/subtraction assignment
*= , /= Multiplication/division assignment
%= , &= Modulus/bitwise AND assignment
^= , |= Bitwise exclusive/inclusive OR assignment
<>= Bitwise shift left/right assignment
, expression separator left-to-right

C Conditional Statement: IF, IF Else and


Nested IF Else with Example
What is a Conditional Statement?

In a 'C' program are executed sequentially. This happens when there is no condition around
the statements. If you put some condition for a block of statements the flow of execution
might change based on the result evaluated by the condition. This process is referred to as
decision making in 'C.' The decision-making statements are also called as control statements.

In 'C' programming conditional statements are possible with the help of the following two
constructs:

1. If statement

2. If-else statement

If statement

It is one of the powerful conditional statement. If statement is responsible for modifying the
flow of execution of a program. If statement is always used with a condition. The condition is
evaluated first before executing any statement inside the body of If. The syntax for if
statement is as follows:

if (condition)
instruction;

The condition evaluates to either true or false. True is always a non-zero value, and false is a
value that contains zero. Instructions can be a single instruction or a code block enclosed by
curly braces { }.

Following program illustrates the use of if construct in 'C' programming:

#include<stdio.h>
int main()
{
int num1=1;
int num2=2;
if(num1<num2) //test-condition
{
printf("num1 is smaller than num2");
}
return 0;
}

Output:

num1 is smaller than num2


The If-Else statement

The if-else is statement is an extended version of If. The general form of if-else is as follows:

if (test-expression)
{
True block of statements
}
Else
{
False block of statements
}
Statements;

n this type of a construct, if the value of test-expression is true, then the true block of
statements will be executed. If the value of test-expression if false, then the false block of
statements will be executed. In any case, after the execution, the control will be automatically
transferred to the statements appearing outside the block of If.

Following programs illustrate the use of the if-else construct:

We will initialize a variable with some value and write a program to determine if the value is
less than ten or greater than ten.

Let's start.

#include<stdio.h>
int main()
{
int num=19;
if(num<10)
{
printf("The value is less than 10");
}
else
{
printf("The value is greater than 10");
}
return 0;
}

Output:

The value is greater than 10


Nested If-else Statements

When a series of decision is required, nested if-else is used. Nesting means using one if-else
construct within another one.

Let's write a program to illustrate the use of nested if-else.

#include<stdio.h>
int main()
{
int num=1;
if(num<10)
{
if(num==1)
{
printf("The value is:%d\n",num);
}
else
{
printf("The value is greater than 1");
}
}
else
{
printf("The value is greater than 10");
}
return 0;
}

Output:

The value is:1


Nested Else-if statements

Nested else-if is used when multipath decisions are required.

The general syntax of how else-if ladders are constructed in 'C' programming is as follows:

if (test - expression 1) {
statement1;
} else if (test - expression 2) {
Statement2;
} else if (test - expression 3) {
Statement3;
} else if (test - expression n) {
Statement n;
} else {
default;
}
Statement x;

This type of structure is known as the else-if ladder. This chain generally looks like a ladder
hence it is also called as an else-if ladder. The test-expressions are evaluated from top to
bottom. Whenever a true test-expression if found, statement associated with it is executed.
When all the n test-expressions becomes false, then the default else statement is executed.

Let us see the actual working with the help of a program.

#include<stdio.h>
int main()
{
int marks=83;
if(marks>75){
printf("First class");
}
else if(marks>65){
printf("Second class");
}
else if(marks>55){
printf("Third class");
}
else{
printf("Fourth class");
}
return 0;
}

Output:

Switch Statement in C/C++


Switch case statements are a substitute for long if statements that compare a variable to
several integral values

• The switch statement is a multiway branch statement. It provides an easy way to


dispatch execution to different parts of code based on the value of the expression.
• Switch is a control statement that allows a value to change control of execution.

Syntax:

switch (n)
{
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
default: // code to be executed if n doesn't match any cases
}

Example :
// Following is a simple C program
// to demonstrate syntax of switch.
#include <stdio.h>
int main()
{
int x = 2;
switch (x)
{
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
case 3: printf("Choice is 3");
break;
default: printf("Choice other than 1, 2 and 3");
break;
}
return 0;
}

break, continue and goto statements


The break; continue; and goto; statements are used to alter the normal flow of a program.
Loops perform a set of repetitive task until text expression becomes false but it is sometimes
desirable to skip some statement/s inside loop or terminate the loop immediately without
checking the test expression. In such cases, break and continue statements are used.

break statement
In C programming, break statement is used with conditional if statement.
The break is used in terminating the loop immediately after it is encountered.
it is also used in switch...case statement. which is explained in next topic.

Syntax:
break;

The break statement can be used in terminating loops like for, while and do...while

Example:
//Write a C Program Which use of break statement.
#include<stdio.h>
#include<conio.h>
void main(){
int num, sum=0;
int i,n;
printf("Note: Enter Zero for break loop!\n");
printf("Enter Number of inputs\n");

scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter num%d: ",i);
scanf("%d",&num);
if(num==0) {
break; /*this breaks loop if num == 0 */
printf("Loop Breaked\n");
}

sum=sum+num;
}
printf("Total is %d",sum);
getch();
}
Output:
Command Prompt

Note: Enter Zero for break loop!


Enter Number of inputs
5
Enter num1: 5
Enter num2: 10
Enter num3: 0
Loop Breaked
Total is 15

continue statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue
statement is used.

Syntax:
continue;

Just like break, continue is also used with conditional if statement.

Example:
//Write a C Program Which use of continue statment.
#include<stdio.h>
#include<conio.h>
void main(){
int i, n=20;
clrscr();
for(i=1;i<=n;++i){
if(i % 5 == 0) {
printf("pass\n");
continue; /*this continue the execution of loop if i % 5
== 0 */
}
printf("%d\n",i);
}
getch();
}
Output:
Command Prompt

1
2
3
4
pass
6
7
8
9
pass
11
12
13
14
pass
16
17
18
19
pass

goto statement
In C programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.

Syntax:
goto label;
.............
.............
.............
label:
statement;

In this syntax, label is an identifier.


When, the control of program reaches to goto statement, the control of the program will jump
to the label: and executes the code below it.

Example:
//Write a C Program Which Print 1 To 10 Number Using goto statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
count: //This is Label

printf("%d\n",i);
i++;
if(i<=10) {
goto count; //This jumps to label "count:"
}
getch();
}
Output:
Command Prompt
1
2
3
4
5
6
7
8
9
10

Note:

Though goto statement is included in ANSI standard of C, use of goto statement should be
reduced as much as possible in a program.

Reasons to avoid goto statement

• Though, using goto statement give power to jump to any part of program, using goto
statement makes the logic of the program complex and tangled.
• In modern programming, goto statement is considered a harmful construct and a bad
programming practice.
• The goto statement can be replaced in most of C program with the use of break and
continue statements.
• In fact, any program in C programming can be perfectly written without the use of goto
statement.
• All programmer should try to avoid goto statement as possible as they can.

C Loops: For, While, Do While, Break,


Continue with Example
What are Loops?

In looping, a program executes the sequence of statements many times until the stated
condition becomes false. A loop consists of two parts, a body of a loop and a control
statement. The control statement is a combination of some conditions that direct the body of
the loop to execute until the specified condition becomes false.

Types of Loops

Depending upon the position of a control statement in a program, a loop is classified into two
types:

1. Entry controlled loop

2. Exit controlled loop

In an entry controlled loop, a condition is checked before executing the body of a loop. It is
also called as a pre-checking loop.

In an exit controlled loop, a condition is checked after executing the body of a loop. It is also
called as a post-checking loop.
Sample Loop

The control conditions must be well defined and specified otherwise the loop will execute an
infinite number of times. The loop that does not stop executing and processes the statements
number of times is called as an infinite loop. An infinite loop is also called as an "Endless
loop." Following are some characteristics of an infinite loop:

1. No termination condition is specified.

2. The specified conditions never meet.

The specified condition determines whether to execute the loop body or not.

'C' programming language provides us with three types of loop constructs:

1. The while loop

2. The do-while loop

3. The for loop

While Loop

A while loop is the most straightforward looping structure. The basic format of while loop is
as follows:

while (condition) {
statements;
}

It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body


of the loop. If a condition is true then and only then the body of a loop is executed. After the
body of a loop is executed then control again goes back at the beginning, and the condition is
checked if it is true, the same process is executed until the condition becomes false. Once the
condition becomes false, the control goes out of the loop.

After exiting the loop, the control goes to the statements which are immediately after the
loop. The body of a loop can contain more than one statement. If it contains only one
statement, then the curly braces are not compulsory. It is a good practice though to use the
curly braces even we have a single statement in the body.
In while loop, if the condition is not true, then the body of a loop will not be executed, not
even once. It is different in do while loop which we will see shortly.

Following program illustrates a while loop:

#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
num++; //incrementing operation
}
return 0;
}

Output:

1
2
3
4
5
6
7
8
9
10
Do-While loop

A do-while loop is similar to the while loop except that the condition is always executed after
the body of a loop. It is also called an exit-controlled loop.

The basic format of while loop is as follows:

do {
statements
} while (expression);

As we saw in a while loop, the body is executed if and only if the condition is true. In some
cases, we have to execute a body of the loop at least once even if the condition is false. This
type of operation can be achieved by using a do-while loop.

In the do-while loop, the body of a loop is always executed at least once. After the body is
executed, then it checks the condition. If the condition is true, then it will again execute the
body of a loop otherwise control is transferred out of the loop.

Similar to the while loop, once the control goes out of the loop the statements which are
immediately after the loop is executed.

The critical difference between the while and do-while loop is that in while loop the while is
written at the beginning. In do-while loop, the while condition is written at the end and
terminates with a semi-colon (;)

The following program illustrates the working of a do-while loop:

We are going to print a table of number 2 using do while loop.

#include<stdio.h>
#include<conio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=10);
return 0;
}

Output:

2
4
6
8
10
12
14
16
18
20
For loop

A for loop is a more efficient loop structure in 'C' programming. The general structure of for
loop is as follows:

for (initial value; condition; incrementation or decrementation )


{
statements;
}

• The initial value of the for loop is performed only once.


• The condition is a Boolean expression that tests and compares the counter to a fixed value
after each iteration, stopping the for loop when false is returned.
• The incrementation/decrementation increases (or decreases) the counter by a set value.

Following program illustrates the use of a simple for loop:

#include<stdio.h>
int main()
{
int number;
for(number=1;number<=10;number++) //for loop to print 1-10
numbers
{
printf("%d\n",number); //to print the number
}
return 0;
}

Output:

1
2
3
4
5
6
7
8
9
10
Unit 3

Types of Functions in C
In real time, a function may be defined with or without parameters and a function may or may
not return a value. It completely depends upon the user requirement. In this article, We will
explain you the types of functions in C Programming language with an example.

In C Programming, As per our requirement, We can define the User-defined functions in


multiple ways. The following are list of available types of Functions in C

1. Function with no argument and no Return value


2. Function with no argument and with a Return value
3. Function with argument and No Return value
4. Function with argument and Return value
5. From the above, 1 and 3 types does not return any value when the function is called. So, We
use void return type while defining the function.
6. When we call the function 2 and 4 types will return some value. So, We have to use the
appropriate data type (int, float, double etc) as return type while defining the function. We
use return keyword inside the function to return some value when the function is called
from the main() function or any sub-functions.

Types of Functions in C Programming

The Following examples will explain you the available function types in C programming.

C Function with No argument and No Return value

In this method, We won’t pass any arguments to the function while defining, declaring or
calling the function. This type of functions in C will not return any value when we call the
function from main() or any sub function. When we are not expecting any return value but,
we need some statements to be printed as output then, this type of functions in C are very
useful.

C Function with No argument and No Return value


Example
In this program, We are going to calculate the Sum of 2 integer values and print the output
from the user defined function itself.

/* Function with No argument and No Return value Example */


#include<stdio.h>

// Function Declaration
void Addition();

void main()
{
printf("\n ............. \n");

Addition();
}

void Addition()
{
int Sum, a = 10, b = 20;
Sum = a + b;

printf("\n Sum of a = %d and b = %d is = %d", a, b, Sum);


}

OUTPUT

Function with No arguments and with Return value Example

In this program, We are going to calculate the multiplication of 2 integer values using the
user defined function without arguments and return keyword.

OUTPUT
Function with argument and No Return value Example

This program allows the user to enter 2 integer values and then, We are going to pass those
values to the user-defined function to calculate the sum.

#include<stdio.h>

void Addition(int, int);

void main()
{
int a, b;

printf("\n Please Enter two integer values \n");


scanf("%d %d",&a, &b);

//Calling the function with dynamic values


Addition(a, b);
}

void Addition(int a, int b)


{
int Sum;

Sum = a + b;

printf("\n Additiontion of %d and %d is = %d \n", a, b, Sum);


}
Function with arguments and Return value Example

This program allows the user to enter 2 integer values and then, We are going to pass those
values to the user-defined function to multiply those values and return the value using return
keyword.

#include<stdio.h>

int Multiplication(int, int);

int main()
{
int a, b, Multi;

printf("\n Please Enter two integer values \n");


scanf("%d %d",&a, &b);

//Calling the function with dynamic values


Multi = Multiplication(a, b);

printf("\n Multiplication of %d and %d is = %d \n", a, b, Multi);


return 0;
}

int Multiplication(int a, int b)


{
int Multi;

Multi = a * b;

return Multi;
}

S-ar putea să vă placă și