0% found this document useful (0 votes)
2 views32 pages

Introduction to C Program

The document provides an introduction to the C programming language, detailing its history, key features, and structure. It covers fundamental concepts such as tokens, identifiers, variables, and data types, along with examples of syntax and usage. Additionally, it explains the importance of constants and the rules for naming variables and identifiers in C.

Uploaded by

aboliwable96k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views32 pages

Introduction to C Program

The document provides an introduction to the C programming language, detailing its history, key features, and structure. It covers fundamental concepts such as tokens, identifiers, variables, and data types, along with examples of syntax and usage. Additionally, it explains the importance of constants and the rules for naming variables and identifiers in C.

Uploaded by

aboliwable96k
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Introduction to C Programming

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.

 B, created by Ken Thompson in 1970, was a simplified version of BCPL used in


system programming for Unix.

Why Was C Developed?

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

These are the key features of C language:

 Simplicity: Straightforward syntax, easy to learn and understand.


 Portability: Code can be compiled on various platforms with minimal changes.
 Modularity: Functions help organize and reuse code efficiently.
 Rich Library: Provides numerous built-in functions for common tasks.
 Low-level Memory Access: Pointers allow direct manipulation of memory.
 Efficiency: Compiled into machine code, making programs fast.
 Dynamic Memory Allocation: Flexibility to allocate memory at runtime.
Introduction to C Programming

 Structured Programming: Code is organized into functions for clarity.


 Recursion: Functions can call themselves for complex problem-solving.

Structure of C Program

1.Library File Access


Definition section
Global declaration
2.Functions
Main()
{
Declaration
statement
}
3.User-defined functions
Function1()
{

}
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)

Printf("Hello World") Return 0;

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.

The special characters are listed below:

