Professional Documents
Culture Documents
UNIT 2operators
UNIT 2operators
OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are
called operands and + is called operator. C language supports following type of operators.
Types of Operators-
Arithmetic Operators
Logical (or Relational) Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators:
Bitwise Operators:
Assume if A = 60; and B = 13; Now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
Assignment Operators:
x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced by x. Here x and
1 are known as L-VALUES and R-VALUES respectively L-values can be on either side of the
assignment operator where as R-values only appear on the right.
So x is an L-value because it can appear on the left as we've just seen, or on the right like this: y
= x; However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is
invalid.
Misc Operators
Show Examples
Operator Description Example
sizeof() Returns the size of an variable. sizeof(a), where a is interger, will return 4.
& Returns the address of an variable. &a; will give actaul address of the variable.
Operators Categories:
All the operators we have discussed above can be categorized into following categories:
Precedence of C Operators:
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedenace than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precede nce appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity
Expression
Statement-
A statement is a command given to the computer that instructs the computer to take a specific
action, such as display to the screen, or collect input. A computer program is made up of a series
of statements.
Contents-
1 Labeled Statements
2 Compound Statements
3 Expression Statements
4 Selection Statements
5 Iteration Statements
6 Jump Statements
Labeled Statements
A simple identifier followed by a colon (:) is a label. Usually, this label is the target of a goto
statement.
Within switch statements, case and default labeled statements exist. A statement of the form
indicates that control will pass to this statement if the value of the control expression of the
switch statement matches the value of the constant-expression. A statement of the form
default : statement
indicates that control will pass to this statement if the control expression of the switch statement
does not match any of the constant-expressions within the switch statement. If the default
statement is omitted, the control will pass to the statement following the switch statement.
Compound Statements
A compound statement is the way C groups multiple statements into a single statement. It
consists of multiple statements and declarations within braces (i.e. { and }). In the ANSI C
Standard of 1989-1990, a compound statement contained an optional list of declarations
followed by an optional list of statements; in more recent revisions of the Standard, declarations
and statements can be freely interwoven through the code. The body of a function is also a
compound statement by rule.
Expression Statements
Selection Statements
if ( expression ) statement
In this type of if-statement, the sub-statement will only be executed iff the expression is non-
zero.
In this type of if-statement, the first sub-statement will only be executed iff the expression is
non-zero; otherwise, the second sub-statement will be executed. Each else matches up with the
closest unmatched if, so that the following two snippets of code are not equal:
if (expression)
if (secondexpression) statement1;
else
statement2;
if (expression)
{
if (secondexpression) statement1;
}
else
statement2;
because in the first, the else statement matches up with the if statement that has secondexpression
for a control, but in the second, the braces force the else to match up with the if that has
expression for a control.
Switch statements are also a type of selection statement. They have the format
The statement here is usually compound and it contains case-labeled statements and optionally a
default-labeled statement.
Iteration Statements
C has three kinds of iteration statements. The first is a while-statement with the form
The substatement of a while runs repeatedly as long as the control expression evaluates to non-
zero at the beginning of each iteration. If the control expression evaluates to zero the first time
through, the substatement may not run at all.
The second is a do-while statement of the form
This is similar to a while loop, except that the controlling expression is evaluated at the end of
the loop instead of the beginning and consequently the sub-statement must execute at least once.
The third type of iteration statement is the for-statement. In ANSI C 1989, it has the form
In more recent versions of the C standard, a declaration can substitute for the first expression.
The opt subscript indicates that the expression is optional.
The statement
for (e1; e2; e3)
s;
The e1 expression represents an initial condition; e2 a control expression; and e3 what to happen
on each iteration of the loop. If e2 is missing, the expression is considered to be non-zero on
every iteration, and only a break statement within s (or a call to a non-returning function such as
exit or abort) will end the loop.
Jump Statements
C has four types of jump statements. The first, the goto statement, is used sparingly and has the
form
goto identifier ;
This statement transfers control flow to the statement labeled within the given identifier.
break ;
is used within iteration statements and switch statements to pass control flow to the statement
following the while, do-while, for, or switch.
continue ;
is used within the substatement of interation statements to transfer control flow to the place just
before the end of the substatement. In for statements the iteration expression will then be
executed before the controlling expression is evaluated.
The fourth type of jump statement is the return statement with the form
return expressionopt ;
This statement returns from the function. If the function return type is void, the function may not
return a value; otherwise, the expression represents the value to be returned.
Input : In any programming language input means to feed some data into program. This can be
given in the form of file or from command line. C programming language provides a set of built-
in functions to read given input and feed it to the program as per requirement.
Output : In any programming language output means to display some data on screen, printer or
in any file. C programming language provides a set of built-in functions to output required data.
Here we will discuss only one input function and one putput function just to understand the
meaning of input and output. Rest of the functions are given into C - Built-in Functions
printf() function
This is one of the most frequently used functions in C for output. ( we will discuss what is
function in subsequent chapter. ).
main()
{
int dec = 5;
char str[] = "abc";
char ch = 's';
float pi = 3.14;
Here %d is being used to print an integer, %s is being usedto print a string, %f is being used to
print a float and %c is being used to print a character.
scanf() function
This is the function which can be used to to read an input from the command line.
main()
{
int x;
int args;
Here %d is being used to read an integer value and we are passing &x to store the vale read
input. Here &indicates the address of variavle x.
This program will prompt you to enter a value. Whatever value you will enter at command
prompt that will be output at the screen using printf() function. If you eneter a non-integer value then it
will display an error message.
Enter an integer: 20
Read in 20
getch()
The getch() function is used to catch a character from the keyboard. The getch() function reads a
single character from the keyboard but does not show on the screen. For this functionality, you
can use the getch() function to hold the output window until hitting any key from the keyboard.
#include <conio.h>
#include <stdio.h>
void main()
{
int c;
clrscr();
printf(“Press any key\n”);
c = getch();
if (c)
printf(“A key is pressed from keyboard ”);
else
printf(“An error occurred ”);
getch();
}
Function : getchar()
getchar() is used to get or read the input (i.e a single character) at run time.
Declaration:
int getchar(void);
Example Declaration:
char ch;
ch = getchar();
Return Value:
This function return the character read from the keyboard.
Example Program:
void main()
{
char ch;
ch = getchar();
printf("Input Char Is :%c",ch);
}
Program Explanation:
Here, declare the variable ch as char data type, and then get a value through getchar()library
function and store it in the variable Ch. And then, print the value of variable ch.
During the program execution, a single character is get or read through the getchar(). The given
value is displayed on the screen and the compiler wait for another character to be typed. If you
press the enter key/any other characters and then only the given character is printed through
the printf function.
putchar()
putchar() displays any alphanumeric characters to the standard output device. It displays only
one character at a time.
Declaration:
int putch(variable_name);
Example Declaration:
char ch = 'a';
putchar(ch);
Remarks:
putchar displays one character at a time to the Monitor.
Example Program:
void main()
{
char ch='a';
putchar(ch);
}
To use any of the standard functions, the appropriate header file should be included. This is done
at the beginning of the C source file. For example, to use the function printf() in a program, the
line
#include <stdio.h>
should be at the beginning of the source file, because the definition for printf() is found in the file
stdio.h All header files have the extension .h and generally reside in the /include subdirectory.
#include <stdio.h>
#include "mydecls.h"
The use of angle brackets <> informs the compiler to search the compilers include directory for
the specified file. The use of the double quotes "" around the filename inform the compiler to
search in the current directory for the specified file.
A header file is a file with extension .h which contains C function declarations and macro
definitions to be shared between several source files. There are two types of header files: the files
that the programmer writes and the files that comes with your compiler.
You request to use a header file in your program by including it with the C preprocessing
directive #include, like you have seen inclusion of stdio.h header file, which comes along with
your compiler.
Including a header file is equal to copying the content of the header file but we do not do it
because it will be error-prone and it is not a good idea to copy the content of a header file in the
source files, especially if we have multiple source files in a program.
A simple practice in C or C++ programs is that we keep all the constants, macros, system wide
global variables, and function prototypes in the header files and include that header file wherever
it is required.
Include Syntax
Both the user and the system header files are included using the preprocessing directive #include.
It has the following two forms −
#include <file>
This form is used for system header files. It searches for a file named 'file' in a standard list of
system directories. You can prepend directories to this list with the -I option while compiling
your source code.
#include "file"
This form is used for header files of your own program. It searches for a file named 'file' in the
directory containing the current file. You can prepend directories to this list with the -I option
while compiling your source code.
Include Operation
The #include directive works by directing the C preprocessor to scan the specified file as input
before continuing with the rest of the current source file. The output from the preprocessor
contains the output already generated, followed by the output resulting from the included file,
followed by the output that comes from the text after the #include directive. For example, if you
have a header file header.h as follows −
and a main program called program.c that uses the header file, like this −
int x;
#include "header.h"
the compiler will see the same token stream as it would if program.c read.
int x;
char *test (void);
Once-Only Headers
If a header file happens to be included twice, the compiler will process its contents twice and it
will result in an error. The standard way to prevent this is to enclose the entire real contents of
the file in a conditional, like this −
#ifndef HEADER_FILE
#define HEADER_FILE
#endif
This construct is commonly known as a wrapper #ifndef. When the header is included again, the
conditional will be false, because HEADER_FILE is defined. The preprocessor will skip over
the entire contents of the file, and the compiler will not see it twice.
Computed Includes
Sometimes it is necessary to select one of the several different header files to be included into
your program. For instance, they might specify configuration parameters to be used on different
sorts of operating systems. You could do this with a series of conditionals as follows −
#if SYSTEM_1
# include "system_1.h"
#elif SYSTEM_2
# include "system_2.h"
#elif SYSTEM_3
...
#endif
But as it grows, it becomes tedious, instead the preprocessor offers the ability to use a macro for
the header name. This is called a computed include. Instead of writing a header name as the
direct argument of #include, you simply put a macro name there −
#define SYSTEM_H "system_1.h"
...
#include SYSTEM_H
SYSTEM_H will be expanded, and the preprocessor will look for system_1.h as if the #include
had been written that way originally. SYSTEM_H could be defined by your Makefile with a -D
option.
Preprocessor directives
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual compilation. We'll refer to the C
Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank
character, and for readability, a preprocessor directive should begin in the first column. The
following section lists down all the important preprocessor directives −
Directive Description
#define Substitutes a preprocessor macro.
#include Inserts a particular header from another file.
#undef Undefines a preprocessor macro.
#ifdef Returns true if this macro is defined.
#ifndef Returns true if this macro is not defined.
#if Tests if a compile time condition is true.
#else The alternative for #if.
#elif #else and #if in one statement.
#endif Ends preprocessor conditional.
#error Prints error message on stderr.
#pragma Issues special commands to the compiler, using a standardized method.
Preprocessors Examples
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use
#define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to the current
source file. The next line tells CPP to get myheader.h from the local directory and add the
content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
Include Syntax
Both user and system header files are included using the preprocessing directive ‘#include’. It
has two variants:
#include <file>
This variant is used for system header files. It searches for a file named file in a standard
list of system directories. You can prepend directories to this list with the -I option (see
Invocation).
#include "file"
This variant is used for header files of your own program. It searches for a file named file
first in the directory containing the current file, then in the quote directories and then the
same directories used for <file>. You can prepend directories to the list of quote
directories with the -iquote option.
The argument of ‘#include’, whether delimited with quote marks or angle brackets, behaves like
a string constant in that comments are not recognized, and macro names are not expanded. Thus,
#include <x/*y> specifies inclusion of a system header file named x/*y.
However, if backslashes occur within file, they are considered ordinary text characters, not
escape characters. None of the character escape sequences appropriate to string constants in C
are processed. Thus, #include "x\n\\y" specifies a filename containing three backslashes. (Some
systems interpret ‘\’ as a pathname separator. All of these also interpret ‘/’ the same way. It is
most portable to use only ‘/’.)
It is an error if there is anything (other than comments) on the line after the file name.
If the file name that's enclosed in double quotation marks is an incomplete path
specification, the preprocessor first searches the "parent" file's directory. A parent file is the file
that contains the #include directive. For example, if you include a file named file2 in a file
named file1, file1 is the parent file.
Include files can be "nested"; that is, an #include directive can appear in a file that's named by
another #include directive. For example, file2 could include file3. In this case, file1 would still
be the parent of file2, but it would be the "grandparent" of file3.
When include files are nested and when compiling occurs on the command line, directory
searching begins with the directories of the parent file and then proceeds through the directories
of any grandparent files. That is, searching begins relative to the directory that contains the
source that's currently being processed. If the file is not found, the search moves to directories
that are specified by the /I compiler option. Finally, the directories that are specified by the
INCLUDE environment variable are searched.
From the development environment, the INCLUDE environment variable is ignored. For
information about how to set the directories that are searched for include files—this also applies
to the LIB environment variable—see VC++ Directories Property Page.
This example adds the contents of the file named STDIO.H to the source program. The angle
brackets cause the preprocessor to search the directories that are specified by the INCLUDE
environment variable for STDIO.H, after it searches directories that are specified by the /I
compiler option.
#define-
In the C Programming Language, the #define directive allows the definition of macros within
your source code. These macro definitions allow constant values to be declared for use
throughout your code.
Macro definitions are not variables and cannot be changed by your program code like variables.
You generally use this syntax when creating constants that represent numbers, strings or
expressions.
Syntax
The syntax for creating a constant using #define in the C language is:
#define CNAME value
OR
#define CNAME (expression)
CNAME
The name of the constant. Most C programmers define their constant names in uppercase,
but it is not a requirement of the C Language.
value
The value of the constant.
expression
Expression whose value is assigned to the constant. The expression must be enclosed in
parentheses if it contains operators.
Note
Do NOT put a semicolon character at the end of #define statements. This is a common
mistake.
Example
Let's look at how to use #define directives with numbers, strings, and expressions.
Number
The following is an example of how you use the #define directive to define a numeric constant:
#define AGE 10
In this example, the constant named AGE would contain the value of 10.
String
For example:
#define NAME "TechOnTheNet.com"
In this example, the constant called NAME would contain the value of "TechOnTheNet.com".
int main()
{
printf("%s is over %d years old.\n", NAME, AGE);
return 0;
}
Q:1 Define Operator. Explain various types of operator based upon the number of operands.
Q:2 What are arithmetic and logical operators?
Q:3 Write Short Note on Preprocessor Directive
# define
#include
Q:4 What is Swapping? Write a C program to swap 2 variables without using third variable.
Q:5 Differentiate among getch(), getche(), getchar() functions.
Q:6 Explain the use of goto and exit statements.
Q:7 What are header file? Also explain pre-processor directives in c with examples.