Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
317 views

Unit 2 Computing Fundamentals and C Programming

C programming is a general-purpose programming language developed in 1972 by Dennis Ritchie. It is one of the most widely used languages. The structure of a C program includes sections like documentation, preprocessor, definitions, main function, and user-defined functions. Some key facts about C are that it was created for the UNIX operating system, and today it remains one of the most popular system programming languages.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
317 views

Unit 2 Computing Fundamentals and C Programming

C programming is a general-purpose programming language developed in 1972 by Dennis Ritchie. It is one of the most widely used languages. The structure of a C program includes sections like documentation, preprocessor, definitions, main function, and user-defined functions. Some key facts about C are that it was created for the UNIX operating system, and today it remains one of the most popular system programming languages.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Unit 2

Overview of C

C programming is a general-purpose, procedural, imperative computer


programming language developed in 1972 by Dennis M. Ritchie at the Bell
Telephone Laboratories to develop the UNIX operating system. C is the most
widely used computer language. It keeps fluctuating at number one scale of
popularity along with Java programming language, which is also equally
popular and most widely used among modern software programmers.
Introduction
C programming language is a MUST for students and working professionals
to become a great Software Engineer specially when they are working in
Software Development Domain. I will list down some of the key advantages of
learning C Programming:
 Easy to learn
 Structured language
 It produces efficient programs
 It can handle low-level activities
 It can be compiled on a variety of computer platforms
Facts about C
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around the early
1970s.
 The language was formalized in 1988 by the American National
Standard Institute (ANSI).
 The UNIX OS was totally written in C.
 Today C is the most widely used and popular System Programming
Language.
 Most of the state-of-the-art software have been implemented using C.
Structure of C program
The structure of a language gives us a basic idea of the order of the sections in a program.
We get to know when and where to use a particular statement, variable, function, curly
braces, parentheses, etc. It also increases our interest in that programming language.

The sections of a C program are listed below:

1. Documentation section
2. Preprocessor section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions

Documentation section
It includes the statement specified at the beginning of a program, such as a
program's name, date, description, and title. It is represented as:

1. //name of a program

Or

1. /*
2. Overview of the code
3. .
4. */

Both methods work as the document section in a program. It provides an overview of


the program. Anything written inside will be considered a part of the documentation
section and will not interfere with the specified code.

Preprocessor section
The preprocessor section contains all the header files used in a program. It informs
the system to link the header files to the system libraries. It is given by:
1. #include<stdio.h>
2. #include<conio.h>

The #include statement includes the specific file as a part of a function at the time of
the compilation. Thus, the contents of the included file are compiled along with the
function being compiled. The #include<stdio.h> consists of the contents of the
standard input output files, which contains the definition of stdin, stdout, and stderr.
Whenever the definitions stdin, stdout, and stderr are used in a function, the
statement #include<stdio.h> need to be used.

There are various header files available for different purposes. For example, # include
<math.h>. It is used for mathematic functions in a program.

Define section
The define section comprises of different constants declared using the define
keyword. It is given by:

1. #define a = 2
Global declaration
The global section comprises of all the global declarations in the program. It is given
by:

1. float num = 2.54;


2. int a = 5;
3. char ch ='z';

The size of the above global variables is listed as follows:

char = 1 byte

float = 4 bytes

int = 4 bytes

We can also declare user defined functions in the global variable section.

Main function
main() is the first function to be executed by the computer. It is necessary for a code
to include the main(). It is like any other function available in the C library.
Parenthesis () are used for passing parameters (if any) to a function.

The main function is declared as:

1. main()
We can also use int or main with the main (). The void main() specifies that the
program will not return any value. The int main() specifies that the program can
return integer type data.

1. int main()

Or

1. void main()

Main function is further categorized into local declarations,


statements, and expressions.

Local declarations
The variable that is declared inside a given function or block refers to as local
declarations.

1. main()
2. {
3. int i = 2;
4. i++;
5. }

Statements

The statements refers to if, else, while, do, for, etc. used in a program within the
main function.

Expressions

An expression is a type of formula where operands are linked with each other by the
use of operators. It is given by:

1. a - b;
2. a +b;

User defined functions


The user defined functions specified the functions specified as per the requirements
of the user. For example, color(), sum(), division(), etc.

