You are on page 1of 24

The C Character Set

A character denotes any alphabet, digit or special symbol used to represent information.
Alphabets A, B, ....., Y, Z and a, b, ......, y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols ~ ‘ ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; " ' < > , . ? /

C Tokens
A token is the smallest element of a program that is meaningful to the compiler.
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
Keywords​:
● Keywords are pre-defined or reserved words in a programming language which
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.
● C​ language supports ​32​ keywords which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

Example​: int money;


int ​is a​ ​keyword​ ​and​ money ​is a​ ​variable
Variables:

● In programming, a variable is a container (storage area) to hold data.


● To indicate the storage area, each variable should be given a unique
name (​identifier​). Variable names are just the symbolic representation of
a memory location.

For example: ​int playerScore = 95;


playerScore​ is a ​variable​ of int type. Here, the variable is assigned an integer value 95.

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.

There are certain rules that should be followed while naming c 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.
● main: ​method name
● a: ​variable name
Constants
A constant is an entity that doesn’t change.

Types of C Constants
C constants can be divided into two major categories:
(a)Primary Constants​: Integer, Real and Character constants.
(b)Secondary Constants​: Array, Pointer, Structure, Union, Enum etc.

Rules for Constructing Integer Constants


(a) An integer constant must have at least one digit.
(b) It must not have a decimal point.
(c) It can be either positive or negative.
(d) If no sign precedes an integer constant it is assumed to be positive.
(e) No commas or blanks are allowed within an integer constant.
(f) The allowable range for integer constants is -32768 to 32767.

Example: ​426
+782
-8000
-7605
Real Constants
Real constants are often called Floating Point constants.
The real constants could be written in two forms—​Fractional form ​and
Exponential form​.

Following rules must be observed while constructing real constants expressed in


fractional form:
(a) A real constant must have at least one digit.
(b) It must have a decimal point.
(c) It could be either positive or negative.
(d) Default sign is positive.
(e) No commas or blanks are allowed within a real constant.
Example:​ +325.34
426.0
-32.76
-48.5792

Character Constants

● A character constant is a single alphabet, a single digit or a single special symbol


enclosed within single quotes.
● The maximum length of a character constant is 1 character.
● Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple
variable of char type.
● A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or
a universal character (e.g., '\u02C0').
● There are certain characters in C that represent special meaning when preceded by a
backslash for example, newline (\n) or tab (\t).

Comments in C
Comments in C language are used to provide information about lines of code. It is
widely used for documenting code. There are 2 types of comments in the C language.

1. Single Line Comments

2. Multi-Line Comments

1) Single Line Comments

Single line comments are represented by double slash \\. Let's see an example of a
single line comment in C.
#include<stdio.h>
int​ main(){
​//printing information
printf(​"Hello C"​);
return​ 0;
}
Output:

Hello C

Even you can place the comment after the statement. For example:

printf(​"Hello C"​);​//printing information

2) Multi Line Comments


Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines
of code, but it can't be nested. Syntax:

/*
code
to be commented
*/
Let's see an example of a multi-Line comment in C.

#include<stdio.h>
int​ main(){
​/*printing information
Multi-Line Comment*/
printf(​"Hello C"​);
return​ 0;
}
Output:

Hello C
Input and Output in C

printf() function
The ​printf() function​ is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

printf(​"format string"​,argument_list);

The ​format string​ can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function
The ​scanf() function​ is used for input. It reads the input data from the console.

scanf(​"format string"​,argument_list);

Program to print cube of given number


#include<stdio.h>

