C Final Notes for Print
C Final Notes for Print
OVERVIEW OF C
C the most widely used computer language-is being taught today as a core subject in almost all
the undergraduate programmes. The increasing popularity of C is probably due to its many
desirable qualities.
It is a robust language whose rich set of built-in functions and operators can be usedto
write any complex program.
Programs written in C are efficient and fast. This is due to its variety of data types and
powerful operators.
C language is well suited for Structured Programming.
C program is a group of building blocks called Function.
C is a general-purpose structured programming language that is powerful, efficient and
compact.
C combines the features of a high-level language with the elements of the assembler and is,
thus, close to both man and machine.
Easy to learn
Structured language
Produces efficient programs
Can handle low-level activities
Can be compiled on a variety of computers
History of C
Dennis Ritchie invented C language. Ken Thompson created a language which was based upon
a language known as BCPL and it was called as B. B language was created in 1970, basically for UNIX
operating system Dennis Ritchie used ALGOL, BCPL and B as thebasic reference language from which
he created C.
The success of Unix was the most important factor as Unix used C for building its utilities, its
success had carried C.
C remained a simple and small language meant for building system components. C was held to be
sufficiently abstract that humans can read – which is why C is considered a middle-level language.
C was not designed in isolation but to write useful tools that interact with large systems. C is
regarded as a tool for building larger tools.
(Linux,Database,3D Movie)
#include <stdio.h>
int main()
{
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
}
Output
Hello, World!
Pre-processor Commands
Functions
Variables
Statements & Expressions
Comments
The following program is written in the C programming language. Open a text file hello.cusing
editor and put the following lines inside that file.
#include <stdio.h>main()
{
..... /* My first program*/
- Decode: The control unit then decodes the newly received instruction.
- Execute: During the execution the Control unit first commands the correct part of hardware to take
action.
1.5 CONSTANTS
A constant is a name given to the variable whose values can't be altered or changed. A constant is
very similar to variables in the C programming language, but it can hold only a single variable during the
execution of a program.
1.6 VARIABLES
Variables are containers for storing data values, like numbers and characters.
Each variable in C has an associated data type. It specifies the type of data that the variable can
store like integer, character, floating, double, etc. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. The data type is a
collection of data with values having fixed values, meaning as well as its characteristics.
The character set is set of valid characters’ which are recognized by language compiler. A
character denotes any alphabet, digit or special symbol used to represent information. The type
char is used to store a single character.
o All the uppercase letters A to Z, lowercase letters a to z, the digits 0 to 9 and some
special symbols are called characters.
o A character must be a single value character and should be enclosed between two
single quotation marks. For example 'a', 'b', 'c', '1', '2', '>', '?' etc.
Special Symbols:
s.no Spl.char Meaning s.no Spl.char meaning
1 < Less than 12 ] Right square bracket
2 > Greater then 13 ( Left parentheses
3 : Colon 14 ) Right parentheses
4 , Comma 15 / slash
5 { Left brace 16 \ Back slash
6 } Right brace 17 ` Tilde
7 [ Left square bracket 18 + plus
8 - Minus 19 & Ampersand
9 * Asterisk 20 _ Underscore
10 % Percentage 21 = Equal
11 # Hash 22 “ Double quote
1.9 C TOKENS
C tokens are the basic buildings blocks in C language which are constructed together to writea
C program.
Each and every smallest individual unit in a C program are known as C tokens.
Keywords
Identifiers
Constants
Strings
Special symbols
Operators
Keywords
There are certain reserved words called keywords that have standard, predefined meaning
in C. These keywords can be used only for their intended purpose but they cannot be used as
programmer defined identifiers. They are 32 in numbers as shown in below:
Keywords
Auto double Long typedef
Break else Register union
Case extern Return unsigned
Char float Short void
Const for size of volatile
continue goto Static while
default if Struct enum
Do int Switch signed
Identifiers
Identifiers are the names that are given to various program elements like variables,
functions, arrays and procedures.
Identifiersconsist of letters and digits in any order, except the first character must beletter.
Both upper case and lower case letters are permitted but commonly lower case lettersare
used.
And both upper case and lower case are not interchangeable.
The underscore (_) can also be included and is considered as to be letter. Anunderscore is
often used in middle of an identifier.
The ANSI (American National Standard Institute) compiler allows at least 31characters in
an identifier name.
1.11 CONSTANTS
A constant value is the one which does not change during the execution of a program.
C supports several types of constants:
Constants
Integer Constants
Real Constants
Character Constants
Single CharacterConstants
String Constants
Integer Constants
1. Decimal integer
2. Octal integers
3. Hexadecimal integer.
0743
034
043567
0x4 0x9f
0x63
0X643
Real Constant
Real Constants consists of a fractional part in their representation. Integer constants are
inadequate to represent quantities that vary continuously. These quantities are represented by
numbers containing fractional parts like 25.052. For example, valid real constants are
5000.0
String Constants
A string constant is a set of characters enclosed in double quotation marks. The characters
in a string constant sequence may be an alphabet, number, special character and blank space. For
Example, valid string constants are 'John' '12456' 'HELLO !'
1.12 VARIABLES
A variable is a data item whose value can change during execution of program. It is a
memory location used to store a data value. Variable names are case sensitive.
Example of variable names is
employee
student_id
image1
Examples of invalid variable names are435
2_name
%cdf Rules
apply on variables
VARIABLE DECLARATION IN C
A variable declaration provides assurance to the compiler that there is one variable existing with
the given type and name so that compiler proceed for further compilation without needing
complete detail about the variable.
1.13 DATATYPES
"Data type can be defined as the type of data of variable or constant store."
When we use a variable in a program then we have to mention the type of data. This can be
handled using data type in C. the variety of data types available allow the programmer to select the
type appropriate to the needs of the application as well as the machine.
Integers are most commonly data type used in C. int are used for all arithmetic’s and
logical operations. The integer variables in C are declared as
int x; inty,z;
int w = 10;
These statements declares integer variable x,y,z and w which can store integer values.
Rules apply on int
It can't be fractional.
No blank space or comma is allowed.
Memory occupied by int value is of 2 bytes.
It can vary from -32768 to +32767.
To display anint variable the %d is used.
The type char is used to store a single character. All the uppercase letters A to Z, lowercase
letters a to z, the digits 0 to 9 and some special symbols are called characters. A character must be
a single value character and should be enclosed between two single quotation marks. The char in
C are declared as.
Floating point numbers are numbers having a decimal point number. they have greaterrang
and express in decimal numbers. So, they are sometimes called as real numbers. The floating point
variables in C are declared as float x;
float length, breath;float z
= 10.50;
These statements declare floating point variable x, length, breath and z which can store floatvalues.
For example:
int age;
float weight;
char gender;
Value = amount+rate*amount;
variable_name= constant;
Variables can be declared as constants by using the “const” keyword before the datatype of the
variable. The constant variables can be initialized once only.
const int height = 8;
1.18 AS VOLATILE
The volatile keyword in C is used to indicate to the compiler that a variable's value may change
unexpectedly. This is often the case when a variable is being accessed by multiple threads or when it
represents hardware that is external to the computer.
1.19 OPERATORS
Assignment =
Arithmetic +, -, *, /, %
Unary ++, --
Conditional ()?:;
ARITHMETIC OPERATORS
Operator Meaning
+ Addition or Unary Plus
- Subtraction or Unary Minus
* Multiplication
/ Division
% Modulus Operator
The operands acted upon by Arithmetic Operators must represent numeric values. Thus,operands
can be integer, quantifier, floating point or characters.
Integer Arithmetic
Operation Result
x+y 13
x-y 7
When an arithmetic operation is performed on two real numbers or fraction numbers such
an operation is called floating point arithmetic.
Operation Result
x+y 14.5
x–y 10.5
x*y 25.0
RELATIONAL OPERATORS
The Relational Operators are used to performed comparisons between variables or between
variable and constant. The values of relational expression are either one or zero. It is one if the
specified relation is true and zero if the relation is false.
Operator Meaning
< is less than
> is greater than
is less than or
<=
equal to
is greater than
>=
or equal to
== is equal to
!= is not equal to
2. ((i+j)>=k) True 1
3. Ki=3 False 0
4. (j==2) True 1
When arithmetic expressions are used on either side of a relational operator, the arithmetic
expressions will be evaluated first and then the results compared.Relational expressions are
used in decision statements such as if and while to decide the course of action of a running
program.
LOGICAL OPERATORS
The logical operator is used for combining simple condition, and forming a complex
condition. That is, logical operators are used to combine two or more relational expression. They
return either a ‘true’ or ‘false’.
Operator Meaning
&& AND
|| OR
! NOT
AND & OR
Logical AND (&&) return true when both operands are true and false otherwise false.
Logical OR (||) return true when either of its operands are true and return false if boththe
operands are false.
NOT(!)
Logical NOT (!) return true when its operand result is false and return false when its operandresult
is true.
Operand !operand
1 0
0 1
EX:
43 (c!=’p’)||((i+f)<=10) True 1
ASSIGNMENT OPERATORS
The Assignment Operators are used to assign the result of an expression to a variable. It is
used to assign the R.H.S. value of any expression into L.H.S. variable. The most commonly used
Assignment Operators is ‘=’.
v op= exp;
The simple assignment operator (=) takes the following general form:
Syntax: <identifier><operator>=<expression>
Increments and Decrement Operators are also called Unary Operators because theyhave
only one operand.
++ Operator
-- Operator
Increment and decrement operators are unary operators and they require variable as their
operands.
When postfix ++(or --) is used with a variable in an expression, the expression is evaluated
first using the original value of the variable and then the variable is incremented (or
decremented) by one.
When prefix ++ (or --) is used in an expression, the variable is incremented (or decremented)
first and then the expression is evaluated using the new value of the variable.
The precedence and associatively of ++ and – operators are the same as those of unary
+ and unary -.
Conditional Operator also called Ternary Operator because it have three operands andcan
be written out with (? :). It is used to evaluate an expression returning a value if that expression is
true and a different one if the expression is evaluated as false.
The operator?: works as follows: exp1 is evaluated first. If it is nonzero (true), then the expression
exp2 is evaluated and becomes the value of the expression. If exp1 is false, exp3 isevaluated and
its value becomes the value of the expression. Note that only one of the expressions (either exp2
or exp3) is evaluated.
Expression Result
7 == 5 ? 4 : 3 returns 3, since 7 is not equal to 5
7 == 5 + 2 ? 4 : 3 returns 4, since 7 is equal to 5 + 2
returns the value of a, since 5 is
5 >3 ? a : b
greaterthan 3
1.20 EXPRESSION
1. Arithmetic expression
2. Relational expression
3. Logical expression
Arithmetic Expression
a*b–c axb–c
(m + n) * (x + y) (m + n) (x + y)
a*b/c (ab / c)
EVALUATION
3*x*x+2*x+1 3x2 +2x + 1
OF
EXPRESSIONS
Variable = expression;
x = a * b – c;y = b /
c * a;
z = a – b / c + d;
IMPORTANT QUESTIONS
2 Marks
1. Define constant.
2. What is meant by Operand?
3. What is Character set?
4. What are the fundamental data types available in C?
5. Write Importance of C.
6. Define variables.
7. Define data types.
8. How to declare a variable?
9. Define Keywords.
10. What are the classification of constants in C?
5 Marks
1. Describe the Data types in C.
2. Write a Sample C program.
3. Describe the basic Structure of C program.
4. Discuss about expression.
10 Marks
1. Explain Operators in C.
2. Explain about constants with examples.
3. Explain about variables with example.
UNIT II
CONTROL STATEMENTS
Control statements are required where we want to have any control over the executionof the
statement i.e. whether to execute any set of statement and for how many times is statement would
be executive. These statements control the flow of execution.
If Statement
Switch Case
Go to Statement
Conditional Operator
The if statement is a powerful decision-making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used in conjunction
with an expression. It takes the following form:
if (test expression);
It allows the computer to evaluate the expression first and then, depending on whether the value of
the expression (relation or condition) is ‘true’ (or non-zero) or ‘false’ (zero’), it transfers the control
to a particular statement. This point of program
Entryhas two paths to follow, one for the true condition
and the other for the false condition.
Fals
Test
True
The if statement implemented in different forms depending on the complexity of conditionsto be
tested. The different forms are:
1. Simple if statement
2. if… else statement
3. Nested if…. Else statement
4. else if ladder
2.2 SIMPLE IF
This is a conditional statement used in C to check condition or to control the flow of
execution of statements. This is also called as 'decision making statement or control statement.'
The execution of a whole program is done in one direction only.
Syntax
if(condition)
{
Statements;
}
2.3 ELSE IF
This is also one of the most useful conditional statements used in C to check conditions.
Syntax
if(condition)
{
true statements;
}
else
{
false statements;
}
It is a conditional statement which is used when we want to check more than 1 condition at a
time in a same program. The conditions are executed from top to bottom checking each condition
whether it meets the conditional criteria or not. If it found the condition is true then
it executes the block of associated statements of true part else it goes to next condition toexecute.
Syntax
if(condition)
{
if(condition)
{
Statements;
}
else
{
Statements;
}
}
else
{
Statements;
}
If (condition1) Statement
– 1; Else if (condition2)
Statement-2;
Else if (condition3)
Statement-3;
Else if (condition)
Statement-n;
Else
Syntax Description
2.6 SWITCH
This is a multiple or multi-waybranching decision making statement.
When we use nested if-else statement to check more than 1 condition then the
complexity of a program increases in case of a lot of conditions.
Switch case checks the value of a expression against a case values, if condition
matches the case values then the control is transferred to that point.
Syntax
switch(expression)
{
case expr1:
Statements-1;break;
case expr2:
Statements-2;break;
''''''''''''''''
''''''''''''''''
Case expr-n:
Statements-n;break;
default:
}
In above syntax, switch, case, break are keywords.
The expression is an integer expression or characters.
expr1, expr2 are known as 'case labels.'
Caselabels end with a semicolon (: ).
If case is found whose value matches with the value of the expression, then the
block of statements that follow the case are executed.
Statements inside case expression need not to be closed in braces.
Break statement causes an exit from switch statement.
Default case is optional case. When neither any match found, it executes.
goto [expr];
Figure
2.8 DECISION MAKING AND LOOPING
'A loop' is a part of code of a program which is executed repeatedly. A loop is used using
condition. The repetition is done until condition becomes condition true.
A loop declaration and execution can be done in following ways.
Basically, the type of looping statements depends on the condition checking mode. Condition
checking can be made in two ways as: Before loop and after loop. So, there are 2(two) types of
looping statements.
Controlled Loop
In such type of loop, the test condition is checked first before the loop is executed.
Some common examples of these looping statements are:
o while loop
o for loop
o do-while loop
2.8.1 WHILE
This is an entry controlled looping statement. It is used to repeat a block of statements until
condition becomes true.
Syntax while(condition)
{
statements;
increment/decrement;
}
Program
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
++i;
}
return 0;
}
Output
1
2
3
4
5
2.8.2 DO-WHILE
This is an exit controlled looping statement.
Sometimes, there is need to execute a block of statements first then to check condition. At that
time such type of a loop is used. In this, block of statements are executed first and then condition
is checked.
Syntax
do
statements; (increment/decrement);
}while(condition);
2.8.3 FOR
In this loop structure, more than one variable can be initialized. One of the most important features
of this loop is that the three actions can be taken at a time like variable initialization, condition
checking and increment/decrement. The for loop can be more concise and flexible than that of
while and do-while loops.
Syntax
for(initialisation; test-condition; incre/decre)
Statements;
#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
2 Marks
1. Define GOTO.
2. What is meant by JUMP Statement?
3. Write the Syntax of IF Statement.
4. Write the difference between While and Do while.
5. Write the Syntax of For loop.
6. Define ‘IF’ Statement.
7. What is meant by break statement.
8. Write the syntax of Switch Statement.
9. What are the types of Control Statement?
10. What are the types of Branching Statement?
5 Marks
1. Write the difference between While and Do while.
2. Explain Switch and Goto Statement.
3. Write the difference between IF and Else IF.
10 Marks
1. Discuss in detail about Control Statement.
2. Discuss in detail about Branching Statement.
UNIT III
ARRAYS
Array is a collection of homogenous data stored under unique name. The values in an array are
called as 'elements of an array.' These elements are accessed by numbers called as 'subscripts or
index numbers.' Arrays may be of any variable type.Array is also called as 'subscripted variable.'
Types of an Array
The array which is used to represent and store data in a linear form is called as 'single or one
dimensional array.'
Syntax
<data-type><array_name> [size];
Example
Declaration
Like any other variable, arrays must be declared before they used but with adifference of
squarebrackets [].
The type specifies the type of the elements that will be contained in the array, such as int floator
char and the size indicates the maximum number of elements that can be stored inside the array
for ex:
float height[50];
Initialization of arrays
We can initialize the elements in the array in the same way as the ordinary variables when they are
declared. The general form of initialization off arrays is:
Disadvantages
The array which is used to represent and store data in a tabular form is called as 'two
dimensional array.' Such type of array specially used to represent data in a matrix form.
Syntax
<data-type><array_nm> [row_subscript][column-subscript];
Example
inta[3][3];
Like one dimensional arrays, two dimensional arrays may be initialized during theirdeclaration
as
It will declare a array variable with two subscript values and value inserting in this array will be start
from row to column direction. we can write above statement by surrounding element of each row
by braces as
Initialization
Like one dimensional arrays, two dimensional arrays may be initialized during theirdeclaration
as
It will declare a array variable with two subscript values and value inserting in this array will be start
from row to column direction. we can write above statement by surrounding element of each row
by braces as
c[2][3]={{1,3,0}, {-1,5,9}};
OR
int c[][3]={{1,3,0}, {-1,5,9}};
OR
int c[2][3]={1,3,0,-1,5,9};
IMPORTANT QUESTIONS
2 Marks
1. Define Arrays.
2. Write the declaration of Arrays.
3. Write the Initialisation of one dimensional Arrays.
4. What are the types of Arrays.
5. Define Multi dimensional Arrays.
5 Marks
1. Write the Declaration and Initialisation of One dimensional Arrays.
2. Briefly explain Multi dimensional Arrays.
10 Marks
1. Explain the Declaration and Initialisation of Arrays.
UNIT IV
FUNCTIONS
C functions can be classified in two categories: Library functions and User defined functions.
The difference between this two functions is, Library functions are already built in and we need not
to write its code, whereas a User defined function has to be written to get it executed during the
output.
A function definition, also known as function implementation shall include the following
elements;
1. function name
2. function type
3. list of parameters
4. local variable declarations
5. function statements
6. a return statement.
All the six elements are grouped into two parts, namely,
1. Function header(first three elements)
2. Function body(second three elements)
Syntax
return;or
return (expression);
The first, the ‘plain’ return does not return any value; it acts much as the closing brace of the
function. When a return is encountered, the control is immediately passed back to the calling
function.
As example of the use of a simple return is as follows:
if(error)return;
/* function declaration */
int max(int num1, int num2);
int main () {
return 0;
}
return result;
}
Output
Max value is : 200
#include <stdio.h>
void printArray(int * arr, int size)
{
int i;
printf("Array elements are: ");
for(i = 0; i < size; i++)
{
printf("%d, ", arr[i]);
}
}
int main()
{
int arr[5];
printArray(arr, 5); // Pass array directly to function printArray
return 0;
}
Output: Array elements are: 0, 0, -295874432, 22032, -735842928,
The call by value method of passing arguments to a function copies the actual value of an argument into
the formal parameter of the function.
// Main function
int main()
{
int a = 10, b = 20;
// Pass by Values
swapx(a, b);
printf("In the Caller:\na = %d b = %d\n", a, b);
return 0;
}
// Swap functions that swaps
// two values
void swapx(int x, int y)
{
int t;
t = x;
x = y;
y = t;
printf("Inside Function:\nx = %d y = %d\n", x, y);
}
Output
Inside Function:
x = 20 y = 10
In the Caller:
a = 10 b = 20
In call by reference method of parameter passing, the address of the actual parameters is passed to
the function as the formal parameters.
Both the actual and formal parameters refer to the same locations.
Any changes made inside the function are actually reflected in the actual parameters of the caller.
// Function Prototype
void swapx(int*, int*);
// Main function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b);
return 0;
t = *x;
*x = *y;
*y = t;
Output
The following table lists the differences between the call-by-value and call-by-reference methods of
parameter passing.
In this method, the value of each variable in the In this method, the address of actual variables in the
calling function is copied into corresponding calling function is copied into the dummy variables of
dummy variables of the called function. the called function.
In call-by-values, we cannot alter the values of In call by reference, we can alter the values of
actual variables through function calls. variables through function calls.
Values of variables are passed by the Simple Pointer variables are necessary to define to store the
technique. address values of variables.
This method is preferred when we have to pass This method is preferred when we have to pass a
some small values that should not change. large amount of data to the function.
4.10 STORAGE CLASSES
Variables in C have not only data type but also storage class that provides informationabout
their location and visibility. The storage class decides the portion of the program withinwhich the
variables are recognized.
int m; main()
{
inti;
float balance;
…….
……. function1;
}
function1()
{
inti;
float sum;
…….
……
}
A string is actually a one-dimensional array of characters in C language. These are often used to
create meaningful and readable programs.
A character array is a collection of variables which are of character datatype. String is a class that is
instantiated to declare strings. Using index value you can access a character from a character array.
1. A character array is a collection of variables which are of character datatype. String is a class that is
instantiated to declare strings.
2. Using index value you can access a character from a character array. On the other hand, if you want to
access a particular character in a string, you can access it by function string’s_name.charAt(index).
3. As an array is not a datatype similarly a character also is not a datatype. On the other hand, String
being a class act as a reference type hence, it can be said String is a data type.
4. You can not apply any operator on a character array whereas, you can apply operators on String.
5. Being an array character array has a fixed length and its boundaries can be easily overrun. Where
String does not have any boundaries.
6. Array elements are stored in a contiguous memory location hence that can be accessed faster than
string variable.
IMPORTANT QUESTIONS
2 Marks
1. Define Function.
2. Write the categories of Function.
3. Define Recursion.
4. What is meant by Storage Class.
5. Define nested function.
5 Marks
1. Explain fuction with arrays.
2. Explain the form of C function.
3. Write the C program for Recursion Function.
10 Marks
5.1 DEFINITION
Pointer is a variable which holds the memory address of another variable. Pointers are
represented by '*'. It is a derive data type in C. Pointer returns the value of stored address.
Syntax
<data_type> *pointer_name;
C supports a rich set of built-in operations like arithmetic, relational, assignment, conditional, etc.
which can be performed on identifiers. Just like any other variable, these operations can be
also performed on pointer variables.
Example: c = (*ptr1 > *ptr2) ? *ptr1 : *ptr2; As shown in example, assuming *ptr1=20 and *ptr2=10 then the
condition here becomes true for the expression, so it'll return value of true expression i.e. *ptr1, so variable
'c' will now contain value of 20. Address of variable x = 0x7fff3b690fd4
Arithmetic Operators
We can perform arithmetic operations to pointer variables using arithmetic operators. We can add
an integer or subtract an integer using a pointer pointing to that integer variable. The given table shows
the arithmetic operators that can be performed on pointer variables: Examples:*ptr1 + *ptr2
*ptr1 * *ptr2
*ptr1 + *ptr2 - *ptr3
We can also directly perform arithmetic expressions on integers by dereferencing pointers. Let’s look at
the example given below where p1 and p2 are pointers.
*p1 + 10, *p2 - 5, *p1 - *p2 + 10, *p1/2
int main()
{
// Integer variables
int a = 20, b = 10;
// Printing values
printf("Addition = %d\n", add);
printf("Subtraction = %d\n", sub);
printf("Multiplication = %d\n", mul);
printf("Division = %d\n", div);
printf("Modulo = %d\n", mod);
return 0;
}
Output:
Addition = 30
Subtraction = 10
Multiplication = 200
Division = 2
Modulo = 0
Note: While performing division, make sure you put a blank space between ‘/’ and ‘*’ of the pointer as
together it would make a multi-line comment(‘/*’). Example:
Incorrect: *ptr_a/*ptr_b;
Correct: *ptr_a / *ptr_b;
Correct: (*ptr_a)/(*ptr_b);
Relational Operators
Relational operations are often used to compare the values of the variable based on which we can
take decisions. The given table shows the relational operators that can be performed on pointer variables.
Example:
The value of the relational expression is either 0 or 1 that is false or true. The expression will return
value 1 if the expression is true and it’ll return value 0 if false.
// Equal to
if (*ptr_a == *ptr_b) {
printf(
"%d is equal to %d.", *ptr_a, *ptr_b);
}
return 0;
}
Output:
20 is greater than 10.
Output:
20 is greater than 10.
Assignment Operators
Assignment operators are used to assign values to the identifiers. There are multiple shorthand
operations available. A table is given below showing the actual assignment statement with its shorthand
statement. Examples:
*a=10
*b+=20
*z=3.5
*s=4.56743
return 0;
}
Output:
Value of variable a = 50
Conditional Operators
There is only one mostly used conditional operator in C known as Ternary operator. Ternary
operator first checks the expression and depending on its return value returns true or false, which
triggers/selects another expression.
Syntax: expression1 ? expression2 : expression3;
Example:
c = (*ptr1 > *ptr2) ? *ptr1 : *ptr2;
As shown in example, assuming *ptr1=20 and *ptr2=10 then the condition here becomes true for the
expression, so it’ll return value of true expression i.e. *ptr1, so variable ‘c’ will now contain value of 20.
Considering same example, assume *ptr1=30 and *ptr2=50 then the condition is false for the
expression, so it’ll return value of false expression i.e. *ptr2, so variable ‘c’ will now contain value 50.
// Program showing pointer expressions
// during Conditional Operations
#include <stdio.h>
int main()
{
// Initializing integer variables
int a = 15, b = 20, result = 0;
Examples:
(*ptr1)++
(*ptr1)--
return 0;
}
Output:
Increment:
Before increment a = 34
After increment a = 35
Decrement:
Before decrement a = 35
After decrement a=34
Bitwise Operators
Binary operators are also known as bitwise operators. It is used to manipulate data at bit level.
Bitwise operators can’t be used for float and double datatype. A table is shown below with all bitwise
operators:
Examples:
*ptr1 & *ptr2
*ptr1 | *ptr2
*ptr1 ^ *ptr2
// OR operation
or = a | b;
// EX-OR operation
ex_or = a ^ b;
When we increment pointer its value is increased by the length of the data type that it points to. This
length is called scale factor.
Ex :- if p1 is an integer pointer with the initial value say 2800,then after the operations p1=p1+1,the value of
p1 will be 2802,not 2801. when we increment pointer its value is increased by the length of the data type
that it points to. This length is called scale factor
.
5.6 POINTERS AND ARRAYS
When an array is declared, the compiler allocates a base Address and sufficient amount of storage
to contains all the elements of the array in memory location. Base address is the location of the first
element of the array.
If we declare p as integer pointer, then we can make the pointer p to point to the array x by the following
statements.
p = x or p = &x[0]
Now we can access every element of x using p++ to move from one element to another.
p = &x[0] (=1000)
p+1 = &x[1] (=1002)
p+2 = &x[2] (=1004)
p+3 = &x[3] (=1006)
p+4 = &x[4] (=1008)
for(i=0;i<n;i++)
{
printf("\n%d",*p);
sum=sum + *p;
p++;
}
printf("\nsum=%d",sum);
}
OUTPUT
Enter the N: 5
Enter the data :
12345
Sum=15
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a
simple example that shows declaration and function call using function pointer.
#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;
return 0;
}
Output:
Value of a is 10
Why do we need an extra bracket around function pointers like fun_ptr in above example?
If we remove bracket, then the expression “void (*fun_ptr)(int)” becomes “void *fun_ptr(int)” which is
declaration of a function that returns void pointer. See following post for details.
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a
simple example that shows declaration and function call using function pointer.
#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;
IMPORTANT QUESTIONS
2 Marks
1. Define Pointers.
2. Write the scale factor of pointers.
3. Write the declaration of pointers.
4. What is pointer and structure.
5. What are all the Pointer expression?
5 Marks
1. Explain pointer initialization and declaration.
2. Disucss about pointer and structure.
10 Marks
1. Describe about Pointer expression.
2. Explain: i)Pointers and arrays
ii)Pointers and Functions.