The program (basic or advance) follows the same sections as listed above.
Return function is generally the last section of a code. But, it is not necessary to
include. It is used when we want to return a value. The return function returns a value
when the return type other than the void is specified with the function.

Return type ends the execution of the function. It further returns control to the
specified calling function. It is given by:

1. return;

Or

1. return expression ;

For example,

return 0;

Examples
Let's begin with a simple program in C language.

Example 1: To find the sum of two numbers given by the user

It is given by:

1. /* Sum of two numbers */


2. #include<stdio.h>
3. int main()
4. {
5. int a, b, sum;
6. printf("Enter two numbers to be added ");
7. scanf("%d %d", &a, &b);
8. // calculating sum
9. sum = a + b;
10. printf("%d + %d = %d", a, b, sum);
11. return 0; // return the integer value in the sum
12. }

Output
The detailed explanation of each part of a code is as follows:

/* Sum of the two It is the comment section. Any statement described in it is not
numbers */ considered as a code. It is a part of the description section in a
code.
The comment line is optional. It can be in a separate line or part of
an executable line.

#include<stdio.h> It is the standard input-output header file. It is a command of the


preprocessor section.

int main() main() is the first function to be executed in every program. We


have used int with the main() in order to return an integer value.

{… The curly braces mark the beginning and end of a function. It is


} mandatory in all the functions.

printf() The printf() prints text on the screen. It is a function for displaying
constant or variables data. Here, 'Enter two numbers to be added' is
the parameter passed to it.

scanf() It reads data from the standard input stream and writes the result
into the specified arguments.

sum = a + b The addition of the specified two numbers will be passed to the
sum parameter in the output.

return 0 A program can also run without a return 0 function. It simply states
that a program is free from error and can be successfully exited.

Character set of C

character:- It denotes any alphabet, digit or special symbol used to represent information.

Use:- These characters can be combined to form variables. C uses constants, variables, operators, keywords
and expressions as building blocks to form a basic C program.

Character set:- The character set is the fundamental raw material of any language and they are used to
represent information. Like natural languages, computer language will also have well defined character set,
which is useful to build the programs..

The characters in C are grouped into the following two categories:

1. Source character set


a. Alphabets
b. Digits
c. Special Characters
d. White Spaces

2. Execution character set


a. Escape Sequence

Source character set

ALPHABETS
Uppercase letters A-Z
Lowercase letters a-z

DIGITS 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

SPECIAL CHARACTERS

~ tilde % percent sign | vertical bar @ at symbol + plus


sign < less than

_ underscore - minus sign > greater than ^ caret


# number sign = equal to

& ampersand $ dollar sign / slash ( left parenthesis


* asterisk \ back slash

) right parenthesis ′ apostrophe : colon [ left bracket


" quotation mark ; semicolon

] right bracket ! exclamation mark , comma { left flower brace


? Question mark . dot operator

} right flower brace

WHITESPACE CHARACTERS

\b blank space \t horizontal tab \v vertical tab \r carriage


return \f form feed \n new line

\\ Back slash \’ Single quote \" Double quote \? Question


mark \0 Null \a Alarm (bell)

Execution Character Set

Certain ASCII characters are unprintable, which means they are not displayed on the screen or printer. Those
characters perform other functions aside from displaying text. Examples are backspacing, moving to a newline,
or ringing a bell.

They are used in output statements. Escape sequence usually consists of a backslash and a letter or a
combination of digits. An escape sequence is considered as a single character but a valid character constant.

These are employed at the time of execution of the program. Execution characters set are always represented by
a backslash (\) followed by a character. Note that each one of character constants represents one character,
although they consist of two characters. These characters combinations are called as escape sequence.

Backslash character constants

Character ASCII value Escape Sequence Result

Null 000 \0 Null

Alarm (bell) 007 \a Beep Sound

Back space 008 \b Moves previous position

Horizontal tab 009 \t Moves next horizontal tab

New line 010 \n Moves next Line

Vertical tab 011 \v Moves next vertical tab

Form feed 012 \f Moves initial position of next page

Carriage return 013 \r Moves beginning of the line

Double quote 034 \" Present Double quotes

Single quote 039 \' Present Apostrophe


Question mark 063 \? Present Question Mark

Back slash 092 \\ Present back slash

Octal number \000

Hexadecimal number \x

C Tokens
Every smallest individual unit of a c program is called token. Every instruction in a c program is a
collection of tokens. Tokens are used to construct c programs and they are said to the basic
building blocks of a c program.