int​ main(){

int​ number;

printf(​"enter a number:"​);

scanf(​"%d"​,&number);

printf(​"cube of number is:%d "​,number*number*number);

return​ 0;

Output

enter a number:5

cube of number is:125

● The ​scanf("%d",&number)​ statement reads integer number from the console and stores
the given value in number variable.
● The ​printf("cube of number is:%d ",number*number*number)​ statement prints the
cube of number on the console
Program to print sum of 2 numbers
#include<stdio.h>
int​ main(){
int​ x=0,y=0,result=0;

printf(​"enter first number:"​);


scanf(​"%d"​,&x);
printf(​"enter second number:"​);
scanf(​"%d"​,&y);

result=x+y;
printf(​"sum of 2 numbers:%d "​,result);

return​ 0;
}

Output

enter first number:9

enter second number:9


sum of 2 numbers:18

C – Data Types

● C data types are defined as the data storage format that a variable can store a
data to perform a specific operation.
● Data types are used to define a variable before to use in a program.
● Size of variable, constant and array are determined by data types. 
● There are four data types in C language. They are,

Types Data Types

Basic data types/Primary int, char, float, double

Enumeration data type enum

Derived data type pointer, array, structure, union

Void data type void


 

1.​ BASIC DATA TYPES IN C LANGUAGE:

1.1. INTEGER DATA TYPE:

● Integer data type allows a variable to store numeric values.


● “int” keyword is used to refer integer data type.
● The storage size of int data type is 2 or 4 or 8 byte.
● It varies depend upon the processor in the CPU that we use. If we are using
16 bit processor, 2 byte (16 bit) of memory will be allocated for int data type.
● Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of
memory for 64 bit processor is allocated for int datatype.
● int (2 byte) can store values from -32,768 to +32,767
● int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
● If you want to use the integer value that crosses the above limit, you can go
for “long int” and “long long int” for which the limits are very high.

Note:

● We can’t store decimal values using int data type.


● If we use int data type to store decimal values, decimal values will be
truncated and we will get only whole number.
● In this case, float data type can be used to store decimal values in a variable.

1.2. ​CHARACTER DATA TYPE:

● Character data type allows a variable to store only one character.


● Storage size of character data type is 1. We can store only one character
using character data type.
● “char” keyword is used to refer character data type.
● For example, ‘A’ can be stored using char datatype. You can’t store more
than one character using char data type.
● Please refer ​C – Strings​ topic to know how to store more than one characters
in a variable.

1.3. ​FLOATING POINT DATA TYPE:


Floating point data type consists of 2 types. They are,

1. float
2. double

1. FLOAT:

● Float data type allows a variable to store decimal values.


● Storage size of float data type is 4. This also varies depend upon the
processor in the CPU as “int” data type.
● We can use up-to 6 digits after decimal using float data type.
● For example, 10.456789 can be stored in a variable using float data type.

2. DOUBLE:

● Double data type is also same as float data type which allows up-to 10 digits
after decimal.
● The range for double datatype is from 1E–37 to 1E+37.

SIZEOF() FUNCTION IN C LANGUAGE: 

sizeof() function is used to find the memory space allocated for each C data types. 

#include <stdio.h>
#include <limits.h>
int main()
{
int a;
char b;
float c;
double d;
printf("Storage size for int data type:%d \n",sizeof(a));
printf("Storage size for char data type:%d \n",sizeof(b));
printf("Storage size for float data type:%d \n",sizeof(c));
printf("Storage size for double data type:%d\n",sizeof(d));
return 0;
}

OUTPUT: 

Storage size for int data type:4


Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8

MODIFIERS IN C LANGUAGE:

● The amount of memory space to be allocated for a variable is derived by


modifiers.
● Modifiers are prefixed with basic data types to modify (either increase or
decrease) the amount of storage space allocated to a variable.
● For example, storage space for int data type is 4 byte for 32 bit processor.
We can increase the range by using long int which is 8 byte. We can
decrease the range by using short int which is 2 byte.
● There are 5 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
5. long long

Below table gives the detail about the storage size of each C basic data type in 16 bit
processor. Please keep in mind that storage size and range for int and float datatype
will vary depend on the CPU processor (8,16, 32 and 64 bit)

C Data types / storage Size  Range 

char / 1  –127 to 127 

int / 2  –32,767 to 32,767 

float / 4  1E–37 to 1E+37 with six digits of precision 

double / 8  1E–37 to 1E+37 with ten digits of precision 


long double / 10  1E–37 to 1E+37 with ten digits of precision 

long int / 4  –2,147,483,647 to 2,147,483,647 

short int / 2  –32,767 to 32,767 

unsigned short int / 2  0 to 65,535 

signed short int / 2  –32,767 to 32,767 

long long int / 8  –(2power(63) –1) to 2(power)63 –1 

signed long int / 4  –2,147,483,647 to 2,147,483,647 

unsigned long int / 4  0 to 4,294,967,295 

unsigned long long int / 8  2(power)64 –1 

2. ENUMERATION DATA TYPE IN C LANGUAGE:

● Enumeration data type consists of named integer constants as a list.


● It start with 0 (zero) by default and value is incremented by 1 for the
sequential identifiers in the list.
● Enum syntax in C:
enum identifier [optional{ enumerator-list }];
● Enum example in C:

enum month { Jan, Feb, Mar }; or

/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */

enum month { Jan = 1, Feb, Mar };

/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */

enum month { Jan = 20, Feb, Mar };

/* Jan is assigned to 20. Feb and Mar variables will be assigned to 21 and 22
respectively by default */

● The above enum functionality can also be implemented by “#define”


preprocessor directive as given below. Above enum example is same as
given below.
#define Jan 20;

#define Feb 21;

#define Mar 22;

C – ENUM EXAMPLE PROGRAM:


#include <stdio.h>
int main()
{
enum MONTH { Jan = 0, Feb, Mar };
enum MONTH month = Mar;
if(month == 0)
printf("Value of Jan");
else if(month == 1)
printf("Month is Feb");
if(month == 2)
printf("Month is Mar");
}

OUTPUT: ​Month is March

3. DERIVED DATA TYPE IN C LANGUAGE:

The data-types that are derived from the primitive or built-in datatypes are referred to as
Derived Data Types.
Array, pointer, structure and union are called derived data type in C language.

4. VOID DATA TYPE IN C LANGUAGE:

● Void is an empty data type that has no value.


● This can be used in functions and pointers.
● Please visit “​C – Function​” topic to know how to use void data type in function
with simple call by value and call by reference example programs.

C – Operators and Expressions

● The symbols which are used to perform logical and mathematical operations in a C
program are called C operators.
● These C operators join individual constants and variables to form expressions.
● Operators, functions, constants and variables are combined together to form
expressions.
● Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is
constant and A + B * 5 is an expression.

TYPES OF C OPERATORS:

C language offers many types of operators. They are,

1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators

ARITHMETIC OPERATORS IN C: 


C  Arithmetic  operators  are  used  to  perform  mathematical  calculations  like  addition, 
subtraction, multiplication, division and modulus in C programs. 

Arithmetic 
Example 
Operators/Operation 

+ (Addition)  A+B 

– (Subtraction)  A-B 

* (multiplication)  A*B 

/ (Division)  A/B 

% (Modulus)  A%B 
ASSIGNMENT OPERATORS IN C:

In C programs, values for the variables are assigned using assignment operators.

● For example, if the value “10” is to be assigned for the variable “sum”, it can be
assigned as “sum = 10;”
● There are 2 categories of assignment operators in C language. They are,
1. Simple assignment operator ( Example: = )
2. Compound assignment operators ( Example: +=, -=, *=, /=, %=, &=, ^= )

Operators  Example/Description 

sum = 10; 

10 is assigned to variable sum 

sum += 10; 
+= 
This is same as sum = sum + 10 

sum -= 10; 
-= 
This is same as sum = sum – 10 

sum *= 10; 
*= 
This is same as sum = sum * 10 

sum /= 10; 
/= 
This is same as sum = sum / 10 

sum %= 10; 
%= 
This is same as sum = sum % 10 

sum&=10; 
&= 
This is same as sum = sum & 10 

sum ^= 10; 
^= 
This is same as sum = sum ^ 10 

 
RELATIONAL OPERATORS IN C: 

Relational  operators  are  used  to  find  the  relation  between  two  variables.  i.e.  to  compare  the 
values of two variables in a C program.

Operators  Example/Description 

>  x > y (x is greater than y) 

<  x < y (x is less than y) 

>=  x >= y (x is greater than or equal to y) 

<=  x <= y (x is less than or equal to y) 

==  x == y (x is equal to y) 

!=  x != y (x is not equal to y) 

LOGICAL OPERATORS IN C:
These operators are used to perform logical operations on the given expressions.
● There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and logical
NOT (!).

Operators Example/Description

(x>5)&&(y<5)
&& (logical AND)
It returns true when both conditions are true

(x>=10)||(y>=10)
|| (logical OR)
It returns true when at-least one of the condition is true

!((x>5)&&(y<5))
It reverses the state of the operand “((x>5) && (y<5))”
! (logical NOT)
If “((x>5) && (y<5))” is true, logical NOT operator makes it false

BIT WISE OPERATORS IN C:


These operators are used to perform bit operations. Decimal values are converted into binary
values which are the sequence of bits and bit wise operators work on these bits.

● Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT), ^ (XOR),
<< (left shift) and >> (right shift).
TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:

