0% found this document useful (0 votes)
10 views

Unit 1 C notes

The document provides an overview of C programming, including the definition and characteristics of algorithms, flowcharts, structured and modular programming concepts, and the history and importance of the C language. It details the basic structure of C programs, programming style guidelines, the process of executing C programs, and the generation of executable code from source code. Additionally, it explains C tokens, including keywords, identifiers, constants, variables, and special symbols.

Uploaded by

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

Unit 1 C notes

The document provides an overview of C programming, including the definition and characteristics of algorithms, flowcharts, structured and modular programming concepts, and the history and importance of the C language. It details the basic structure of C programs, programming style guidelines, the process of executing C programs, and the generation of executable code from source code. Additionally, it explains C tokens, including keywords, identifiers, constants, variables, and special symbols.

Uploaded by

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

C PROGRAMMING

Algorithm :

An algorithm is a finite set of unambiguous instructions which, when executed, performs a


correct a task correctly.
Algorithm is a finite sequence of instructions, each of which has a clear meaning and can be
performed with a finite amount of effort in a finite length of time.
There are three characteristics features in this description of an algorithm. They are
• The number of steps required to perform the task should be finite.
• Each of the instruction in the algorithm should be unambiguous in nature, meaning on
the execution of each such instruction, the outcome should be definite and predictable.
• The algorithm should solve the problem correctly In other word, on the execution of
the algorithm, the objective should be fulfilled.
Example :
Problem statement- Develop an algorithm to find the average of three numbers taken as
input from the user.
Algorithm Average:
Step 1: Start
Step 2: Input first number into variable a
Step 3: Input second number into variable b
Step 4: Input third number into variable c
Step 5: Compute sum = num1+ num2 + num3
Step 6: Compute Avg =sum/3
Step 7: Display Avg
Step 8: Stop/End

Flowchart
A Flowchart helps us graphically visualize the flow of control within the sequence of
statements. Or It is diagrammatical/graphically representation of given algorithm.
Symbol Purpose Description

Used to indicate the flow of logic by connecting


Flow line
symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/Output Used for input and output operation.

Used for arithmetic operations and data-


Processing
manipulations. This box is used to represent
processing operations.

It is used to represent conditional statement


Desicion
constructs. true and false

On-page Connector This symbol is used to transfer the flow of control from
one point on a page to another point on a different
page. This notation is useful when the flowchart spans
more than one page. (Next Page)

Off-page Connector This symbol is used to transfer the flow of control from
one point to another within a page. A connector isusually
labelled to match with its counterpart. (Same Page)

Predefined Used to represent a group of statements performing


Process/Function one processing task.
Example: Flowchart of an algorithm to find average of three numbers.

Structured Programming:
Structured programming is a programming paradigm that emphasizes organizing code into
logical, well-structured modules, each with a single entry and exit point. It focuses on:

1. Top-down design: Breaking down a program into smaller, manageable functions.

2. Functional decomposition: Dividing a program into smaller, independent functions,


each with a specific task.
3. Control structures: Using if-else statements, loops, and switch statements to control
program flow.

In C, structured programming involves:-

• Writing functions with a clear purpose and minimal side effects.

• Using loops and conditional statements to control program flow.


• Avoiding goto statements and global variables.

Modular Programming:
Modular programming takes structured programming a step further by emphasizing the
separation of concerns and independent modules. It involves:

1. Modular design: Breaking down a program into independent, reusable modules, each
with its own interface and implementation.

2. Encapsulation: Hiding implementation details within a module and exposing only


necessary information through an interface.
3. Abstraction: Focusing on essential features and hiding non-essential details.

In C, modular programming involves:-


• Writing separate source files (modules) for each logical component

• Using header files to define interfaces and declare functions

• Implementing functions in separate source files


• Linking modules together to form the final program

Introduction of C :
The root of all modern languages is ALGOL (Algorithmic Language). ALGOL was the first
computer programming language to use a block structure, and it was introduced in 1960. In
1967, Martin Richards developed a language called BCPL (Basic Combined Programming
Language). BCPL was derived from ALGOL. In 1970, Ken Thompson created a language
using BCPL called B. Both BCPL and B programming languages were typeless.
After that, C was developed using BCPL and B by Dennis Ritchie at the Bell lab in 1972. So,
in terms of history of C language, it was used in mainly academic environments, but at long
last with the release of many C compilers for commercial use and the increasing popularity of
UNIX, it began to gain extensive support among professionals.
Importance of C
1. C is a high level language.

