Module 1 Notes Final
Module 1 Notes Final
INTRODUCTION TO C PROGRAMMING
History of C Language
ALGOL' was the foundation or progenitor of programming languages. It was first introduced
in 1960. 'ALGOL' was widely used in European countries. The ALGOL had introduced the
concept of structured programming to the developer community. The year 1967 marked the
introduction of a novel computer programming language known as 'BCPL', an acronym for
Basic Combined Programming Language. BCPL was designed by Martin Richards in the
mid-1960s.
Dennis K&R C
Dennis Ritchie along with Brian Kernighan published the first edition of their book "The C
Programming Language". Popularly known as K&R (the initials of its authors), the book
served for many years as an informal specification of the language.
ANSI C
In the 1980s, the American National Standards Institute (ANSI) began working on a formal
standard for the C language. This led to the development of ANSI C, which was standardized
in 1989.
Ritchie created C at Bell Laboratories in the early 1970s. It developed from an older language
named B that Ken Thompson created. The main purpose of C's creation was to construct the
Unix operating system, which was crucial in the advancement of contemporary computers.
In 1971, Dennis Ritchie started working on C, and he and other Bell Labs developers kept
improving it. The language is appropriate for both system programming and application
development.
C99
In 1999, the ISO/IEC approved an updated version of the C standard known as C99. The C
standard was further revised in the late 1990s.
C11
C11, published in 2011, is another major revision of the C standard. The C11 standard adds
new features to C and the library and introduced features such as multi-threading support,
anonymous structures and unions, and improved Unicode support.
C17
The C17 standard has been published in June 2018. C17 is the current standard for the C
programming language. No new features have been introduced with this standard revision.
C18
The most recent version of the C standard, C18, was published in 2018. It includes minor
revisions and bug fixes compared to C11.
C23
C23 is the informal name for the next major C language standard revision, expected to be
published in 2024. 14 new keywords are expected to be introduced in this revision.
Features of C Language
C is the widely used Procedure Oriented Programming (POP) language. It
provides many features that are given below.
1. Simple
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
[Link]
1) Simple
C is a simple language in the sense that it provides a structured approach (to break
the problem into parts), the rich set of library functions, data types, etc.
5) Rich Library
6) Memory Management
7) Speed
The compilation and execution time of C language is fast since there are lesser
overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by
using the pointers. We can use pointers for memory, structures, functions, array,
etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for
every function. Recursion enables us to use the approach of backtracking.
10) Extensible
The documentation section is the part of the program where the programmer gives the
details associated with the program. He usually gives the name of the program, the details of
the author and other details like the time of coding and description. It gives anyone reading
the code the overview of the code.
Link Section
The link section consists of the header files of the functions that are used in
the program. It provides instructions to the compiler to link functions from
the system library.
Definition Section
All the symbolic constants are written in definition section. Macros are known
as symbolic constants.
The global variables that can be used anywhere in the program are declared
in global declaration section. This section also declares the user defined
functions.
Subprogram Section
The subprogram section contains all the user defined functions that are used
to perform a specific task. These user defined functions are called in the
main() function.
Example: -
ELEMENTS OF C LANGUAGE AND
PROGRAM CONSTRUCTS
C Character set
As every language contains a set of characters used to construct words, statements, etc., C language also
has a set of characters which include alphabets, digits, special symbols and white spaces.
Alphabets
C language supports all the alphabets from the English language. Lower and upper case letters together
support 52 alphabets.
lower case letters - a to z
UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports a rich set of special symbols that include symbols to perform mathematical operations,
to check conditions, , backspaces, and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | etc.,
White spaces
It includes blank space, tab space, backspace, new line, etc.
C Tokens
Tokens are the smallest individual elements of a program, which are
meaningful to the compiler. C programs are written using these tokens and the
syntax of the language.
The following are the types of C tokens: Keywords, Identifiers, Constant, Strings,
Operators, and Special Symbols.
[Link]:
[Link]
They are used for naming of variables, functions, array etc. These are user-defined
names which consist of alphabets, number, underscore ‘_’. Identifier’s name should
not be same or same as keywords. Keywords are not used as identifiers.
Rules for naming C identifiers −
It must begin with alphabets or underscore.
Only alphabets, numbers, underscore can be used, no other special
characters, punctuations are allowed.
It must not contain white-space.
It should not be a keyword.
It should be up to 31 characters long.
[Link] (Literals)
Constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are enumeration constants
as [Link] are treated just like regular variables except that their values
cannot be modified after their definition.
Integer Literals(Constants)
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix
specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for
decimal.
An integer literal can also have a suffix that is a combination of U and L, for
unsigned and long, respectively. The suffix can be uppercase or lowercase and can
be in any order, i.e., both lu and ul are the same.
It is defined by representing the digits between 0 to 9. For example, 45, 67, etc.
Example
#include <stdio.h>
int main()
{
const int a=23; // constant integer literal
printf("Integer literal : %d", a);
return 0;
}
Output
Integer literal : 23
Floating-point(Real) Constants
A floating-point literal has an integer part, a decimal point, a fractional part, and an
exponent part. You can represent floating point literals either in decimal form or
exponential form.
While representing decimal form, you must include the decimal point, the exponent,
or both; and while representing exponential form, you must include the integer part,
the fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals −
3.14159 /* Legal */
314159E-5L /* Legal */
1.2, +9.0, -4.5
Example of float literal in decimal form.
#include <stdio.h>
int main()
{
const float a=4.5; // constant float literal
const float b=5.6; // constant float literal
float sum;
sum=a+b;
printf("%f", sum);
return 0;
}
Output
10.100000
Character Constants
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').
String Constants
String literals or constants are enclosed in double quotes "". A string contains
characters that are similar to character literals: plain characters, escape sequences,
and universal characters. String literals are stored in C as an array of chars,
terminated by a null character, ‘\0’.
Example:- “A”,”Hai”,”123”
Defining Constants
There are two simple ways in C to define constants −
Using #define preprocessor.(Symbolic Constants)
Example : - #define PI 3.141592
Using const keyword.
Example :- const int a=23;
Symbolic Constants in C
A symbolic constant is a name given to some numeric constant, or a character
constant or string constant, or any other constants.
Examples
#define PI 3.141592
#define SIZE 50
#define TRUE 1
#define FALSE 0
They can be used to assign names to values. For example we can define
the value of ‘pi’ as #define PI 3.141592 and use the name PI in place 3.141592.
This will increase understandability.
ii)Modifiability
4. Strings
Strings in C are always represented as an array of characters having null
character '\0' at the end of the string. This null character denotes the end of
the string. Strings in C are enclosed within double quotes, while characters
are enclosed within single characters. The size of a string is a number of
characters that the string contains.
char a[11] = "CPROGRAMING"; // The compiler allocates the 11 bytes to the
'a' array.
char a[] = "CPROGRAMING"; // The compiler allocates the memory at the
run time.
char a[11] = {'C','P','R','O','G','R','A','M','I','N',’G’,'\0'}; // String is represented in
the form of characters.
5. Special Symbols
Some special characters are used in C, and they have a special meaning
which cannot be used for another purpose.
Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
Simple brackets ( ): It is used in function declaration and function calling. Printf ()
is a pre-defined function.
Curly braces { }: It is used in the opening and closing of the code. It is used in
the opening and closing of the loops.
Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when
printing the value of more than one variable using a single printf statement.
Hash/pre-processor (#): It is used for pre-processor directive. It basically
denotes that we are using the header file.
Asterisk (*): This symbol is used to represent pointers and also used as an
operator for multiplication.
Tilde (~): It is used as a destructor to free memory.
Period (.): It is used to access a member of a structure or a union.
6. Operators
Operators in C is a special symbol used to perform the functions. The data items on
which the operators are applied are known as operands. Operators are applied
between the operands. Depending on the number of operands, operators are
classified as follows:
Unary Operator: A unary operator is an operator applied to the single operand. For
example: increment operator (++), decrement operator (--), size of, (type)*.
Binary Operator: The binary operator is an operator applied between two operands.
The following is the list of the binary operators: Arithmetic, Relational, Shift, Logical,
Bitwise, Conditional, and Assignment Operators.
Character Meaning
‘\a’ alert
‘\b’ backspace
‘\n’ newline
‘\\’ backslash
‘\0’ null
Variables in C
A variable is a data name that may be used to store a data value. The
primary purpose of variables is to store data in memory for later use. Unlike
constants which do not change during the program execution, variables value
may change during execution. If you declare a variable in C, that means you are
asking the operating system to reserve a piece of memory with that variable
name.
dataType variableName;
This declares a variable, declares its data type, and reserves memory for it. It
says nothing about what value is put in memory.
This declares a variable, declares its data type, reserves memory for it, and
puts an initial value into that memory. The initial value must be of the correct
data type.
This declares two variables, both of the same data type, reserves memory,
and puts an initial value in each variable. Again, you can do this for more than
two variables as long as you follow the pattern.
Examples
int i, j, k;
char c, ch;
float f, salary;
double d;
C - Data Types
Data type determines the type of data a variable will hold. If a variable x is declared
as int, it means x can hold only integer values. Every variable which is used in the
program must be declared as what data-type it is. In C language, data types can be
classified into three :-
1. float
2. double
1. FLOAT:
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 1.7E–308 to 1.7E+308.
The C programming language provides a keyword called typedef, which you can
use to give a type a new name. You can use typedef to give a name to your user
defined data types as well. In short, we can say that this keyword is used to redefine
the name of an already existing variable. This keyword is useful when we are dealing
with the lengthy data types.
Syntax of typedef
-
In the above syntax, 'existing_name' is1.1
the name of an already existing variable
3.4 name given to the existing variable.
while 'alias name' is another
Example
In the above statements, we have declared the unit variable of type unsigned int by
using a typedef keyword.
Now, we can create the variables of type unsigned int by writing the following
statement:
unit a, b;
instead of writing:
unsigned int a, b;
ii) Enumeration
Enumeration is another user defined datatype in C language. It is used to assign
names to the integral constants which makes a program easy to read and maintain.
The keyword “enum” is used to declare an enumeration.
Syntax of enum
For example:
Variables of type enum can also be defined. They can be defined in two
ways:
// In both of the below cases, "day" is defined as the variable of
type week.
a) Using two statements
enum week{Mon, Tue, Wed};
enum week day;
b) Using a single statement.
enum week{Mon, Tue, Wed}day;
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Output:
2
Functions
A function is called a C language construct which consists of a function-body associated
with a function-name. In every program in C language, execution begins from the main
function, which gets terminated after completing some operations which may include
invoking other functions.
Function Declaration
Arrays
Array in C is a fixed-size collection of similar data items stored in contiguous memory
locations. An array is capable of storing the collection of data of primitive, derived, and
user-defined data types.
Array Declaration
Pointer
A pointer in C language is a data type that stores the address where data is stored. Pointers
store memory addresses of variables, functions, and even other pointers.
Pointer Declaration
data_type * ptr_name;
where,
data_type: type of data that a pointer is pointing to.
ptr_name: name of the pointer.
*: dereferencing operator.
Structure
In C, a structure is a user-defined data type that can be used to group items of possibly
different types into a single type.
The struct keyword is used to define a structure. The items in the structure are called its
members and they can be of any valid data type.
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
Union
Unions are similar to structures in many ways. What makes a union different is that all the
members in the union are stored in the same memory location resulting in only one member
containing data at the same time. The size of the union is the size of its largest member.
Union is declared using the "union" keyword.
Syntax
union union_name {
datatype member1;
datatype member2;
...
};
Comments in C
A comment is an explanation or description of the source code of the program. It
helps a developer explain logic of the code and improves program readability. At run-time, a
comment is ignored by the compiler , so they won’t be executed.
/*This is a
Multiline comment*/
SAMPLE PROGRAMS
#include <stdio.h>
int main()
/* printf function displays the content that is passed between the double quotes. */
printf("WELCOME TO C PROGRAMMING");
return 0;
Output:
WELCOME TO C PROGRAMMING
Example 2: Program to Print an Integer entered by the user.
#include <stdio.h>
int main()
int num;
scanf("%d", &num);
return 0;
Output:
#include <stdio.h>
void main()
int num;
scanf("%d", &num);
if (num > 0)
else
Output 1:
Enter a number:
Output 2:
Enter a number:
-3
-3 is a negative number
C OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators. C operators can be classified as follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Increment and decrement Operators
7. Conditional Operators
8. Special Operators.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C
language. Assume variable A holds 10 and variable B holds 20 then −
Relational Operators
Relational operators are used to compare or relate two quantities. An expression
containing a relational operator is termed as a relational expression. The value of a
relational expression is either one or zero. The following table shows all the relational
operators supported by C. Assume variable A holds 10 and variable B holds 20 then −
== Checks if the values of two operands are equal or not. If yes, then (A == B) is not true.
the condition becomes true.
!= Checks if the values of two operands are not equal or not. If the (A != B) is true.
values are not equal, then the condition becomes true.
> Checks if the value of left operand is greater than the value of right (A > B) is not true.
operand. If yes, then the condition becomes true.
< Checks if the value of left operand is less than the value of right (A < B) is true.
operand. If yes, then the condition becomes true.
>= Checks if the value of left operand is greater than or equal to the (A >= B) is not true.
value of right operand. If yes, then the condition becomes true.
<= Checks if the value of left operand is less than or equal to the value (A <= B) is true.
of right operand. If yes, then the condition becomes true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
! Called Logical NOT Operator. It is used to reverse the !(A && B) is true.
logical state of its operand. If a condition is true, then
Logical NOT operator will make it false.
Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =.It evaluates expression on right side of = symbol and assigns
evaluated value to left side of the variable.
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
Operator Example Same as
/= a /= b a = a/b
%= a %= b a = a%b
Bitwise Operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Syntax: ++x
a = ++x;
Here, if the value of ‘x’ is 10 then value of ‘a’ will be 11 because the value of ‘x’ gets
modified before using it in the expression.
Syntax: x++
b = x++;
Here, suppose the value of ‘x’ is 10 then value of variable ‘b’ will be 10 because old value of
‘x’ is assigned to ‘b’ and after that it will be incremented.
In the same way we can use decrement operator also.
Conditional Operator in C
The conditional operator is also known as a ternary operator. The conditional statements
are the decision-making statements which depends upon the output of the expression. It is
represented by two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
The behaviour of the conditional operator is similar to the 'if-else' statement as 'if-else'
statement is also a decision-making statement.
Syntax
1. Expression1? expression2: expression3;
Special Operators
Below are some of the special operators that the C programming language offers.
sizeof operator
sizeof (data_type/variable)
Example:
X=sizeof(int);
Y=sizeof(n);
The reference operator noted by ampersand ("&"), is also a unary operator in c languages
that uses for assign address of the variables. It returns the pointer address of the variable.
Syntax
data_type x;
data_type *pt;
pt = &x
The dereference operator or indirection operator, noted by asterisk ("*"), is also a unary
operator in c languages that uses for pointer variables. It operates on a pointer variable,
and returns value equivalent to the value at the pointer address. This is called
data_type *pt;
C Expressions
An expression is a formula in which operands are linked to each other by the use of
operators to compute a value. An operand can be a function reference, a variable, an array element
or a constant.
1. Arithmetic Expressions
2. Relational expressions
3. Logical expressions
4. Conditional expressions
Arithmetic Expressions
An arithmetic expression is an expression that consists of operands (variables or constants)
and arithmetic operators. An arithmetic expression computes a value of type int, float or double.
When an expression contains only integral operands, then it is known as pure integer
expression when it contains only real operands, it is known as pure real expression, and when it
contains both integral and real operands, it is known as mixed mode expression.
For example:
9/2 + a-b;
X*Y-Z
Variable = expression
Example
x= a*b-c
When the statement is encountered, the expression is evaluated first and the result then replaces
the previous value of the variable on the LHS. All variables used in the expression must be assigned
values before evaluation is attempted. Also, all variables used in the program must be defined
before they are used in the expressions.
1. Implicit Conversion
2. Explicit Conversion (also known as Type Casting)
1. If one of the operands is long double, the other is promoted to long double before the
operation is carried out.
2. Else, If one of the operands is double, the other is promoted to double before the operation
is carried out.
3. Otherwise, if one of the operands is float, the other is promoted to float before the
operation is carried out.
4. Otherwise, if one of the operands is unsigned long int, the other is promoted to unsigned
long int before the operation is carried out.
5. Otherwise if either operand is long int, the other operand is unsigned int , then
a. If unsigned int can be converted to long int, the unsigned int operand will be
promoted to long int.
b. Else, both operands will be converted to unsigned long int.
6. Otherwise if either operand is long int, the other operand will be promoted to long int.
7. Else, if one of the operands is unsigned int, the other will be converted to unsigned int.
8. Otherwise, If one operand is of type int then the other operand will be converted to int and
the result of the operation will be an int.
#include<stdio.h>
int main()
x = x + y;
return 0;
Output:
x = 107, z = 108.000000
The final result of an expression is converted to the type of the variable on the LHS of the equal to sign before
assigning the value to [Link] following changes are introduced during the final assignment.
Converting float to an int will truncate the fraction part hence losing the meaning of the value.
Converting double to float will round up the digits.
Converting long int to int will cause dropping of excess high order bits.
(data_type)expression;
where, data_type is any valid c data type, and expression may be constant, variable or expression.
Example
float z;
If we want to get the exact value of 7/5 then we need explicit casting from int to float:
int x=7, y=5;
float z;
Here x is explicitly converted into float and by the rule of automatic type conversion, the division is
performed in floating point mode, thus retaining the fractional part of the result.
Note: - The type of x remains as int in the other parts of the program.
Each operator in C has a precedence associated with it. There are distinct levels of precedence and
an operator may belong to one of these levels. The operators at the higher level are evaluated first.
10 + 20 * 30
and not as (10 + 20) * 30 because the operator * has higher precedence than +.
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”.
Mathematical Functions
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.
There are various methods in math.h header file. The commonly used functions of math.h header
file are given below.
SAMPLE PROGRAMS
[Link] a program to check whether a year is leap year or not.
A year is a leap year if −
It is evenly divisible by 100
o If it is divisible by 100, then it should also be divisible by 400
Except this, all other years evenly divisible by 4 are leap years.
#include <stdio.h>
int main() {
int year;
year = 2016;
if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))
printf("%d is a leap year", year);
else
printf("%d is not a leap year", year);
return 0;
}
Output
2016 is a leap year
#include<stdio.h>
int main()
{
printf("Size of char: %d bytes\n",sizeof(char));
printf("Size of int: %d bytes\n",sizeof(int));
printf("Size of float: %d bytes\n",sizeof(float));
printf("Size of double: %d bytes", sizeof(double));
return 0;
}
Output:
putchar()
This is a single character output function. putchar() writes a single character to
the standard output device, which is normally the console(screen). In case you
want to display more than one characters, use putchar() method in a loop.
#include <stdio.h>
void main( )
{
char c;
printf("Enter a character");
c = getchar();
gets()
It reads a string from the keyboard.
The syntax for gets() function is as follows −
gets(variablename);
Example
#include<stdio.h>
#include<string.h>
main(){
char str[10];
printf("Enter your name: \n");
gets(str);
printf("Hello %s welcome to Tutorialspoint", str);
}
Output
Enter your name:
Madhu
Hello Madhu welcome to Tutorialspoint
puts()
It displays a string on the monitor.
The syntax for puts() function is as follows −
puts(variablename/string);
For example,
puts("tutorial");
Example
#include<stdio.h>
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
getch()
getch() is character input functions. It reads a character from the keyboard but
does not echo the pressed character and returns character pressed. It is
defined in header file conio.h.
Syntax
character_variable = getch();
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf(“Press any character: ”);
ch = getch();
printf(“\nPressed character is: %c”, ch);
}
Output
------------------------------------
Note: while using getch() pressed
character is not echoed. Here pressed
character is e and it is displayed
by printf().
getche()
Syntax
character_variable = getche();
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
printf(“Press any character: ”);
ch = getche();
printf(“\nPressed character is: %c”, ch);
}
Output of the above program :
Press any character: e
Pressed character is: e
-----------------------------------
Note: while using getch() pressed
character is not echoed but while
using getche() it is echoed. Here pressed
character is e and it is displayed
by printf().
Format
Data Type
Specifier
int %d
char %c
float %f
double %lf
unsigned int %u
signed char %c
unsigned char %c
Format
Data Type
Specifier
long double
%Lf
printf()
The printf function is used to output data onto the standard output device. In
general, the printf function is written as,
printf(<control string>, arg1, arg2, . . . , argn);
where the <control string> refers to a string containing required formatting
information as in scanf, and arg1, arg2, ..., argn are individual data variables
whose values are to be printed. However, unlike scanf, these data variable
names are not preceded by the & symbol. This is because printf is expected to
only output the values of these variables and not their addresses.
Example:
printf("%d %f",x,y);
NOTE : printf() function returns the number of characters printed by it, and
scanf() returns the number of characters read by it.
Example:
int i = printf("studytonight");
In this program printf("studytonight"); will return 12 as result, which will be
stored in the variable i, because studytonight has 12 characters.