Introduction to C Program
Introduction to C Program
History of C
Introduction
C is one of the oldest and most influential programming languages, playing a foundational
role in modern software development. Its origin in the early 1970s by Dennis Ritchie at Bell
Labs marked a turning point, as C became the backbone for operating systems like Unix.
Knowing the history of C language is key to appreciating its simplicity, efficiency, and
portability, which continue to shape today's programming world.
C Programming Founder
The founder of C programming language is Dennis Ritchie, who developed it in 1972 at Bell
Labs.
Origin of C Language
The C language has its roots in two earlier languages: BCPL (Basic Combined Programming
Language) and B.
BCPL, developed by Martin Richards in the 1960s, was designed for writing
compilers.
In the late 1960s, Bell Labs was developing an operating system called Unix. Initially, Unix
was written in assembly language, which was machine-dependent and difficult to maintain.
To solve this, Ken Thompson created the B language, a simplified version of BCPL, for Unix
development. However, B lacked essential features for systems programming, like data types.
In 1972, Dennis Ritchie took B and enhanced it, introducing data types and structures,
creating C. The goal was to create a language that offered the efficiency of assembly with the
flexibility of a higher-level language, making Unix portable and easier to maintain.
Key Features of C
Structure of C Program
}
Function2()
{
A 'C' program begins executing at main(). The first part in Fig. consists of comment lines,
enclosed in /* ... */.
Library files are used to give instructions to compiler for linking purpose. All constants and
global variable declaration is done here.
The second part of Fig. Consists of main() function. Every C program must consists of
main() function. Local variable declarations and statements (For example: call other functions
or any computational coded) are defined in main().
The third part of consists of all user-defined functions. These functions are called in main()
function.
Introduction to C Programming
A simple C program:
/* Hello Program*/
#include<stdio.h>
int main(void)
1. #include<stdio.h>
This first line of the program is a pre-processing directive, #include. The #include directive
tells the pre-processor to insert the contents of another file into the source code at the point
where the #include directive is found. The header file stdio.h contains declarations for
standard input and output functions such as printf.
2. int main(void)
This line indicates that a function named main is being defined. The main function serves a
special purpose in C programs. The run-time environment calls the main function to begin
program execution. The type specifier int indicates that the return value, the value of
evaluating the main function that is returned to its invoker (in this case the run-time
environment), is an integer. The keyword void as a parameter list indicates that the main
function takes no arguments.
3. {
This opening curly brace indicates the beginning of the definition of the main function.
4. printf("Hello World");
This line calls (executes the code for) a function named printf, which is declared in the
included header stdio.h and supplied from a system library. In this call, the printf function is
passed (provided with) a single argument, the address of the first character in the string literal
"hello world\n". The semicolon (;) terminates the statement.
5. return 0;
This line terminates the execution of the main function and causes it to return the integer
value 0, which is interpreted by the run-time system as an exit code, (indicating successful
execution).
6.}
This closing curly brace indicates the end of the code for the main function.
Introduction to C Programming
C LANGUAGE FUNDAMENTALS
Character Set
Character set are the set of alphabets, letters and some special characters that are valid in C
language.
A character refers to the digit, alphabet or special symbol used to data representation.
The C character set consists of all uppercase characters A to Z, the lowercase characters a to
z, the digits 0 to 9, certain special characters and white spaces.
* + [ ] / \
! “ < > ( )
= | { } # %
, ; : ? & -
_ $ ~ ` ^
Tokens
C tokens are the basic buildings blocks in C language which are constructed together to write
a C program.
C Tokens
1. Identifiers
2. Keywords
3. Constants
4. String Literals
5. Operators
6. Other Symbols
Introduction to C Programming
Tokens in C
1. Identifiers are user defined words like sum, roll_no, sub_marks and used for variable and
function names.
5. Other symbols are symbols which have particular meaning like; (semicolon indicates end
of an instruction.
6. String literals is a sequence of zero or more characters enclosed in double quo like "Nirali
Prakashan".
Keywords in C
Keywords are predefined or reserved words that have special meanings to the compiler.
These are part of the syntax and cannot be used as identifiers in the program. Lists of
keywords in C or reserved words in the C programming language are mentioned below:
doubl
else enum extern float for goto if
e
We cannot use these keywords as identifiers (such as variable names, function names, or
struct names). The compiler will throw an error if we try to do so.
C Identifiers
Introduction to C Programming
In C programming, identifiers are the names used to identify variables, functions, arrays,
structures, or any other user-defined items. It is a name that uniquely identifies a program
element and can be used to refer to it later in the program.
Example:
// Creating a variable
int val = 10;
// Creating a function
void func() {}
In the above code snippet, "val" and "func" are identifiers.
C Variables
A variable in C is a named piece of memory which is used to store data and access it
whenever required. It allows us to use the memory without having to memorize the exact
memory address.
To create a variable in C, we have to specify a name and the type of data it is going to store
in the syntax.
data_type name;
C provides different data types that can store almost all kinds of data. For example, int, char,
float, double, etc.
int num;
char letter;
float decimal;
In C, every variable must be declared before it is used. We can also declare multiple variables
of same data type in a single statement by separating them using comma as shown:
data_type name1, name2, name3, ...;
C Variable Initialization
Once the variable is declared, we can store useful values in it. The first value we store is
called initial value and the process is called Initialization. It is done using assignment
operator (=).
int num;
num = 3;
It is important to initialize a variable because a C variable only contains garbage value when
it is declared. We can also initialize a variable along with declaration.
int num = 3;
Note: It is compulsory that the values assigned to the variables should be of the same data
type as specified in the declaration.
Accessing Variables
The data stored inside a C variable can be easily accessed by using the variable's name.
Example:
#include <stdio.h>
int main() {
Output
3
Introduction to C Programming
Types of Variables
There are two types of variables ie., local and global variables.
1. Local Variables:
Variables that are declared inside a function are called Local Variables. Local variables can
be used only by the statement which is inside the block and in which variables are
declared.Local variables cannot be used outside the block, Lifetime of the local variable is till
the end of the block ie. a local variable is created when block enters and destroyed when
block exit.
We can declare same variable name within two different blocks. However, we cannot have
same variable name within one block.
Formal Parameters:
If a function use arguments, it must declare variables so that the variables will accept the
values of the arguments. These variables are referred as formal parameters of the function.
Constants in C
#include <stdio.h>
Introduction to C Programming
int main() {
Output
10
Syntax
We define a constant in C using the const keyword. Also known as a const type qualifier, the
const keyword is placed at the start of the variable declaration to declare that variable as a
constant.
const data_type var_name = value;
1. Integer constants
Definition: Integer constants represent whole numbers without a decimal point or fractional
part. They can be positive or negative.
o Decimal (base 10): Regular integers written with digits 0-9. Example: 123 , -45 .
o Octal (base 8): Numbers prefixed with 0 and using digits 0-7. Example: 075 .
o Hexadecimal (base 16): Numbers prefixed with 0x or 0X and using digits 0-9 and letters A-
F (or a-f) to represent 10-15. Example: 0x1A3 .
3. Character constants
Introduction to C Programming
Definition: Represent a single character enclosed within single quotes ( ' ' ).
Examples: 'A' , '5' , '+' .
Storage: Character constants are stored as integer values based on their ASCII representation.
4. String Constants
The string constants are a collection of various special symbols, digits, characters, and
escape sequences that get enclosed in double quotations.
The definition of a string constant occurs in a single line:
“This is Cookie”
Backspace \b
New line \n
Form feed \f
Horizontal tab \t
Carriage return \r
Single quote \’
Double quote \”
Vertical tab \v
Backslash \\
Question mark \?
Alert or bell \a
DATA TYPE
Data types in C classify variables based on the kind of value they can store and the operations
that can be performed on them.
Each variable in C has an associated data type. It specifies the type of data that the variable
can store like integer, character, floating, double, etc
C is a statically type language where each variable's type must be specified at the
declaration and once specified, it cannot be changed.
Example:
We use int keyword to declare the integer variable:
int val;
We can store the integer values (literals) in this variable.
#include <stdio.h>
int main() {
int var = 22;
Output
var = 22
A variable of given data type can only contains the values of the same type. So, var can
only store numbers, not text or anything else.
The integer data type can also be used as:
1. unsigned int: It can store the data values from zero to positive numbers, but it can’t
store negative values
2. short int: It is lesser in size than the int by 2 bytes so can only store values from -
32,768 to 32,767.
3. long int: Larger version of the int datatype so can store values greater than int.
4. unsigned short int: Similar in relationship with short int as unsigned int with int.
Note: The size of an integer data type is compiler dependent. We can use sizeof operator to
check the actual size of any data type. In this article, we are discussing the sizes according
to 64-bit compilers.
Character Data Type
Character data type allows its variable to store only a single character. The size of the
character is 1 byte. It is the most basic data type in C. It stores a single character and
requires a single byte of memory in almost all compilers.
Range: (-128 to 127) or (0 to 255)
Size: 1 byte
Format Specifier: %c
Example:
#include <stdio.h>
int main() {
Introduction to C Programming
char ch = 'A';
Output
ch = A
Float Data Type
In C programming, float data type is used to store single precision floating-point values.
These values are decimal and exponential numbers.
Range: 1.2E-38 to 3.4E+38
Size: 4 bytes
Format Specifier: %f
Example:
#include <stdio.h>
int main() {
float val = 12.45;
Output
val = 12.450000
Double Data Type
The double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It can easily accommodate about 16 to 17 digits after or
before a decimal point.
Range: 1.7E-308 to 1.7E+308
Size: 8 bytes
Format Specifier: %lf
Example:
#include <stdio.h>
int main() {
Introduction to C Programming
Output
val = 1.452100
Void Data Type
The void data type in C is used to indicate the absence of a value. Variables of void data
type are not allowed. It can only be used for pointers and function return type and
parameters.
Example:
void fun(int a, int b){
// function body
}
where function fun is a void type of function means it doesn't return any value.
1.FUNCTION
A function is a named and finite set of C program statements.
They assigned to do some specific task.
Function is associates with three tasks-
Function Prototype
Function Definition Writing
Function Calling
2.ARRAY
3.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.
Introduction to C Programming
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.
1. Structure
As we know, C doesn't have built-in object-oriented features like C++ but structures can be
used to achieve encapsulation to some level. Structures are used to group items of different
types into a single type. The "struct" keyword is used to define a structure. The size of the
structure is equal to or greater than the total size of all of its members.
Syntax
struct structure_name {
data_type member_name1;
data_type member_name1;
....
....
};
2. 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;
...
};
3. Enumeration (enums)
Introduction to C Programming
Enum is short for "Enumeration". It allows the user to create custom data types with a set of
named integer constants. The "enum" keyword is used to declare an enumeration. Enum
simplifies and makes the program more readable.
Syntax
Syntax
Operators in C
Operators are the basic components of C programming. They are symbols that represent
some kind of operation, such as mathematical, relational, bitwise, conditional, or logical
computations, which are to be performed on values or variables. The values and variables
used with operators are called operands.
Example:
#include <stdio.h>
int main() {
printf("%d", sum);
return 0;
}
Output
30
In the above expression, '+' is the addition operator that tells the compiler to add both of
the operands 10 and 20.
Types of Operators in C
C language provides a wide range of built in operators that can be classified into 6 types
based on their functionality:
Table of Content
Arithmetic Operators
Relational Operators
Logical Operator
Bitwise Operators
Assignment Operators
Other Operators
Arithmetic Operators
The arithmetic operators are used to perform arithmetic/mathematical operations on
operands. There are 9 arithmetic operators in C language:
Operator Description
Symbol Syntax
Adds two
+ Plus numeric values. a+b
Subtracts right
- Minus operand from left a-b
operand.
Multiply two
* Multiply numeric values. a*b
Divide two
/ Divide numeric values. a/b
Operator Description
Symbol Syntax
Used to specify
+ Unary Plus the positive +a
values.
Increases the
++ Increment value of the a++
operand by 1.
Decreases the
-- Decrement value of the a--
operand by 1.
#include <stdio.h>
int main() {
int a = 25, b = 5;
return 0;
}
Output
a + b = 30
a - b = 20
a * b = 125
a/b=5
a%b=0
+a = 25
-a = -25
a++ = 25
a-- = 26
Relational Operators
The relational operators in C are used for the comparison of the two operands. All these
operators are binary operators that return true or false values as the result of comparison.
These are a total of 6 relational operators in C:
Operator Description
Symbol Syntax
Operator Description
Symbol Syntax
operand. Else
false
Returns true if
== Equal to both the operands a == b
are equal.
Returns true if
!= Not equal to both the operands a != b
are NOT equal.
#include <stdio.h>
int main() {
int a = 25, b = 5;
return 0;
}
Introduction to C Programming
Output
a<b :0
a>b :1
a <= b: 0
a >= b: 1
a == b: 0
a != b : 1
Here, 0 means false and 1 means true.
Logical Operator
Logical Operators are used to combine two or more conditions/constraints or to
complement the evaluation of the original condition in consideration. The result of the
operation of a logical operator is a Boolean value either true or false.
There are 3 logical operators in C:
Operator Description
Symbol Syntax
Returns true if
&& Logical AND both the operands a && b
are true.
Returns true if
|| Logical OR both or any of the a || b
operand is true.
int main() {
int a = 25, b = 5;
return 0;
Introduction to C Programming
Output
a && b : 1
a || b : 1
!a: 0
Bitwise Operators
The Bitwise operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is performed on the
operands.
Note: Mathematical operations such as addition, subtraction, multiplication, etc. can be
performed at the bit level for faster processing.
There are 6 bitwise operators in C:
Operator Description
Symbol Syntax
Performs bit-by-
bit AND
& Bitwise AND a&b
operation and
returns the result.
Performs bit-by-
bit OR operation
| Bitwise OR a|b
and returns the
result.
Performs bit-by-
bit XOR
^ Bitwise XOR a^b
operation and
returns the result.
Operator Description
Symbol Syntax
number of
positions;
multiplies the
number by 2 for
each shift.
int main() {
int a = 25, b = 5;
return 0;
}
Output
a & b: 1
a | b: 29
a ^ b: 28
~a: -26
a >> b: 0
a << b: 800
Assignment Operators
Introduction to C Programming
Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data type as the variable on the left
side otherwise the compiler will raise an error.
The assignment operators can be combined with some other operators in C to provide
multiple operations using single operator. These operators are called compound operators.
In C, there are 11 assignment operators:
Operator Description
Symbol Syntax
Operator Description
Symbol Syntax
Assign the
remainder in the
Modulus and division of left
%= assign operand with the a %= b
right operand to
the left operand.
Performs bitwise
AND and assigns
&= AND and assign a &= b
this value to the
left operand.
Performs bitwise
OR and assigns
|= OR and assign a |= b
this value to the
left operand.
Performs bitwise
XOR and assigns
^= XOR and assign a ^= b
this value to the
left operand.
Performs bitwise
Rightshift and
Rightshift and
>>= assign this value a >>= b
assign
to the left
operand.
Operator Description
Symbol Syntax
int main() {
int a = 25, b = 5;
return 0;
}
Output
a = b: 5
a += b: 10
a -= b: 5
a *= b: 25
a /= b: 5
a %= b: 0
a &= b: 0
a |= b: 5
a ^= b: 0
a >>= b: 0
a <<= b: 0
Introduction to C Programming
Other Operators
Apart from the above operators, there are some other operators available in C used to
perform some specific tasks. Some of them are discussed here:
sizeof Operator
sizeof is much used in the C programming language.
It is a compile-time unary operator which can be used to compute the size of its
operand.
The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
Basically, the sizeof the operator is used to compute the size of the variable or datatype.
Syntax
sizeof (operand)
Comma Operator ( , )
The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
The comma operator has the lowest precedence of any C operator. It can act as both
operator and separator.
Syntax
operand1 , operand2
Conditional Operator ( ? : )
The conditional operator is the only ternary operator in C++. It is a conditional operator
that we can use in place of if..else statements.
Syntax
expression1 ? Expression2 : Expression3;
Here, Expression1 is the condition to be evaluated. If the condition(Expression1)
is True then we will execute and return the result of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the result of Expression3.
Addressof operator & returns the address of a variable and the dereference operator * is
a pointer to a variable. For example *var; will pointer to a variable var
Example
avoid ambiguity. As, it is very common for a C expression or statement to have multiple
operators and in this expression.
The below table describes the precedence order and associativity of operators in C. The
precedence of the operator decreases from top to bottom.
Precedence Operator Description Associativity
Postfix increment/decrement (a
a++ , a-- left-to-right
1 is a variable)
Prefix increment/decrement (a
++a , --a right-to-left
is a variable)
Logical negation/bitwise
!,~ right-to-left
complement
* Dereference right-to-left
right
10 | Bitwise OR left-to-right
12 || Logical OR left-to-right
14 = Assignment right-to-left
Addition/subtraction
+= , -= right-to-left
assignment
Multiplication/division
*= , /= right-to-left
assignment
Modulus/bitwise AND
%= , &= right-to-left
assignment
Bitwise exclusive/inclusive OR
^= , |= right-to-left
assignment
assignment
Formatted input and output functions in C are used to read and write data in a structured
and controlled manner, allowing for conversion between data types and their textual
representations. These functions are part of the standard input/output library (stdio.h).
printf():
This function is used for formatted output to the console (or stdout).
Purpose: Displays data on the console in a structured format.
Syntax: int printf(const char *format, ...);
Usage: The format string contains ordinary characters to be printed as is, and format
specifiers (e.g., %d for integer, %f for float, %s for string) that determine how subsequent
arguments are converted and displayed.
scanf():
This function is used for formatted input from the console (or stdin).
Purpose: Reads data from the user in a specific format.
Syntax: int scanf(const char *format, ...);
Usage: The format string contains format specifiers that define the expected data types of
the input. The subsequent arguments must be pointers to variables where the read data will
be stored.
getchar Function in C
C getchar is a standard library function that takes a single input character from standard
input. The major difference between getchar and getc is that getc can take input from any
no of input streams but getchar can take input from a single standard input stream.
It is defined inside the <stdio.h> header file.
Just like getchar, there is also a function called putchar that prints only one character to
the standard output stream.
Introduction to C Programming
Syntax of getchar() in C
int getchar(void);
getchar() function does not take any parameters.
getch() function in C
getch() is a nonstandard function and is present in conio.h header file which is mostly used
by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it
defined by POSIX.
Like these functions, getch() also reads a single character from the keyboard. But it does not
use any buffer, so the entered character is immediately returned without waiting for the enter
key.
Syntax:
int getch(void);