2. It is a structured programming language.


3. C is user friendly language
4. C supports set of operators.

5. C is best suited as compiler.

6. C provides collection of built- in function like printf() and scanf().

7. It supports library functions


Example: stdio.h, conio.h, stdlib.h etc

8. C is a portable
Basic structure of c programs

1. Documentation Section
This section consists of the description of the program, the name of the program, Anything
written as comments will be treated as documentation of the program.

// description, name of the program (single line comment)

/* description, (multi-line comment)


name of the program */

2. Preprocessor / Link Section


All the header files of the program will be declared in the preprocessor section of the
program. Header files help us to access other‟s improved code into our code.

Example:
#include<stdio.h>
#include<math.h>
Preprocessors are the programs that process our source code before the process of compilation.
There are multiple steps which are involved in the writing and execution of the program.

3. Definition Section
The definition section defines all symbolic constants. A symbolic constant is a constant value given
to a name which can't be changed in program.
Example: #define PI 3.14

4. Global Declaration
The global declaration section contains global variables, function declaration, and static
variables. Variables and functions which are declared in this scope can be used anywhere in
the program.

Example: int num = 18;

5. Main() Function Section


The return type of the main() function can be int as well as void too. void() main tells the
compiler that the program will not return any value. The int main() tells the compiler that the
program will return an integer value.

Example: void main() or int main()

6. Sub Programs
User-defined functions are called in this section of the program. The control of the program is
shifted to the called function whenever they are called from the main or outside the main()
function.

Example: int sum(int x, int y)

{
return x+y;
}

Sample of C Programs :
Example 1: A program to print one line of text.
Code: #include<stdio.h>
Void main()
{
/* …… printing begins…….*/
printf(“I see, I remember.”);
/*……..printing ends………*/
}
Output : I see, I remember.

Example 2: Program to find the average of three numbers.


#include<stdio.h>
void main()

