Getting Started With C
Getting Started With C
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
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.
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.
Character Constants
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.
2. Multi-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:
/*
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.
printf("format string",argument_list);
scanf() function
The scanf() function is used for input. It reads the input data from the console.
scanf("format string",argument_list);
int main(){
int number;
printf("enter a number:");
scanf("%d",&number);
return 0;
Output
enter a number:5
● 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;
result=x+y;
printf("sum of 2 numbers:%d ",result);
return 0;
}
Output
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,
Note:
1. float
2. double
1. FLOAT:
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 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:
MODIFIERS IN C LANGUAGE:
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)
/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */
/* Jan is assigned to 20. Feb and Mar variables will be assigned to 21 and 22
respectively by default */
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.
● 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:
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
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
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 language are & (bitwise AND), | (bitwise OR), ~ (bitwise NOT), ^ (XOR),
<< (left shift) and >> (right shift).
TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:
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
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.
● 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
Precedence of operators
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 Left to Right 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”.
Type Conversion in C
A type cast is basically a conversion from one type to another. There are two types of 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
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.