In a c program tokens may contain the following...

1. Keywords
2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
7. Data values

C Keywords
As every language has words to construct statements, C programming also has words with a

specific meaning which are used to construct c program instructions. In the C programming

language, keywords are special words with predefined meaning. Keywords are also known as

reserved words in C programming language.

In the C programming language, there are 32 keywords. All the 32 keywords have their meaning

which is already known to the compiler.

Properties of Keywords
 All the keywords in C programming language are defined as lowercase letters so they
must be used only in lowercase letters
 Every keyword has a specific meaning, users can not change that meaning.
 Keywords can not be used as user-defined names like variable, functions, arrays,
pointers, etc...
 Every keyword in C programming language represents something or specifies some kind
of action to be performed by the compiler.

The following table specifies all the 32 keywords with their meaning...

Data types Qualifiers User-defined Storage Classes Loop Others

int signed typedef auto for const

char unsigned enum extern while volatile

float short register do sizeof

double long static

Decision Jump Derived function

if goto struct void

else continue union return

switch break

case

default

C Identifiers
In C programming language, programmers can specify their name to a variable, array, pointer,
function, etc... An identifier is a collection of characters which acts as the name of variable,
function, array, pointer, structure, etc... In other words, an identifier can be defined as the user-
defined name to identify an entity uniquely in the c programming language that name may be of
the variable name, function name, array name, pointer name, structure name or a label.

Example
int marks;
char studentName[30];

Here, marks and studentName are identifiers.

Rules for Creating Identifiers

1. An identifier can contain letters (UPPERCASE and


lowercase), numerics & underscore symbol only.
2. An identifier should not start with a numerical value. It can start with a letter or an
underscore.
3. We should not use any special symbols in between the identifier even whitespace.
However, the only underscore symbol is allowed.
4. Keywords should not be used as identifiers.
5. There is no limit for the length of an identifier. However, the compiler considers the first
31 characters only.
6. An identifier must be unique in its scope.

Rules for Creating Identifiers for better


programming
The following are the commonly used rules for creating identifiers for better programming...

1. The identifier must be meaningful to describe the entity.


2. Since starting with an underscore may create conflict with system names, so we avoid
starting an identifier with an underscore.
3. We start every identifier with a lowercase letter. If an identifier contains more than one
word then the first word starts with a lowercase letter and second word onwards first
letter is used as an UPPERCASE letter. We can also use an underscore to separate
multiple words in an identifier.

C Operators
An operator is a symbol used to perform arithmetic and logical operations in a program. That

means an operator is a special symbol that tells the compiler to perform mathematical or logical

operations. C programming language supports a rich set of operators that are classified as

follows.

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Increment & Decrement Operators

5. Assignment Operators

6. Bitwise Operators

7. Conditional Operator

8. Special Operators
Arithmetic Operators (+, -, *, /, %)

The arithmetic operators are the symbols that are used to perform basic mathematical operations

like addition, subtraction, multiplication, division and percentage modulo. The following table

provides information about arithmetic operators.

Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Remainder of the Division 5%2=1

⇒ The addition operator can be used with numerical data types and character data type. When it

is used with numerical values, it performs mathematical addition and when it is used with

character data type values, it performs concatination (appending).

⇒ The remainder of the division operator is used with integer data type only.

Relational Operators (<, >, <=, >=, ==, !=)

The relational operators are the symbols that are used to compare two values. That means the

relational operators are used to check the relationship between two values. Every relational

operator has two results TRUE or FALSE. In simple words, the relational operators are used to

define conditions in a program. The following table provides information about relational

operators.
Operato
r Meaning Example

< Returns TRUE if the first value is smaller than second value 10 < 5 is
otherwise returns FALSE FALSE

> Returns TRUE if the first value is larger than second value otherwise 10 > 5 is
returns FALSE TRUE

<= Returns TRUE if the first value is smaller than or equal to second 10 <= 5 is
value otherwise returns FALSE FALSE

>= Returns TRUE if the first value is larger than or equal to second 10 >= 5 is
value otherwise returns FALSE TRUE

== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5 is


FALSE

!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is
TRUE

Logical Operators (&&, ||, !)

The logical operators are the symbols that are used to combine multiple conditions into one

condition. The following table provides information about logical operators.