BELOW ARE THE BIT-WISE OPERATORS AND THEIR NAME IN C LANGUAGE.

1. & – Bitwise AND


2. | – Bitwise OR
3. ~ – Bitwise NOT
4. ^ – XOR
5. << – Left Shift
6. >> – Right Shift

NOTE:

● Bit wise left shift and right shift :​ In left shift operation “x << 1 “, 1 means that the bits
will be left shifted by one place. If we use it as “x << 2 “, then, it means that the bits will
be left shifted by 2 places.

Increment/decrement Operators

● Increment operators are used to increase the value of the variable by one and
decrement operators are used to decrease the value of the variable by one in C
programs.
● Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
● Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;

 
DIFFERENCE  BETWEEN  PRE/POST  INCREMENT  &  DECREMENT 
OPERATORS IN C: 

Below  table  will  explain  the  difference  between  pre/post  increment  and  decrement  operators 
in C programming language. 

Operator  O
​ perator/Description 

Pre increment operator  value of i is incremented before assigning it to the 


(++i)  variable i 

Post increment operator  value of i is incremented after assigning it to the 


(i++)  variable i 

Pre decrement operator  value of i is decremented before assigning it to the 


(-–i)  variable i 

Post decrement operator 


value of i is decremented after assigning it to variable i 
(i–-) 