{
int num1=7, b=num2, num3=6,sum, average;
printf(“Enter first number :");

printf("%d\n",num1);

printf(“Enter second number :");


printf("%d\n",num2);
printf(“Enter third number : ");

printf("%d\n",num3);
sum=num1+num2+num3;

average =sum/3;

printf("the sum of 3 number is = %d\n",sum);


printf("the average of 3 numbers is = %d", average);
getch();
}
Output:

Enter first number: 7


Enter second number: 8
Enter third number: 6
The sum of 3 numbers is = 21
The average of 3 numbers is = 7
Programming Style :
1. Indentation and Spacing –
• Use 4 spaces for indentation
• A proper indentation of braces and statements would make a program easier and
debug.
• Use 1 space between identifiers and operators
• Use 1 blank line between functions and variable declarations
2. Naming Conventions –
• Use lowercase letters and underscores for variable and function names
• Use uppercase letters for symbolic constants
3. Comments –
• Use /* … */ for multi-line comments
• Use // for single-line comments
• Place comments above the code they describe
• Keep comments concise and up-to-date
4. Code Organization –
• Break down large programs into smaller functions and modules
• Use header files to separate declarations and implementations
• Use #include guards to prevent multiple inclusions

Executing a 'C' Programs:


Executing the program written in C involves a series of steps. There are :
1. Creating the program
2. Compiling the program
3. Linking the program with functions that are needed from the C library , and
4. Executing the program
1. System Ready: The system is prepared to receive and process the C program.
2. Program Code: The C program code is entered into the system.
3. Edit Source Program: The entered code is reviewed and modified as needed to
ensure correctness and efficiency.
4. Compile Source Program: The C compiler translates the source code into
machine-readable object code.
5. Syntax Errors: If there are any syntax errors in the code, the compiler will
identify and report them.
6. Link with System Library: The object code is linked with necessary system
libraries to create an executable program.
7. Input Data: The program is provided with the required input data.
8. Execute Object Code: The executable program is run, and the code is executed.
9. Logic & Data Errors: If there are any logical errors or errors in the input data,
the program may produce incorrect output.
10. Correct Output: If the program executes correctly and the input data is valid, the
correct output is produced.
11. Stop: The program execution is terminated.

The process of compiling and running a C program involves entering the code, checking
for errors, translating the code into machine language, linking with necessary libraries,
providing input data, executing the program, and verifying the output. This sequence
ensures that the program is syntactically correct, logically sound, and produces the desired
results.

Generation of Executable code from Source Code

• Source code is the file containing the c program. The program input to a compiler.
The compiler is a system software that translate the source program to object code.

• The object contains an equivalent set of machine instructions corresponding to the


source program which is understood by by the computer.

• A given c program may make use of several library functions. The object code of the
program would have to be linked to the object codes of the library functions.

• The linker is a system software that links together all the object codes to generate the
final executable code.

• The executable code is submitted to the operating system for execution whenever
required.
C Tokens
In passage of text, individual words and punctuation marks are called Tokens.

In a C program the smallest individual units are known as C Tokens. C has six types of
tokens. They are

1. C Token – Keywords
• The keywords are pre-defined or reserved words in a programming language.
• Each keyword is meant to perform a specific function in a program. Since keywords
are referred names for a compiler, they can‟t be used as variable names because by
doing so, we are trying to assign a new meaning to the keyword which is not allowed.

• You cannot redefine keywords. However, you can specify the text to be substituted for
keywords before compilation by using C preprocessor directives.
C language supports 32 keywords which are given below:
2. C Token – Identifiers
• Identifiers are used as the general terminology for the naming of variables, functions,
and arrays.

• These are user-defined names consisting of an arbitrarily long sequence of letters and
digits with either a letter or the underscore(_) as a first character.

• Identifier names must differ in spelling and case from any keywords.
• You cannot use keywords as identifiers; they are reserved for special use. Once
declared, you can use the identifier in later program statements to refer to the associated
value.

Rules for Naming Identifiers


• They must begin with a letter or underscore(_).
• They must consist of only letters, digits, or underscore. No other special character is
allowed.

• It should not be a keyword.

• It must not contain white space.

• It should be up to 31 characters long as only the first 31 characters are significant.


For example,

main: method name.


a: variable name

3. C Token- Constants :
The quantity which does not change during the execution of a program is known as constant.
The constants refer to the variables with fixed values. They are like normal variables but with
the difference that their values can not be modified in the program once they are defined.
Constants may belong to any of the data types.
Examples of Constants in C
const int c_var = 20;

Types of C constants.

1. Integer Constants: Whole numbers, either positive, negative, or zero, without a fractional
part.
Example: 123, -456
• Hexadecimal Constants : Hexadecimal integer constants are integer constants
having sequence of digits preceded by 0x or 0X. They may also include
alphabets from A to F representing numbers 10 to 15.

Example: 0x1A, 0xFF, 0X8d, 0xbD

• Octal Constants: Integer constants consisting of sequence of digits from the


set 0 through 7 starting with 0 is said to be octal integer constants.

Example: 012, 077, 0540

• Decimal Constants: Integer constants consisting of a set of digits, 0 through


9, preceded by an optional – or + sign. Example of valid decimal integer
constant.
Example: 123, -567 , 0 , +56

2. (Real) Floating-Point Constants: The numbers having fractional parts are called real
or floating point constants. These may be represented in one of the two forms called
fractional form .
Example: 3.14, -0.5, -247.32, +121.44

3. Character Constants: A character constant contains one single character enclosed


within single quotes
Example: 'a', '!„, „?‟, „z‟, „ ‟

4. String Constants : String constants are sequence of characters enclosed within double
quotes.
Example: "hello", "goodbye“,”1987”, “College”, “India”
Escape Characters/ Escape Sequences

C allows us to have certain non graphic characters in character constants. Non graphic
characters are those characters that cannot be typed directly from keyboard, for
example, tabs, carriage return, etc.
These non graphic characters can be represented by using escape sequences
represented by a backslash() followed by one or more characters.
Here are some common character constants:

1. Newline: \n
2. Tab: \t
3. Carriage Return: \r
4. Backslash: \
5. Single Quote: „/”
6. Double Quote: „/””
7. Bell: \a
8. Form Feed: \f
9. Vertical Tab: \v

4. C Token – variables
The quantity that changes during the execution of a program is called a variable. A variable
is nothing
but a name given to a storage area that our programs can manipulate.
Syntax: datatype variablename;
Ex : int sum;
Examples: a, b, sum, si, age, city etc..
A variable is a named storage location that holds a value. Variables allow you to store,
manipulate, and reuse data in your code.
Variable names may consist of letters, digits, and the underscore(_) character, subject
to the following
• They must begin with a letter.
• Uppercase and lowercase letters are significant. That variable Total is not same as
total or TOTAL.

• It should not be a keyword.


• White space is not allowed.
5. Special Symbols
The following special symbols are used in C having some special meaning and thus,
cannot be used for some other purpose.

[] () {} , ; : * … = #

Braces{}: These opening and ending curly braces marks the start and end of a block
of code containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls and
function parameters.
Brackets[]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.

6. C Token – Data Type

Integer Data Type

The integer datatype in C is used to store the integer numbers (any number including
positive, negative and zero without decimal part). Octal values, hexadecimal values,
and decimal values can be stored in int data type in C.
The integer data type can also be used as short int and long int.
short int
short int:
int
syntax: short int var_name;
int: long int
size: 1 byte
format Specifier: %hd syntax: int var_name;
size: 2 bytes
format Specifier: %d
long int:

syntax: long int var_name;


size: 4 bytes
format Specifier: %ld

Floating Data Type


Float in C is used to store decimal and exponential values. It is used to store decimal numbers
(numbers with floating point values) with single precision.
Syntax: float var_name;
The integer data type can also be used as short int and long int.
 Format Specifier: %f
 Size of float: 4 bytes

Double Data Type


A Double data type in C is used to store decimal numbers (numbers with floating point values)
with double precision. It is used to define numeric values which hold numbers with decimal
values in C.
Syntax: double var_name;
 Format Specifier: %lf
 Size of float: 8 bytes
float
float:
double
syntax: float var_name;
double: long double
size: 4 bytes
format Specifier: %f syntax: double var_name;
size: 4 bytes
format Specifier: %lf
long int:

syntax: long double var_name;


size: 16 bytes
format Specifier: %Lf

Character Data Type


Character data type allows its variable to store only a single character. The size of the character
is 1 byte. It is the most basic data type in C. It stores a single character and requires a single
byte of memory in almost all compilers.
Syntax: char var_name;
 Size: 1 byte
 Format Specifier: %c
Void Data Type
The void data type in C is used to specify that no value is present. It does not provide a result
value to its caller. It has no values and no operations. It is used to represent nothing. Void is
used in multiple ways as function return type, function arguments as void, and pointers to void.
// function return type void
Syntax: void exit(int check);

//Function without any parameter can accept void.


int print(void);
Example: void printHello()
{
printf(“Hello”);
}
• Boolean (_bool): True or false values.
Example: _bool isAdmin = true;
• Array (Collection of Values): A collection of values of the same type stored in
contiguous memory locations.
Example: int scores[5] = {90, 80, 70, 60, 50};
• Pointer (Memory Address): A variable that stores the memory address of another
variable.
Example: int *ptr = &x; // pointer to variable x
• Structure (Custom Data Type : A custom data type that combines multiple variables
of different types.
Example: struct Person
{
int age;
char name[20];
};

Declaration of variables :
1. Pre defined type declaration
Basic Syntax: Datatype variable_name;
Examples:
1. int x; // declares an integer variable x
2. float y; // declares a floating-point variable y
3. char c; // declares a character variable c
4. double z; // declares a double-precision floating-point variable z

2. User defined type declaration


In C, a user-defined type is a custom data type created by the programmer using the typedef
keyword. Or C supports a feature known as “type definition” that allows users to define an
identifier that would represent an existing data type.
General form : typedef datatype identifier;
Here's an example: typedef int units;
units batch1, batch2;
This creates a new type called units that is equivalent to the built-in int type.

3. Assigning values to Variables :


Values can be assigned to variables using the assignment operator = as follows:
Syntax : variable_name = constant ;
Example x = 6;
y = 4;
syntax : data type variable_name = constant;
Example: int x = 5; // assigns 5 to x
float y = 3.14; // assigns 3.14 to y
char c = 'A'; // assigns 'A' to c

Defining symbolic constants.


Identifiers are used to represent fixed values in programs using symbolic constants in the C
programming language.
These parameters are frequently used to increase the readability, maintainability, and
modifiability of code, which may be numerical or not. The C language's
"#define" command is used to declare symbolic constants.
Syntax:
Syntax for defining a symbolic constant in C:
#define MAX_V 100
#define PI 3.142159
Operators, Expression:
The definition section defines all symbolic constants. A symbolic constant is a constant value given
to a name which can't be changed in program.
C language offers many types of operators. They are,

Unary Operators

Unary operators operate on a single operand. They perform operations such as incrementing a
value, negating it, or performing logical NOT.

Binary Operators

Binary operators operate on two operands. They perform operations such as addition,
subtraction, multiplication, etc.

Ternary Operator

The ternary operator, also known as the conditional operator, operates on three operands. It is
a shorthand for the if-else statement

1. Arithmetic operators :
• Addition (+): The addition operator adds two or more numbers together.
Example: a+b = 5 + 3 = 8.
• Subtraction (-): The subtraction operator subtracts one number from another.
Example: a-b = 10 - 4 = 6.
• Multiplication (*): The multiplication operator multiplies two or more numbers
together.
Example: a*b = 6 * 9 = 54.
• Division (/): The division operator divides one number by another, resulting in a
quotient.
Example: a/b = 20 / 4 = 5.
• Exponentiation (^ or *): The exponentiation operator raises a number to a power.
Example: a^b = 2 ^ 3 = 8 or pow(base, exponential)

// C program to demonstrate syntax of binary arithmetic operators

#include <stdio.h>
#include<math.h>
int main()
{
int num1 = 10, num2 = 4, sum, sub, mul, div, power;

// printing num1 and num2


printf(“num1 is %d and num2 is %d\n", num1,num2);

sum = num1+num2; // addition


printf("num1+num2is %d\n", sum);

sub = num1-num2; // subtraction


printf("num1-num2is %d\n", sub);

mul = num1*num2; // multiplication


printf("num1*num2is %d\n", mul);

div = num1/num2; // division


printf("num1/num2is %d\n", div);

power = pow(num1,num2); // power value


printf("num1^ num2 is %d\n", power);
return 0;
}

Output
num1 is 10 and num2 is 4
num1+num2 is 14
num1-num2 is 6
num1*num2 is 40
num1/num2 is 2
num1^ num2 is ^10000
2. Relational operators in C:
These are used to compare two operands given in an expression. They define the relationship
that exists between two constants or variables. Results in either TRUE or FALSE.
There are six relational operators in C

 Less than: The ‘< ’ operator compares two operands. It compares less than or not.
For example, x<y. 10<5, result is false.

• Greater than: The ‘>’ operator compares two operands. It compares greater
than or not.
For example, x>y. 20>5,, result is true.

• Less than or equal to: The ‘<=’ operator compares two operands. It compares less
than or equal to or not.
For example, x<=y. 15<=5,, result is false.

• Greater than or equal to: The ‘>=’ operator compares two operands. It compares
greater than or equal to or not.
For example, x>=y. 15>=5,, result is true.

• Equal to: The ‘==’ operator compares two operands. It compares equal to or not.
For example, x==y. 15==5,, result is false.

• Not Equal to: The ‘!=’ operator compares two operands. It compares equal to or not.
For example, x!=y. 15!=5,, result is true.
// C program to demonstrate working of relational operators

#include <stdio.h>
int main()
{
int num1 = 10, num2 = 4;

// greater than example


if (num1 > num2)
printf("num1 is greater than num2\n");
else
printf("num1 is less than or equal to num2\n");

// greater than equal to


if (num1>= num2)
printf("num1 is greater than or equal to num2\n");
else
printf("num1 is lesser than num2\n");

// less than example


if (num1< num2)
printf("num1 is less than num2\n");
else
printf("num1 is greater than or equal to num2\n");
// lesser than equal to
if (num1 <= num2)
printf("num1 is lesser than or equal to num2\n");
else
printf("num1 is greater than num2\n");
// equal to
if (num1== num2)
printf("num1 is equal to num2\n");
else
printf("num1 and num2 are not equal\n");
// not equal to
if (num1 != num2)
printf("num1 is not equal to num2\n");
else
printf("num1 is equal num2\n");

return 0;
}
Output :
num1 is greater than num2
num1 is greater than or equal to num2
num1 is greater than or equal to num2
num1 is greater than num2
num1 and num2 are not equal
num1 is not equal to num2

3. Logical operators
This class of C operators is used to make decisions. Logical operators are used to evaluate
two or more conditions. The result of these operators is either TRUE or FALSE.

• Logical AND operator:


The logical AND operator is used to perform adding operation on two logical operands. The
result of logical AND is true, when both the operands are true. Otherwise the answer is false.

&& operator – If clause‖ becomes true only when both conditions if (a > 0 && b > 0) is
true. Else, it becomes false.
// C program for Logical AND Operator
#include <stdio.h>
int main()

int num1 = 10, num2= 20;


if (num1 > 0 && num2 > 0)

{
printf("Both values are greater than 0\n");

}
else
{

printf("Both values are less than 0\n");


}

return 0;
}

Output : Both values are greater than 0

• Logical OR operator:
The logical OR operator is used to perform OR operation on two logical operands. The result
of logical OR is false, when both the operands are false. Otherwise the answer is True.

|| Operator – ―if clause‖ becomes true when any one of the condition if (a > 0 || b > 0) is
true. It becomes false when none of the condition is true.
// C program for Logical OR Operator
#include <stdio.h>
int main()

{
int num1 = -1, num2 = 20;
if (num1> 0 || num2> 0)

printf("Any one of the given value is greater than 0\n");


}

else
{

printf("Both values are less than 0\n");


}

return 0;
}
Output : Any one of the given value is greater than 0

 Logical NOT operator:


If the given operand is true then the logical NOT operator will make it false and vice-versa.
Below is the truth table for the logical NOT operator.
! Operator – It is used to reverses the state of the operand.
If the conditions if (!(a > 0 && b > 0)) is true, true (1) is returned. This value is inverted
by ―!!.

X !X

0 1

1 0
// C program for Logical NOT Operator
#include <stdio.h>
int main()
{
int num1 = 10, num2= 20;
if (!(num1 > 0 && num2 > 0))
{
// condition returned true but
// logical NOT operator changed
// it to false
printf("Both values are greater than 0\n");
}
else
{
printf("Both values are less than 0\n");
}
return 0;
}
Output: Both values are less than 0

4. Assignment Operator:

Assignment operators are used for assigning 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 the
variable on the left side otherwise the compiler will raise an error.
The syntax is:

Examples:
sum = a + b;
a +=b;
//C program to demonstrate working of Assignment operators
#include <stdio.h>
int main()
{
int num1= 10;
int num2= 5;
num1 += num2; // num1 = num1 + num2, now num1 is 15
printf("num1 += num2: %d\n", num1);

num1-= num2; // num1 = num1 - b, now num1 is 10


printf("num1 -= num2: %d\n", num1);

num1 *= num2; // num1 = num1 * num2, now num1 is 50


printf("num1*= num2: %d\n", num1);

num1/= num2; // num1 = num1 / num2, now num1 is 10


printf("num1/= num2: %d\n", num1);

num1%= num2; // num1= num1 % num2, now num1 is 0


printf("num1 %%= num2: %d\n", num1);
return 0;
}}
Output
num1 += num2: 15
num1 -= num2: 10
num1*= num2: 50
num1/= num2: 10
num1 %= num2: 0
5. Increment & Decrement Operators:
Increment operator is used to increment the value of an integer quantity by one. Or
Increment operators are used to increase the value of the variable by one .
This is represented by „++‟ (double plus) symbol.
For example:
if int a = 3; then both a++ and ++a indicate a = a +1. Therefore, the value of a is 4.
++a indicates pre increment.
a++ indicates post increment.

//Example for increment operators


In this program, value of i is incremented one by one from 1 up to 9 using i++ operator
and output is displayed as ―1 2 3 4 5 6 7 8 9.

#include <stdio.h>
int main()
{
int num=1;
while(num<10)
{
printf("%d ",num);
num++;
}
}
Output: 1 2 3 4 5 6 7 8 9

• Pre Increment(++i) - Value of i is incremented before assigning it to variable i.


Example program for pre – increment operators in c

//Example for increment operators


#include <stdio.h>
int main()
{
int num=0;
while(++num < 5 )
{
printf("%d ",num);
}
return 0;
}

Output: 1 2 3 4

• Post Increment(i++) - Value it to variable i. of i is incremented after assigning it


to variable i.

//Example for increment operators


#include<stdio.h>
int main()
{
int num=0;
while(num++ < 5 )
{
printf("%d ",num);
}
return 0;
}

Output: 1 2 3 4 5

Decrement operator is used to reduce the value of an integer quantity by one.


This is represented by „--‟ (double plus) symbol.
For example:
if int a = 3; then both a-- and --a indicate a = a - 1. Therefore, the value of a is 2.
--a indicates pre decrement.
a-- indicates post decrement

Example program for decrement operators in c


In this program, value is decremented one by one from 20 up to 11 using ―I operator and
output is displayed as ―20 19 18 17 16 15 14 13 12 11‖
//Example for decrement operators
#include <stdio.h>
int main()
{
int num=20;
while(num>10)
{
printf("%d ",num);
i--;
}
}
Output: 20 19 18 17 16 15 14 13 12 11

• Pre Decrement - Value of i is decremented before assigning it to variable i.

//Example program for pre – decrement operators in c


#include <stdio.h>
int main()
{
int num=10;
while(--num> 5 )
{
printf("%d ",num);
}
return 0;
}

Output: 9 8 7 6

• Post Decrement - Value of i is decremented after assigning it to variable i.

//Example program for post – decrement operators in c:


#include<stdio.h>
int main()
{
Int num=10;
while(num-- > 5 )
{
printf("%d ",num);
}
return 0;
}

Output: 9 8 7 6 5
6. Ternary (Conditional) Operator:
This is used to test the relationship between two variables.
The conditional operator takes three operands.
The symbol „?‟ is used as a conditional operator in C.
The general form: Where,

Expression - Relational expression


Value1 - value to be assigned when the result of expression is true.
Value2 - value to be assigned when the result of expression is false.
Example: small = a < b? a : b ; if a=5,b=10
small = 5 < 10? 5 : 10;
small = 5

Example: //Program for conditional / ternary operator


#include <stdio.h>
int main() {
int age = 25;
char *status = (age >= 18) ? "Adult" : "Minor";
printf("You are an %s.\n", status);
return 0;
}
Output: You are an Adult.

7. Bitwise Operators:
All data items are stored in the computer‟s memory as asequence of bits (0‟s and 1‟s).
C provides six bitwise operators.
• The result of a bitwise AND is a 1 when both the bits are 1. Otherwise, it is a
zero.
• The result of a bitwise OR is a 0 when both the bits are 0. Otherwise,
• it is 1.
• The result of a bitwise XOR is a 1, if the bits are different (1 and 0).
• Otherwise, it is a 0 (when both are 0‟s and both are 1‟s).
• The bitwise complement operator is an unary operator that reverses the state of
each bit within an integer or a character.
• The left shift operator shifts the bits towards left.
• The right shift operator shifts the bits towards right.
Left Shift (<<) Operators
The left shift(<<) is a binary operator that takes two numbers, left shifts the bits of the first
operand, and the second operand decides the number of places to shift. In other words, left-
shifting an integer “a” with an integer “b” denoted as „(a<<b)’ is equivalent to multiplying
a with 2^b (2 raised to power b).

Synatx: a<<b
Example: Let‟s take a=5; which is 101 in Binary Form. Now, if “a is left-shifted by 2”
i.e a=a<<2 then a will become a=a*(2^2). Thus, a=5*(2^2)=20 which can be written
as 10100.

Right Shift(>>) Operators


Right Shift(>>) is a binary operator that takes two numbers, right shifts the bits of the first
operand, and the second operand decides the number of places to shift. In other words, right-
shifting an integer “a” with an integer “b” denoted as „(a>>b)„ is equivalent to dividing a
with 2^b.

Synatx: a>>b
Example: let‟s take a=5; which is 101 in Binary Form. Now, if “a is right-shifted by 2” i.e
a=a>>2 then a will become a=a/(2^2). Thus, a=a/(2^2)=1 which can be written as 01.
8. Special Operator in C
Below are some of special operators that C language offers.

S No Operators Description

1 & This is used to get the address of the variable.


Example : &a will give address of a
2 * This is used as pointer to a variable.
Example : * a where, * is pointer to the variable a
3 Sizeof() This gives the size of the variable.
Example : size of (char) will give us 1.

4 Comma The Comma operator can be used to link the related


Operator expressions together.
Example : value= (x=10, y=5, x+y)

//Example program for & and * operators in c


In this program, & symbol is used to get the address of the variable and * symbol is used to get
the value of the variable that the pointer is pointing to. Please refer C – pointer topic to know
more about pointers.
#include<stdio.h>
int main()
{
int *ptr, num;
num = 50; /* address of num is assigned to ptr */
ptr = &num; /* display num's value using ptr variable */
printf("%d", *ptr);
return 0;
}
Output: 50

//Example program for sizeof() operator in c


sizeof() operator is used to find the memory space allocated for each C data types.
#include<stdio.h>
int main()
{
int num;
char value;
printf("Storage size for int data type:%d \n",sizeof(num));
printf("Storage size for char data type:%d \n",sizeof(value));
return 0;
}
Output: Storage size for int data type: 4
Storage size for char data type: 1

Working with Expression:


An expression is a combination of operators and operands which reduces to a single value.

Operator Precedence And Associativity In C

:
There are three types of expression.
1) Arithmetic expression
2) Relational expression
3) Logical expression