* + [ ] / \
! “ < > ( )
= | { } # %
, ; : ? & -
_ $ ~ ` ^

White space characters:

Backspace \b Vertical tab \v


newline \n Form feed \f
Horizontal tab \t Carriage return \r

These characteristics combinations are known as escape sequence.

Tokens

In a C program the smallest individual meaningful units is called token.

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.

2. Keywords are reserved words like int, for, while etc.

3. Constants are fixed a value which does not change like 10 π.

4. Operators are symbols which represents an operation like +, -, * etc.

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:

auto break case char const continue default do

doubl
else enum extern float for goto if
e

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

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.

Rules for Naming Identifiers in C

A programmer must follow a set of rules to create an identifier in C:


 Identifier can contain following characters:
o Uppercase (A-Z) and lowercase (a-z) alphabets.
o Numeric digits (0-9).
o Underscore (_).
 The first character of an identifier must be a letter or an underscore.
 Identifiers are case-sensitive.
 Identifiers cannot be keywords in C (such as int, return, if, while etc.).

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, ...;

Rules for Naming Variables in C


We can assign any name to a C variable as long as it follows the following rules:
 A variable name must only contain letters, digits, and underscores.
 It must start with an alphabet or an underscore only. It cannot start with a digit.
 No white space is allowed within the variable name.
 A variable name must not be any reserved word or keyword.
 The name must be unique in the program.
Introduction to C Programming

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() {

// Create integer variable


int num = 3;

// Access the value stored in


// variable
printf("%d", num);
return 0;
}

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.

Program : Program for local variables.


#include <stdio.h>
int main()
{
int m15, n=22;
// m, n are local variables
if (m==n)
Introduction to C Programming

printf("m and n are equal");


else
printf("m and n are not equal"); }
return 0;
}

Output: m and n are not equal

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.

Formal parameters are local to function.


Example:
double addition(int a, int b)
{
double c;
c = a + b;
return c;
Function addition Cintor
}
The function addition has two parameters a and b. This function returns addition of x and y.

Constants in C

In C programming, const is a keyword used to declare a variable as constant, meaning its


value cannot be changed after it is initialized. It is mainly used to protect variables from
being accidentally modified, making the program safer and easier to understand. These
constants can be of various types, such as integer, floating-point, string, or character
constants.
Let's take a look at an example:

#include <stdio.h>
Introduction to C Programming

int main() {

// Defining constant variable


const int a = 10;
printf("%d", a);
return 0;
}

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.

 Types: Integer constants can be represented in various bases:

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 .

2. Floating-point constants (Real constants)


 Definition: These constants represent real numbers with a fractional part.
 Representation: Floating-point constants can be expressed in two forms:
o Decimal form: Includes a decimal point, an optional exponent part, or both.
Example: 3.14, 6.0.
o Exponential form (scientific notation): Uses e or E to indicate the exponent.
Example: 3.14e2 (representing 3.14×1023.14 cross 10 squared 3.14×102).

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”

Backslash character/Escapes Sequence:


 These are some types of characters that have a special type of meaning in the C
language.
 These types of constants must be preceded by a backslash symbol so that the program
can use the special function in them.
 Here is a list of all the special characters used in the C language and their purpose:
Meaning of Character Backslash Character

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

Hexadecimal constant (Here, N – hex.dcml cnst) \XN


Introduction to C Programming

Octal constant (Here, N is an octal constant) \N

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.

Integer Data Type


The integer datatype in C is used to store the integer numbers (any number including
positive, negative and zero without decimal part). Octal values, hexadecimal values, and
decimal values can also be stored in int data type in C.
 Range: -2,147,483,648 to 2,147,483,647
 Size: 4 bytes
 Format Specifier: %d
Format specifiers are the symbols that are used for printing and scanning values of given
data types.
Introduction to C Programming

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;

printf("var = %d", var);


return 0;
}

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';

printf("ch = %c", ch);


return 0;
}

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;

printf("val = %f", val);


return 0;
}

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

double val = 1.4521;

printf("val = %lf", val);


return 0;
}

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.

Derived Data Types


In C, the data types derived from the primitive or built-in data types are called Derived
Data Types. In other words, the derived data types are those data types that are created by
combining primitive data types and other derived data types.
There are three derived data types available in C. They are as follows:
1. Function
2. Array
3. Pointer

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

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
data_type array_name [size];

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.

User-Defined Data Types


The data types defined by the user themself are referred to as user-defined data types.
These data types are derived from the existing data types.
Types of User-Defined Data Types
There are 4 types of user-defined data types in C. They are
1. Structure
2. Union
3. Enum
4. Typedef

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

enum enum_name {const1, const2, ..., constN};


Here, the const1 will be assigned 0, const2 = 1, and so on in the sequence.
4.Typedef
typedef is used to redefine the existing data type names. Basically, it is used to provide new
names to the existing data types. The "typedef" keyword is used for this purpose;

Syntax

typedef existing_name alias_name;

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() {

// Expression for getting sum


int sum = 10 + 20;

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.

Unary, Binary and Ternary Operators


On the basis of the number of operands they work on, operators can be classified into three
types :
Introduction to C Programming

1. Unary Operators: Operators that work on single operand.


Example: Increment( ++) , Decrement(--)
2. Binary Operators: Operators that work on two operands.
Example: Addition (+), Subtraction( -) , Multiplication (*)
3. Ternary Operators: Operators that work on three operands.
Example: Conditional Operator( ? : )

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

% Modulus Returns the a%b


remainder after
diving the left
Introduction to C Programming

Operator Description
Symbol Syntax

operand with the


right operand.

Used to specify
+ Unary Plus the positive +a
values.

Flips the sign of


- Unary Minus the value. -a

Increases the
++ Increment value of the a++
operand by 1.

Decreases the
-- Decrement value of the a--
operand by 1.

Example of C Arithmetic Operators

#include <stdio.h>

int main() {

int a = 25, b = 5;

// using operators and printing results


printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a % b = %d\n", a % b);
printf("+a = %d\n", +a);
printf("-a = %d\n", -a);
printf("a++ = %d\n", a++);
Introduction to C Programming

printf("a-- = %d\n", a--);

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

Returns true if the


left operand is
< Less than less than the right a<b
operand. Else
false

Returns true if the


left operand is
> Greater than greater than the a>b
right operand.
Else false

<= Less than or Returns true if the a <= b


equal to left operand is
less than or equal
to the right
Introduction to C Programming

Operator Description
Symbol Syntax

operand. Else
false

Returns true if the


left operand is
Greater than or greater than or
>= a >= b
equal to equal to right
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.

Example of C Relational Operators

#include <stdio.h>

int main() {
int a = 25, b = 5;

// using operators and printing results


printf("a < b : %d\n", a < b);
printf("a > b : %d\n", a > b);
printf("a <= b: %d\n", a <= b);
printf("a >= b: %d\n", a >= b);
printf("a == b: %d\n", a == b);
printf("a != b : %d\n", a != b);

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.

Returns true if the


! Logical NOT !a
operand is false.

Example of Logical Operators in C


#include <stdio.h>

int main() {
int a = 25, b = 5;

// using operators and printing results


printf("a && b : %d\n", a && b);
printf("a || b : %d\n", a || b);
printf("!a: %d\n", !a);

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.

Flips all the set


Bitwise First
~ and unset bits on ~a
Complement
the number.

<< Bitwise Leftshift Shifts bits to the a << b


left by a given
Introduction to C Programming

Operator Description
Symbol Syntax

number of
positions;
multiplies the
number by 2 for
each shift.

Shifts bits to the


right by a given
Bitwise number of
>> a >> b
Rightshilft positions; divides
the number by 2
for each shift.

Example of Bitwise Operators


#include <stdio.h>

int main() {
int a = 25, b = 5;

// using operators and printing results


printf("a & b: %d\n", a & b);
printf("a | b: %d\n", a | b);
printf("a ^ b: %d\n", a ^ b);
printf("~a: %d\n", ~a);
printf("a >> b: %d\n", a >> b);
printf("a << b: %d\n", a << b);

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

Assign the value


Simple of the right
= Assignment operand to the left a=b
operand.

Add the right


operand and left
operand and
+= Plus and assign a += b
assign this value
to the left
operand.

Subtract the right


operand and left
Minus and operand and
-= assign assign this value a -= b
to the left
operand.

Multiply the right


operand and left
Multiply and operand and
*= assign assign this value a *= b
to the left
operand.

/= Divide and Divide the left a /= b


assign operand with the
right operand and
Introduction to C Programming

Operator Description
Symbol Syntax

assign this value


to the left
operand.

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.

<<= Leftshift and Performs bitwise a <<= b


assign Leftshift and
Introduction to C Programming

Operator Description
Symbol Syntax

assign this value


to the left
operand.

Example of C Assignment Operators


#include <stdio.h>

int main() {
int a = 25, b = 5;

// using operators and printing results


printf("a = b: %d\n", a = b);
printf("a += b: %d\n", a += b);
printf("a -= b: %d\n", a -= b);
printf("a *= b: %d\n", a *= b);
printf("a /= b: %d\n", a /= b);
printf("a %%= b: %d\n", a %= b);
printf("a &= b: %d\n", a &= b);
printf("a |= b: %d\n", a |= b);
printf("a ^= b: %d\n", a ^= b);
printf("a >>= b: %d\n", a >>= b);
printf("a <<= b: %d\n", a <<= b);

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 (&) and Dereference (*) Operators

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

int num = 10;


int* add_of_num = &num;

Operator Precedence and Associativity


Operator Precedence and Associativity is the concept that decides which operator will be
evaluated first in the case when there are multiple operators present in an expression to
Introduction to C Programming

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

() Parentheses (function call) left-to-right

[] Brackets (array subscript) left-to-right

Member selection via object


. left-to-right
name

-> Member selection via a pointer left-to-right

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)

+,- Unary plus/minus right-to-left

Logical negation/bitwise
!,~ right-to-left
complement

Cast (convert value to


(type) right-to-left
temporary value of type)

* Dereference right-to-left

& Address (of operand) right-to-left

Determine size in bytes on this


sizeof right-to-left
2 implementation

3 *,/,% Multiplication/division/modulus left-to-right

4 +,- Addition/subtraction left-to-right

5 << , >> Bitwise shift left, Bitwise shift left-to-right


Introduction to C Programming

Precedence Operator Description Associativity

right

Relational less than/less than or


< , <= left-to-right
equal to

Relational greater than/greater


> , >= left-to-right
6 than or equal to

Relational is equal to/is not


== , != left-to-right
7 equal to

8 & Bitwise AND left-to-right

9 ^ Bitwise XOR left-to-right

10 | Bitwise OR left-to-right

11 && Logical AND left-to-right

12 || Logical OR left-to-right

13 ?: Ternary conditional right-to-left

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

<<=, >>= Bitwise shift left/right right-to-left


Introduction to C Programming

Precedence Operator Description Associativity

assignment

15 , expression separator left-to-right

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).

Key Formatted I/O Functions:

 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);

You might also like