Operato
r Meaning Example

&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 > 10 is
otherwise returns FALSE FALSE

|| Logical OR - Returns FALSE if all conditions are FALSE 10 < 5 || 12 > 10 is


otherwise returns TRUE TRUE

! Logical NOT - Returns TRUE if condition is FLASE and !(10 < 5 && 12 > 10) is
returns FALSE if it is TRUE TRUE
⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is

FALSE then complete condition becomes FALSE.

⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE

then complete condition becomes TRUE.

Increment & Decrement Operators (++ & --)

The increment and decrement operators are called unary operators because both need only one

operand. The increment operators adds one to the existing value of the operand and the

decrement operator subtracts one from the existing value of the operand. The following table

provides information about increment and decrement operators.

Operator Meaning Example

++ Increment - Adds one to existing value int a = 5;


a++; ⇒ a = 6

-- Decrement - Subtracts one from existing value int a = 5;


a--; ⇒ a = 4

The increment and decrement operators are used infront of the operand (++a) or after the

operand (a++). If it is used infront of the operand, we call it as pre-increment or pre-

decrement and if it is used after the operand, we call it as post-increment or post-decrement.

Pre-Increment or Pre-Decrement

In the case of pre-increment, the value of the variable is increased by one before the expression

evaluation. In the case of pre-decrement, the value of the variable is decreased by one before

the expression evaluation. That means, when we use pre-increment or pre-decrement, first the

value of the variable is incremented or decremented by one, then the modified value is used in

the expression evaluation.

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