1. Arithmetic expression
An expression involving arithmetic operators is called arithmetic expression.
Evaluation of expression
At first, the expressions within parenthesis are evaluated. If no parenthesis is present, then the
arithmetic expression is evaluated from left to right.
There are two priority levels of operators in C.
High priority: * / %
Low priority: + -

The evaluation procedure of an arithmetic expression includes two left to right passes through
the entire expression. In the first pass, the high priority operators are applied as they are
encountered and in the second pass, low priority operations are applied as they are encountered.
Suppose, we have an arithmetic expression as:

x = 9 – 12 / 3 + 3 *2 - 1

This expression is evaluated in two left to right passes as:


First Pass: Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1

Second Pass: Step 1: x = 5 + 6 – 1


Step 2: x = 11 – 1

Step 3: x = 10
But when parenthesis is used in the same expression, the order of evaluation gets changed.

2. Relational expression
A relational expression can be defined as a meaningful combination of operands and
relational operators.
3. Logical expression:
Expressions involving the logical operators are called the logical expressions.

Type conversion in Expressions :


Type conversion in C is the process of converting one data type to another. The typeconversion
is only performed to those data types where conversion is possible. Type conversion is
performed by a compiler. In type conversion, the destination data type can‟t be smaller than
the source data type.
1. Implicit Type Conversion :
When the type conversion is performed automatically by the compiler without programmer„s
intervention, such type of conversion is known as implicit type conversion or type promotion

