C Notes - Module1
C Notes - Module1
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972 by Dennis
Ritchie. The development of C is given in the figure below:
Major parts of popular operating systems like Windows, UNIX, Linux is still written in C. This is
because even today when it comes to performance (speed of execution) nothing beats C. Moreover,
if one is to extend the operating system to work with new devices one needs to write
device driver programs. These programs are
exclusively written in C. Also, common consumer
devices like microwave oven, washing machines
and digital cameras are getting smarter by the day.
This smartness comes from a microprocessor, an
operating system and a program embedded in this
devices. These programs not only have to run fast
but also
have to work in limited amount of memory. No wonder that such programs are written in C. C is
a compiled language. That means the computer will not interpret the code directly. Instead, you
will need to convert—or compile—the human-readable source code into machine-readable
machine code.
FEATURES OF C
• Simple: C is a simple language in the sense that it provides structured approach (to break
the problem into parts), rich set of library functions, data types etc.
• Machine Independent or Portable: Unlike assembly language, c programs can be
executed in many machines with little bit or no change. But it is not platform-
independent.
• Mid-level prorgramming language: C is also used to do low level programming. It is
used to develop system applications such as kernel, driver etc. It also supports the feature
of high level language. That is why it is known as mid-level language.
• Rich Library: C provides a lot of inbuilt functions that makes the development fast.
• Speed: The compilation and execution time of C language is fast.
• Extensible: C language is extensible because it can easily adopt new features.Structured
prorgramming language
• Structured prorgramming language: C is a structured programming language in the
sense that we can break the program into parts using functions. So, it is easy to
understand and modify.
Structured programming (sometimes known as modular programming) is a subset of procedural
programming that enforces a logical structure on the program being written to make it more
efficient and easier to understand and modify. Certain languages such as Ada, Pascal, and dBASE
are designed with features that encourage or enforce a logical program structure.
One of the biggest advantages of using any structured language is that a programmer can declare
local variables inside a given boundary and these local variables are only available to the code
which is a part of that structure. For example, in C language a programmer can declare a local
variable which can only be used inside the function body where it is declared. In the absence of
functions and local variables programmers will have to create global variables and this will lead
to many bugs in the program because of uncontrolled access to global data.
Although the term block-structured language does not strictly apply to C, C is commonly reffered
to sructured language. It has many similarities to other structured languages, sunch as ALGOL
Pascal, and Module-2. The reason that C (and C++) is not, technically, a block-structured
language is that block-structured languages permit procedures or functions to be declared inside
other procedures or functions. Since C does not allow the creation of functions
within functions, it cannot formally be called block-structured.
STRUCTURE OF C PROGRAM
The computer will start running your program from the main() function. The name is important: if
you don’t have a function called main(), your program won’t be able to start. The main() function
has a return type of int. So what does this mean? Well, when the computer runs your program, it
will need to have some way of deciding if the program ran successfully or not. It does this by
checking the return value of the main() function. If you tell your main() function to return 0, this
means that the program was successful. If you tell it to return any other value, this means that there
was a problem.
The function name comes after the return type. That’s followed by the function parameters if there
are any. Finally, we have the function body. The function body must be surrounded by braces.
DATA TYPE IN C
Data types in C programming language enables the programmers to appropriately select
the data as per requirements of the program and the associated operations of handling
it.
int variable_name;
Float data type declares a variable that can store numbers containing a decimal
number,floating point numbers (single precision).
Syntax
float variable_name;
Double data type also declares variable that can store floating point numbers but gives
precision double than that provided by float data type. Thus, double data type are also
referred to as double precision data type.
Syntax
double variable_name;
Note:- Single precision and Double precision basically differs in the number of digits represented after
the decimal point. Double precision number will represent more digits after the decimal point than a
single precision number. Example: - Single precision – 32.75 and double precision – 32.7543
Character data type declares a variable that can store a character constant. Thus, the
variables declared as char data type can only store one single character.
Syntax
char variable_name;
Syntax
void variable_name;
• Short
• Long
• Signed
• unsigned
It should be noted that the above qualifiers cannot be applied to float and can only be
applied to integer and character data types.
The entire list of data types in c available for use is given below:
Size(in
C Data Types Range
bytes)
Int
2 -32,768 to 32,767
signed int
2 -32,768 to 32,767
unsigned int
Integer Data Types 2 0 to 65535
short int
1 -128 to 127
signed short
1 -128 to 127
int
unsigned short 1 0 to 255
int
4 -2,147,483,648 to
long int 2,147,483,647
4
signed long int Same as Above
4
unsigned long 0 to 4,294,967,295
int
%d 2 bytes 0 to 255
Int
%f 4 bytes
Float -3.4e38 to +3.4e38
%lf 8 bytes
Double -1.7e38 to +1.7e38
%ld 4 bytes
long int -231 to +231
%u 2 bytes 0 to 65535
unsigned int
%Lf 16 bytes
long double -3.4e38 to +3.4e38
%c 1 byte 0 to 255
Unsigned char
C TOKENS
A compiler designer prescribes rules for making a program using statements. The smallest
unit in a program/statement is called a token. The compiler identifies them as token. The
keywords, identifiers, constants, string literals, and operators are examples of tokens. Punctuation
characters such as brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) are also tokens.
Keywords:
Keywords are the reserved words used in programming. Each keywords has fixed meaning
and that cannot be changed by user. For example:
int roll;
As, C programming is case sensitive, all keywords must be written in lowercase. Here is
the list of all keywords predefined by ANSI C.
Keywords in C Language
Do If static while
Besides these keywords, there are some additional keywords supported by Turbo C.
Identifiers
Identifiers, as the name suggests help us to identify data and objects in the program. Identifiers
are basically the name given to program elements such as variables, arrays, and functions.
(1) It cannot include any special characters or punctuation marks (like #, $, ^,?, etc) except
the underscore ‘_”.
(2) There cannot be two successive underscores.
(3) Key words cannot be used as identifiers.
(4) The case of alphabets characters that form the identifier name is significant. For example
“First” is different from ‘first’ and ‘FIRST’.
(5) The identifier name must begin with an alphabet or and underscore. However, use of
underscore as the first character must be avoided because several compiler-defined
identifiers in the standard C library have underscore as their first character.
(6) Identifier can be of any reasonable length. They shoud not contain more than 31
characters.
Roll_no,marks,emp_number,basic_pay etc.
Variable
A variable is defined as a meaningful name given to the data storage location in computer memory.
When using a variable, we actually refer to address of the memory where the is stored. C language
supports two basic kinds of variable-numeric and character.
Each variable to be used in the program must be declared. To declare a variable, specify the data type
of the variable followed by its name.
While declaring a variables, we can also initialize them with some value. For example,
int roll_no=11;
float salary=40000;
char grade=’A’
Constants
There are 4 types of constants in C.
▪ Integer constants
▪ Character constants
▪ Real/Floating point constants
▪ String constants
By definition, a constant is a quantity that does not change throughout the execution of a program.
Integer Constants
An integer constant is an integer quantity which contains a sequence of digits.It should not have a
decimal point. Blanks and commas are not allowed within an integer constant.An integer constant can
be either +ve or -ve. The constant must lie within the range of the declared data type (including
qualifiers long,short etc.).
Integer Type
Prefix Suffix Example
Ox
Hexa Decimal OxA7B
O
Octal O54
Ox I or L
Long Hexa Decimal OxA7BL
O I or L
Long Octal O54L
▪ A decimal constant can contain any combination of integers from 0 through 9. Ex:
189 0 75 87
▪ A hexa decimal constant should begin with 0X or 0x. Ex: 0x65F or 0X7A
▪ An octal constant should begin with digit 0. It can take any digits from 0 through 7.
Note:- There is no binary integer constant in C by default. This means, you cant give a binary number
directly to program by writing sth like:- 0b11001011 – which is meaningless and result in an error. How
ever, programmer can add a preprocessor (which we will learn later) to accept binary numbers in a
program.
Floating Point Constants
They are also known as real constants. A real constant contains a decimal point or an exponent. It
can be either +ve or -ve. Commas and blank space are not allowed within a real constant.
CONSTANT VS LITERAL
A literal is a value that is expressed as itself. For example, the number 25 or the string
“Hello World” is both literals.
A constant is a data type that substitutes a literal. Constants are useful in situations where
• a specific, unchanging value is to be used at various times during the software program
• you want to more easily understand the software code
A variable in a program can change its value during the course of execution of the program.
A constant retains the same value throughout the program.
Constant Literal
Suppose we are writing a program to determine which members of a population are eligible to vote,
permitted to drink, both or neither.
Constant Literal
• Constants free the programmer from having to remember what each literal should be. Often values that
stay constant throughout the program have a business meaning. If there are several such values, the
programmer can define them all in the beginning of the program and then work with the easier-to-
remember constant names.
• If business requirements dictate that the constant be changed (for example, if the drinking age is
lowered to 20 in the future), it is much easier to adapt the program. If we use literals throughout the
program, the change will be hard to do and there is a good chance some instances will not be corrected.
INPUT /OUTPUT IN C
printf() function
int printf(const char *format [,argument, …]);
#include <stdio.h>
int main()
{
char ch = 'A';
char str[20] = "fresh2refresh.com";
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf("Character is %c \n", ch);
printf("String is %s \n" , str);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("Octal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
}
OUTPUT:
Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
Example 2:
#include <stdio.h>
int main()
{
// Tries to print number right justified to 3 digits but the number is not right adjusted because
there are only 4 numbers
printf("4 digit integer right justified to 3 column: %3d\n", integer);
scanf() function
int scanf(const char *format [,address, …]);
On success, scanf() function return the number of input fields successfully scanned, converted, and
stored. Return value =0 if no fields were stored.
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}
OUTPUT :
Enter any character
a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai
OPERATORS IN C
Operators are the symbol which operates on value or a variable. For example: + is a
operator to perform addition.
C programming language has wide range of operators to perform various operations. For
better understanding of operators, these operators can b e classified as:
Arithmetic Operators
* Multiplication
/ Division
a+b=13
a-b=5
a*b=36
a/b=2
Explanation
In C programming,
a/b=2.5
a/d=2.5
c/b=2.5
c/d=2
When i++ is used as prefix (like: ++var ), ++var will increment the value of var and then
return it but, if ++ is used as postfix (like: var++), operator will return the value of operand
first and then only increment it. This can be demonstrated by an example:
#include <stdio.h>
int main(){
int c=2,d=2;
printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.
printf("%d",++c); //this statement increments 1 to c then, only c is displayed.
return 0;
}
Output
Assignment Operators
The most common assignment operator is =. This operator assigns the value in right side to
the left side. For example:
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Relational Operator
Relational operators check relationship between two operands. If the relation is true, it
returns value 1 and if the relation is false, it returns value 0. For example: a>b Here, > is
a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.
Relational operators are used in decision making and loops in C programming.
EXAMPLE:
/*Relational operator */
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10,b=20;
clrscr();
printf("\n %d<%d=%d",a,b,a<b);
printf("\n %d<=%d=%d",a,b,a<=b);
printf("\n %d>%d=%d",a,b,a>b);
printf("\n %d>=%d=%d",a,b,a>=b);
printf("\n %d==%d=%d",a,b,a==b);
printf("\n %d!=%d=%d",a,b,a!=b);
getch();
return 0;
}
OUTPUT:
10<20=1
10<=20=1
10>20=0
10>=20=0
10==20=0
10!=20=1
Logical Operators
Logical operators are used to combine expressions containing relation operators. In C,
there are 3 logical operators:
Meaning of
Operator Operator Example
Logical
! NOT If c=5 then, !(c==5) returns false.
Explanation
For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is
false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true,
either the expression should be true. Since, (c==5) is true. So, the expression is true. Since,
expression (c==5) is true, !(c==5) is false.
Conditional Operator
Conditional operator takes three operands and consists of two symbols ? and : . Conditional
operators are used for decision making in C. For example:
c=(c>0)?10:-10;
If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.
/*Conditional operator*/
#include<stdio.h>
#include<conio.h>
int main()
{
int num1,num2,larger;
//clrscr();
printf("\nEnter two Numbers:");
scanf("%d%d",&num1,&num2);
larger=num1>num2?num1:num2;
printf("Larger of %d and %d is: %d",num1,num2,larger);
getch();
return 0;
}
OUTPUT:
Enter two Numbers:10
13
Larger of 10 and 13 is: 13
Bitwise Operators
Bitwise operators operate on individual bits of integer (int and long) values. This is useful for
writing low-level hardware or OS code where the ordinary abstractions of numbers, characters,
pointers, and so on, are insufficient. Bit manipulation code tends to be less "portable". Code is
"portable" if without any programmer intervention it compiles and runs correctly on different types
of computers. The bit wise operations are commonly used with unsigned types. These operators
perform bit wise logical operations on values. Both operands must be of the same type and width:
the resultant value will also be this type and width. These operators include: bitwise AND, bitwise
OR, bitwise XOR and shift operators.
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Left shift
When we apply a left-shift, every bit is shifted to the left by one place. So the MSB of the number is lost,
the LSB of number is set to 0.Shifting once to the left multiplies the number by 2.
On the contrary, when we apply a shift-right operator, every bit in number is shifted to the right by one
place. So, the LSB of the number is set to 0.
Right Shift
a = 0000 0011 = 3
(a<<=1) = 00000110 = 6
(a<<=2) = 00011000 = 24
(a<<=3) = 11000000 = 192
Left Shift
a=11000000 =192
(a>>=1) = 01100000 = 96
(a>>=2) = 00011000 = 24
(a>>=3) = 0000 0011 = 3
Example:
/*Bitwise operator*/
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10,b=12,c=0;
c=a&b;
printf("\n the value of c after a&b is %d",c);
c=a|b;
printf("\n the value of c after a|b is %d",c);
c=a^b;
printf("\n the value of c after a^b is %d",c);
printf("\n the value of a after a>>1 is %d",a>>1);
printf("\n the value of b after b<<1 is %d",b<<1);
getch();
return 0;
}
OUTPUT:
the value of c after a&b is 8
the value of c after a|b is 14
the value of c after a^b is 6
the value of a after a>>1 is 5
the value of b after b<<1 is 24
sizeof operator in C
Sizeof is a unary operator which can be used to compute the size of its operand. The result of sizeof
is of unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data-
type, including primitive types such as integer and floating-point types, pointer types, or compound
datatypes such as Structure, union etc.
• When sizeof() is used with the data types such as int, float, char… etc it simply return
amount of memory is allocated to that data types.
#include<stdio.h>
int main()
{
printf("%d\n",sizeof(char));
printf("%d\n",sizeof(int));
printf("%d\n",sizeof(float));
printf("%d", sizeof(double));
return 0;
}
Output
1
4
4
8
• Size of constant
#include<stdio.h>
int main() {
printf("%d", sizeof(10));
printf("%d", sizeof('A'));
printf("%d", sizeof(10.10));
return 0;
}
• When sizeof() is used with the expression, it returns size of the expression. Let see
example:
#include<stdio.h>
int main()
{
int a = 0;
double d = 10.21;
printf("%d", sizeof(a+d));
return 0;
}
Output
8
/*sizeof operator*/
#include<stdio.h>
#include<conio.h>
int main()
{
int si=-10;
unsigned int ui=11;
long int li=12345;
long unsigned int lui=123456;
float f=11.34f;
double d=231.123;
long double ld=1234.645;
char ch='a';
clrscr();
printf("\nsi=%d",si);
printf("\nui=%u",ui);
printf("\nli=%ld",li);
printf("\nlui=%lu",lui);
printf("\nf=%f",f);
printf("\nf=%e",f);
printf("\nd=%lf",d);
printf("\nld=%Lf",ld);
printf("\nch=%c",ch);
printf("\n\nsize of integer=%d",sizeof(int));
printf("\nsize of long signed integer=%d",sizeof(long signed int));
printf("\nsize of float=%d",sizeof(float));
printf("\nsize of double=%d",sizeof(double));
printf("\nsize of long double=%d",sizeof(long double));
getch();
return 0;
}
DECISION CONTROL STATEMENTS
1. If statement
The if statement is the simplest form of decision control statements that is
frequently used in decision making. The general from of if statement is :-
if (condition)
..
The if structure may include one statement or n statements enclosed within curly
Brackets. First the test condition is evaluated if the condition is true then the
statement inside the if block is executed otherwise statement outside the if block
is executed. Test condition is any valid C statement that include logical operator.
2.if-else statement
The if-else statement is used to express decisions. Formally the syntax is
if (expression)
statement1
else
statement2
where the else part is optional. The expression is evaluated; if it is true (that is, if expression
has a non-zero value), statement1 is executed. If it is false (expression is zero) and if there is an
else part, statement2 is executed instead.
Since an if tests the numeric value of an expression, certain coding shortcuts are possible. The
most obvious is writing
if (expression)
instead of
if (expression != 0)
Sometimes this is natural and clear; at other times it can be cryptic.
3.Else-If
The syntax is
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
Switch
The switch statement is a multi-way decision that tests whether an expression matches one of
a number of constant integer values, and branches accordingly.
switch (expression) {
case const-expr: statements
case const-expr: statements
default: statements
}
Each case is labeled by one or more integer-valued constants or constant expressions. If a case
matches the expression value, execution starts at that case. All case expressions must be
different. The case labeled default is executed if none of the other cases are satisfied. A
default is optional; if it isn't there and if none of the cases match, no action at all takes place.
Cases and the default clause can occur in any order.
The break statement causes an immediate exit from the switch. Because cases serve just as
labels, after the code for one case is done, execution falls through to the next unless you take
explicit action to escape. break and return are the most common ways to leave a switch.
Iterative statements
C language supports three types of iterative statements
• while loop
• do-while loop
• for loop
While loop
Statement x;
while(expression)
{
Statement block;
}
Statement y;
In the while loop, the condition is tested before the execution of any of the statement block is
executed. If the expression is evaluated to true (non-zero), only then the statements will executed
otherwise if the expression is evaluated to false (zero) the control jump to the statement next to the
while loop. The while loop will executed as long as the evaluated to non-zero (true). A while loop
is also called entry-condition loop as condition is tested at the start of the loop. If the expression
evaluates to false, then the statements enclosed in the loop will never be executed.
do-while loop
statement x;
do
{
Statement block;
} while (expression);
statement y;
In do-while loop the conditional expression is evaluated at the end of the loop. This means the
body of the loop is executed at least once even if the conditional expression is evaluated to false
(zero).
Like the while loop, the do-while loop continues to executed until the conditional expression is
evaluated to true (non-zero)