void main(){
int i = 5,j;

j = ++i; // Pre-Increment

printf("i = %d, j = %d",i,j);

Output:

Post-Increment or Post-Decrement

In the case of post-increment, the value of the variable is increased by one after the expression

evaluation. In the case of post-decrement, the value of the variable is decreased by one after the

expression evaluation. That means, when we use post-increment or post-decrement, first the

expression is evaluated with existing value, then the value of the variable is incremented or

decremented by one.

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

void main(){
int i = 5,j;

j = i++; // Post-Increment

printf("i = %d, j = %d",i,j);

Output:
Assignment Operators (=, +=, -=, *=, /=, %=)

The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side

variable (Lvalue). The assignment operator is used in different variants along with arithmetic

operators. The following table describes all the assignment operators in the C programming

language.

Operator Meaning Example

= Assign the right-hand side value to left-hand side variable A = 15

+= Add both left and right-hand side values and store the result into left-hand side A += 10
variable ⇒A=
A+10

-= Subtract right-hand side value from left-hand side variable value and store the A -= B
result ⇒ A = A-B
into left-hand side variable

*= Multiply right-hand side value with left-hand side variable value and store the A *= B
result ⇒ A = A*B
into left-hand side variable

/= Divide left-hand side variable value with right-hand side variable value and store A /= B
the result ⇒ A = A/B
into the left-hand side variable

%= Divide left-hand side variable value with right-hand side variable value and store A %= B
the remainder ⇒A=A
into the left-hand side variable
Operator Meaning Example

%B

Bitwise Operators (&, |, ^, ~, >>, <<)

The bitwise operators are used to perform bit-level operations in the c programming language.

When we use the bitwise operators, the operations are performed based on the binary values.

The following table describes all the bitwise operators in the C programming language.

Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Operator Meaning Example

& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 16 (10000)

| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1 A|B


⇒ 29 (11101)

^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^B
⇒ 13 (01101)

~ the result of Bitwise once complement is negation of the bit ~A


(Flipping) ⇒ 6 (00110)

<< the Bitwise left shift operator shifts all the bits to the left by the A << 2
specified number of positions ⇒ 100
(1100100)

>> the Bitwise right shift operator shifts all the bits to the right by the A >> 2
specified number of positions ⇒ 6 (00110)

Conditional Operator (?:)


The conditional operator is also called a ternary operator because it requires three operands.

This operator is used for decision making. In this operator, first we verify a condition, then we

perform one operation out of the two operations based on the condition result. If the condition is

TRUE the first option is performed, if the condition is FALSE the second option is performed. The

conditional operator is used with the following syntax.

Condition ? TRUE Part : FALSE Part;

Example
A = (10<15)?100:200; ⇒ A value is 100

Special Operators (sizeof, pointer, comma, dot, etc.)

The following are the special operators in c programming language.

sizeof operator

This operator is used to find the size of the memory (in bytes) allocated for a variable. This

operator is used with the following syntax.

sizeof(variableName);

Example
sizeof(A); ⇒ the result is 2 if A is an integer

Pointer operator (*)

This operator is used to define pointer variables in c programming language.

Comma operator (,)

This operator is used to separate variables while they are declaring, separate the expressions in

function calls, etc.

Dot operator (.)

This operator is used to access members of structure or union.


C Constants
In C programming language, a constant is similar to the variable but the constant hold only one

value during the program execution. That means, once a value is assigned to the constant, that

value can't be changed during the program execution. Once the value is assigned to the

constant, it is fixed throughout the program. A constant can be defined as follows...

A constant is a named memory location which holds only one value throughout the

program execution.

In C programming language, a constant can be of any data type like integer, floating-point,

character, string and double, etc.,

Integer constants

An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal

integer value is specified as direct integer value whereas octal integer value is prefixed with 'o'

and hexadecimal value is prefixed with 'OX'.

An integer constant can also be unsigned type of integer constant or long type of integer

constant. Unsigned integer constant value is suffixed with 'u' and long integer constant value is

suffixed with 'l' whereas unsigned long integer constant value is suffixed with 'ul'.

Example

125 -----> Decimal Integer Constant

O76 -----> Octal Integer Constant

OX3A -----> Hexa Decimal Integer Constant

50u -----> Unsigned Integer Constant

30l -----> Long Integer Constant

100ul -----> Unsigned Long Integer Constant

Floating Point constants

A floating-point constant must contain both integer and decimal parts. Some times it may also

contain the exponent part. When a floating-point constant is represented in exponent form, the

value must be suffixed with 'e' or 'E'.


Example

The floating-point value 3.14 is represented as 3E-14 in exponent form.

Character Constants

A character constant is a symbol enclosed in single quotation. A character constant has a

maximum length of one character.

Example

'A'

'2'

'+'

In the C programming language, there are some predefined character constants called escape

sequences. Every escape sequence has its own special functionality and every escape

sequence is prefixed with '\' symbol. These escape sequences are used in output function called

'printf()'.

String Constants

A string constant is a collection of characters, digits, special symbols and escape sequences that

are enclosed in double quotations.

We define string constant in a single line as follows...

"This is btechsmartclass"

We can define string constant using multiple lines as follows...

" This\

is\

btechsmartclass "

We can also define string constant by separating it with white space as follows...

"This" "is" "btechsmartclass"


All the above three defines the same string constant.

Creating constants in C

In a c programming language, constants can be created using two concepts...

1. Using the 'const' keyword

2. Using '#define' preprocessor

Using the 'const' keyword

We create a constant of any datatype using 'const' keyword. To create a constant, we prefix the

variable declaration with 'const' keyword.

The general syntax for creating constant using 'const' keyword is as follows...

const datatype constantName ;

OR

const datatype constantName = value ;

Example

const int x = 10 ;

Here, 'x' is a integer constant with fixed value 10.

Example Program
#include<stdio.h>
#include<conio.h>
void main(){

int i = 9 ;
const int x = 10 ;

i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;
}

The above program gives an error because we are trying to change the constant variable value

(x = 100).

Using '#define' preprocessor / Symbolic Constant

We can also create constants using '#define' preprocessor directive. When we create constant

using this preprocessor directive it must be defined at the beginning of the program (because all

the preprocessor directives must be written before the global declaration).

We use the following syntax to create constant using '#define' preprocessor directive...

#define CONSTANTNAME value

Example

#define PI 3.14

Here, PI is a constant with value 3.14

Example Program
#include<stdio.h>
#include<conio.h>
#defien PI 3.14
void main(){
int r, area ;
printf("Please enter the radius of circle : ") ;
scanf("%d", &r) ;
area = PI * (r * r) ;
printf("Area of the circle = %d", area) ;
}

C Variables
Variables in a c programming language are the named memory locations where the user can

store different values of the same datatype during the program execution. That means a variable

is a name given to a memory location in which we can store different values of the same data

type. In other words, a variable can be defined as a storage container to hold values of the same

datatype during the program execution. The formal definition of a data type is as follows...
Variable is a name given to a memory location where we can store different values of the

same datatype during the program execution.

Every variable in c programming language must be declared in the declaration section before it is

used. Every variable must have a datatype that determines the range and type of values be

stored and the size of the memory to be allocated.

A variable name may contain letters, digits and underscore symbol.

The following are the rules to specify a variable name...

1. Variable name should not start with a digit.

2. Keywords should not be used as variable names.

3. A variable name should not contain any special symbols except underscore(_).

4. A variable name can be of any length but compiler considers only the first 31 characters

of the variable name.

Declaration of Variable

Declaration of a variable tells the compiler to allocate the required amount of memory with the

specified variable name and allows only specified datatype values into that memory location. In C

programming language, the declaration can be performed either before the function as global

variables or inside any block or function. But it must be at the beginning of block or function.

Declaration Syntax:

datatype variableName_1, .. ,variableName_n;

Example
int number;

The above declaration tells to the compiler that allocates 2 bytes of memory with the

name number and allows only integer values into that memory location.

Definition of Variable or Assigning value to a Variable

Variables can be initialized (assigned an initial value) in their declaration. The

initializer consists of an equal sign followed by a constant expression as follows.


Syntax

type variable_name = value;

eg:

int d = 3, f = 5; // definition and initializing d and f.


byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

C Expression Evaluation

In the C programming language, an expression is evaluated based on the operator precedence

and associativity. When there are multiple operators in an expression, they are evaluated

according to their precedence and associativity. The operator with higher precedence is

evaluated first and the operator with the least precedence is evaluated last.

To understand expression evaluation in c, let us consider the following simple example

expression...

10 + 4 * 3 / 2

In the above expression, there are three operators +, * and /. Among these three operators,

both multiplication and division have the same higher precedence and addition has lower

precedence. So, according to the operator precedence both multiplication and division are

evaluated first and then the addition is evaluated. As multiplication and division have the

same precedence they are evaluated based on the associativity. Here, the associativity of

multiplication and division is left to right. So, multiplication is performed first, then division

and finally addition. So, the above expression is evaluated in the order of * / and +. It is

evaluated as follows...

4 * 3 ====> 12
12 / 2 ===> 6

10 + 6 ===> 16

The expression is evaluated to 16.

Operator Precedence and Associativity in C


Operator precedence determines which operator is performed first in an expression
with more than one operators with different precedence.
For example: Solve
10 + 20 * 30

10 + 20 * 30 is calculated as 10 + (20 * 30)


and not as (10 + 20) * 30

Operators Associativity is used when two operators of same precedence appear in an


expression. Associativity can be either Left toRight or Right to Left.
For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right,
so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
Operators Precedence and Associativity are two characteristics of operators that
determine the evaluation order of sub-expressions in absence of brackets
For example: Solve
100 + 200 / 10 - 3 * 10

1) Associativity is only used when there are two or more operators of same
precedence.
The point to note is associativity doesn’t define the order in which operands of a
single operator are evaluated. For example, consider the following program,
associativity of the + operator is left to right, but it doesn’t mean f1() is always called
before f2(). The output of the following program is in-fact compiler dependent.
// Associativity is not used in the below
program.
// Output is compiler dependent.

#include <stdio.h>

int x = 0;
int f1()
{
x = 5;
return x;
}
int f2()
{
x = 10;
return x;
}
int main()
{
int p = f1() + f2();
printf("%d ", x);
return 0;
}

2) All operators with the same precedence have same associativity