In the C programming language, implicit type conversion refers to the compiler's conversion
of one data type into another data type while the program is being executed. Another name
for it is automated type conversion.

// An example of implicit conversion

#include <stdio.h>
int main()
{
int num1= 10; // integer x
char num2 = 'a'; // character c
// num2 implicitly converted to int. ASCII
// value of 'a' is 97
num1 = num1 + num2;
// num1 is implicitly converted to float
float num3 = num1+ 1.0;
printf("num1 = %d, z = %f", num1, num3);
return 0;
}
Output : num1= 107,
num3 = 108.000000

2. Explicit Type Conversion


This process is also called type casting and it is user-defined. Here the user can typecast the
result to make it of a particular data type.
The type conversion performed by the programmer by posing the data type of the expression
of specific type is known as explicit type conversion. The explicit type conversion is also
known as type casting. Type casting in c is done in the following form:
The syntax in C Programming: (data_type)expression;
// C program to demonstrate explicit type casting
#include<stdio.h>
int main()
{
double num = 1.2;
// Explicit conversion from double to int
int sum = (int)num+ 1;
printf("sum = %d", sum);
return 0;
}
Output : sum = 2

Mathematical Functions :
C provides a large number of library functions which perform specific operations.
Mathematical functions are also included among these library functions.

Mathematical functions are defined in the header file called math.h