CONDITIONAL OPERATORS IN C:

● Conditional operators return one value if condition is true and returns another value is
condition is false.
● This operator is also called as ternary operator.

Syntax ​ ​ : ​ (Condition? true_value: false_value);


Example : ​ (A > 100 ? “A is larger value” : “A is smaller value”);

● In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if
else conditional statements.

SPECIAL OPERATORS IN C:
Below are some of the special operators that the C programming language offers.

Operators Description

This is used to get the address of the variable.


&
Example : &a will give address of a.

This is used as pointer to a variable.


*
Example : * a where, * is pointer to the variable a.
This gives the size of the variable.
sizeof()
Example : size of (char) will give us 1.

Operator Precedence and Associativity in C

Precedence of operators

The precedence of operators determines which operator is executed first if


there is more than one ​operator​ in an expression.

Let us consider an example:

int​ x = ​5​ - ​17​* ​6​;

In C, the precedence of ​*​ is higher than ​-​ and ​=​. Hence, ​17 * 6​ is evaluated
first. Then the expression involving ​-​ is evaluated as the precedence of ​-​ is
higher than that of =​ ​.
Operators Associativity​ ​is used when two operators of same precedence appear
in an expression. Associativity can be either ​L​eft​ t​o ​R​ight or​ R​ight​ t​o ​L​eft.
For example:​ ‘*’ and ‘/’ have same precedence and their associativity is ​L​eft​ t​o ​R​ight,
so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

Operators Precedence & Associativity Table

Operator Meaning of operator Associativity

() Functional call Left to right


[] Array element reference
-> Indirect member selection
. Direct member selection
! Logical negation Right to left
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
-- Decrement
& Dereference (Address)
* Pointer reference
sizeof Returns the size of an object
(type) Typecast (conversion)

* Multiply Left to right


/ Divide
% Remainder

+ Binary plus(Addition) Left to right


- Binary minus(subtraction)

<< Left shift Left to right


>> Right shift

< Less than Left to right


<= Less than or equal
> Greater than
>= Greater than or equal

== Equal to Left to right