This is necessary, otherwise, there won’t be any way for the compiler to decide
evaluation order of expressions which have two operators of same precedence and
different associativity. For example + and – have the same associativity.
3) Precedence and associativity of postfix ++ and prefix ++ are different
Precedence of postfix ++ is more than prefix ++, their associativity is also different.
Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left.
See this for examples.
4) Comma has the least precedence among all operators and should be used
carefully For example consider the following program, the output is 1.

#include <stdio.h>
int main()
{
int a;
a = 1, 2, 3; // Evaluated as (a = 1),
2, 3
printf("%d", a);
return 0;
}

5) There is no chaining of comparison operators in C


In Python, expression like “c > b > a” is treated as “c > b and b > a”, but this type of
chaining doesn’t happen in C. For example consider the following program. The
output of following program is “FALSE”.
#include <stdio.h>
int main()
{
int a = 10, b = 20, c = 30;

// (c > b > a) is treated as ((c > b) > a), associativity


of '>'
// is left to right. Therefore the value becomes ((30 >
20) > 10)
// which becomes (1 > 20)
if (c > b > a)
printf("TRUE");
else
printf("FALSE");
return 0;
}

Please see the following precedence and associativity table for reference.

Operator Description
Associativity
() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ — Postfix increment/decrement (see Note 2)
Prefix increment/decrement right-to-left
++ —
+– Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
&
Address (of operand)
sizeof
Determine size in bytes on this implementation
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right
It is good to know precedence and associativity rules, but the best thing is to use
brackets, especially for less commonly used operators (operators other than +, -, *..
etc). Brackets increase the readability of the code as the reader doesn’t have to see the
table to find out the order.