• abs(number): returns the absolute value of given number.


Example: abs(-25) , returns 25
• sqrt(number): returns the square root of given number.
Example: sqrt(81) , return
• pow(base,exponent): returns the power of given number.
Example : pow( 2,3) , returns 8
• floor(number): It returns the value rounded down to the lower integer.
Example : floor(12.36) , returns 12
• ceil(number): It returns the value rounded up to the next higher integer.
Example : ceil(12.36) , returns 13
Example: // write a c program to demonstrate mathematical functions
#include <math.h>
#include <stdio.h>
int main()
{
float num1= 3.14;
float num2 = 2.0;
printf("Sin(%f) = %f\n", num1, sin(num1));
printf("Cos(%f) = %f\n", num1, cos(num2));
printf("Pow(%f, %f) = %f\n", num1, num2, pow(num1, num2));
printf("Sqrt(%f) = %f\n", num1, sqrt(num1));
printf("Sin(%f) = %f\n", num1, sin(num1));
printf("Ceiling of %f = %f\n", num2, ceil(num2));
printf("Floor of %f = %f\n", num1, floor(num1));
return 0;
}
Output:
Sin(3.140000) = 0.001593
Cos(3.140000) = -0.999999
Pow(3.140000, 2.000000) = 9.859601
Sqrt(3.140000) = 1.772005
Sin(3.140000) = 0.001593
Ceiling of 2.000000 = 2.000000
Floor of 3.140000 = 3.000000

You might also like