!= Not equal to

& Bitwise AND Left to right

^ Bitwise exclusive OR Left to right

| Bitwise OR Left to right

&& Logical AND Left to right

|| Logical OR Left to right

?: Conditional Operator Right to left


= Simple assignment Right to left
*= Assign product
/= Assign quotient
%= Assign remainder
+= Assign sum
-= Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift

, Separator of expressions Left to right

Type Conversion in C
A type cast is basically a conversion from one type to another. There are two types of type
conversion:

1. Implicit Type Conversion


Also known as ‘automatic type conversion’.

● Done by the compiler on its own, without any external trigger from the user.
● Generally takes place when in an expression more than one data type is present.
In such condition type conversion (type promotion) takes place to avoid loss of
data.
● All the data types of the variables are upgraded to the data type of the variable
with largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
● It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long long is
implicitly converted to float).
​2. ​Explicit Type Conversion​–
This process is also called type casting and it is user defined. Here the user
can type cast the result to make it of a particular data type.
The syntax in C:
(type) expression

Advantages of Type Conversion


○ This is done to take advantage of certain features of type hierarchies or type
representations.
○ It helps us to compute expressions containing variables of different data
types.
Storage Classes in C
Storage Classes are used to describe the features of a variable/function. These features
basically include the scope, visibility and life-time which help us to trace the existence of
a particular variable during the runtime of a program.
C language uses 4 storage classes​,

1)auto​:
● This is the default storage class for all the variables declared inside a function
or a block.
● Hence, the keyword auto is rarely used while writing programs in C
language.
● Auto variables can be only accessed within the block/function they have been
declared and not outside them (which defines their scope).
● Of course, these can be accessed within nested blocks within the parent
block/function in which the auto variable was declared.
● They are assigned a garbage value by default whenever they are declared.
2) ​extern​:
● Extern storage class simply tells us that the variable is defined elsewhere and
not within the same block where it is used.
● Basically, the value is assigned to it in a different block and this can be
overwritten/changed in a different block as well.
● So an extern variable is nothing but a global variable initialized with a legal
value where it is declared in order to be used elsewhere. It can be accessed
within any function/block.
● Also, a normal global variable can be made extern as well by placing the
‘extern’ keyword before its declaration/definition in any function/block.
● The main purpose of using extern variables is that they can be accessed
between two different files which are part of a large program.
3) ​static​:
● This storage class is used to declare static variables which are popularly used
while writing programs in C language.
● Static variables have a property of preserving their value even after they are
out of their scope! Hence, static variables preserve the value of their last use
in their scope.
● So we can say that they are initialized only once and exist till the termination
of the program.
● Their scope is local to the function to which they were defined.
● Global static variables can be accessed anywhere in the program. By default,
they are assigned the value 0 by the compiler.
4) ​register​:
● This storage class declares register variables which have the same
functionality as that of the auto variables.
● The only difference is that the compiler tries to store these variables in the
register of the microprocessor if a free register is available.
● This makes the use of register variables to be much faster than that of the
variables stored in the memory during the runtime of the program.
● Usually few variables which are to be accessed very frequently in a
program are declared with the register keyword which improves the
running time of the program.
Syntax:
storage_class var_data_type var_name;

Errors in C
Error is an illegal operation performed by the user which results in abnormal working of
the program.
Programming errors often remain undetected until the program is compiled or executed.
Some of the errors inhibit the program from getting compiled or executed. Thus errors
should be removed before compiling and executing.
1) Syntax errors:​ Errors that occur when you ​violate the rules​ of writing C/C++
syntax are known as syntax errors. This compiler error indicates something that
must be fixed before the code can be compiled. All these errors are detected by
the compiler and thus are known as compile-time errors.
Most frequent syntax errors are:
● Missing Parenthesis (​}​)
● Printing the value of variable without declaring it
● Missing semicolon
2) Logical Errors : ​On compilation and execution of a program, desired output is
not obtained when certain input values are given. These types of errors which
provide incorrect output but appear to be error free are called logical errors.
These are one of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are
easy to detect if we follow the line of execution and determine why the program
takes that path of execution.

You might also like