C Math
C Programming allows us to perform mathematical operations through the functions defined
in <math.h> header file. The <math.h> header file contains various methods for performing
mathematical operations such as sqrt(), pow(), ceil(), floor() etc.

C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h
header file are given below.
No. Function Description

rounds up the given number. It returns the integer value which is


1) ceil(number)
greater than or equal to given number.

rounds down the given number. It returns the integer value which
2) floor(number)
is less than or equal to given number.

3) sqrt(number) returns the square root of given number.

pow(base,
4) returns the power of given number.
exponent)

5) abs(number) returns the absolute value of given number.


C Math Example

Let's see a simple example of math functions found in math.h header file.

1. #include<stdio.h>
2. #include <math.h>
3. int main(){
4. printf("\n%f",ceil(3.6));
5. printf("\n%f",ceil(3.3));
6. printf("\n%f",floor(3.6));
7. printf("\n%f",floor(3.2));
8. printf("\n%f",sqrt(16));
9. printf("\n%f",sqrt(7));
10. printf("\n%f",pow(2,4));
11. printf("\n%f",pow(3,3));
12. printf("\n%d",abs(-12));
13. return 0;
14. }
Output:

4.000000

4.000000

3.000000

3.000000

4.000000

2.645751

16.000000

27.000000

12

Also

acos(x)

asin(x)

cos(x) and many more in the math.h.


Reading and Writing a Character

A getchar() reads a single character from standard input, while a getc() reads a single

character from any input stream.

Syntax

var_name = getchar();

Putchar() writes a single character.

putchar(varname);

#include <stdio.h>

1.#include <conio.h>
2.#include <ctype.h>
3.int main()
4.{
5. char ch;
6. printf (" Enter a character ( If we want to exit press #) \n");
7. while (ch != '#') /* accept the number till the user does not enter the # to exit from the loo
p. */
8. {
9. ch = getchar();
10. printf (" \n We have entered the character : ");
11. putchar (ch); // print a single character
12. printf ("\n");
13. }
14. return 0;
15.}

C - Formatted I/O Functions

C language provide us console input/output functions. As the name says, the console input/output
functions allow us to -

 Read the input from the keyboard by the user accessing the console.
 Display the output to the user at the console.

Note : These input and output values could be of any primitive data type.
Formatted input/output functions

Formatted console input/output functions are used to take one or more inputs from the user at
console and it also allows us to display one or multiple values in the output to the user at the
console.

Some of the most important formatted console input/output functions are -


Functions Description

scanf() This function is used to read one or multiple inputs from the
user at the console.

printf() This function is used to display one or multiple values in the


output to the user at the console.
Format specifiers in console formatted I/O functions

Some of the most commonly used format specifiers used in console formatted input/output
functions are displayed in the table below -
Format Specifiers Description

%hi Format specifier used to read or display a signed shortinteger value


or short integer value.

%hu Format specifier used to read or display an unsigned shortinteger


value.

%d
Format specifier used to read or display a signed int integer value.

%u Format specifier used to read or display a unsigned intinteger


value.

%ld Format specifier used to read or display a long integer value


or signed long integer value.

%lu Format specifier used to read or display a unsigned longinteger


value.

%c Format specifier used to read or display a char, character value.


Format specifier %hhi is used to display a signed numerical value.

Format specifier used to read or display a unsigned char, character


%c
value. Format specifier %hhu is used to display a signed numerical
value.

%f Format specifier used to read or display a float, floating-point


value.

%lf Format specifier used to read or display a double, floating-point


value.

%Lf Format specifier used to read or display a long double, floating-


point value.

%s Format specifier used to read or display a string value, to be stored


in a char[] array.

You might also like