0% found this document useful (0 votes)
18 views49 pages

Basics of C Programming Overview

This document provides an overview of the basics of C programming, including programming paradigms, the structure of a C program, and data types. It discusses imperative and object-oriented programming, the history and features of C, and its applications in various fields. Additionally, it covers the components of a C program, including tokens, identifiers, and user-defined data types.

Uploaded by

akila r
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)
18 views49 pages

Basics of C Programming Overview

This document provides an overview of the basics of C programming, including programming paradigms, the structure of a C program, and data types. It discusses imperative and object-oriented programming, the history and features of C, and its applications in various fields. Additionally, it covers the components of a C program, including tokens, identifiers, and user-defined data types.

Uploaded by

akila r
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

Department Of Artificial Intelligence and Data Science

25ES105 - C Programing
UNIT - I
BASICS OF C PROGRAMMING

Introduction to programming paradigms, Applications of C Language - Structure of C program, C


programming: Data Types ,Constants, Enumeration Constants, Keywords ,Operators: Precedence,
Associativity and Bit manipulations - Expressions - Input/output statements, Assignment statements –
Decision making statements - Switch statement – Looping statements – Preprocessor directives -
Compilation process

Introduction to programming paradigms

 Programming paradigm is an approach to solve problem using some programming language.


 The programming paradigm is divided into two broad categories.
 Imperative programming paradigm
 Declarative programming paradigm

Imperative programming paradigm


 It is one of the oldest programming paradigms. It features close relation to machine architecture. It is
based on Von Neumann architecture.
 It performs step by step task by changing state.
 The paradigm consists of several statements and after execution of all the result is stored. Examples
of Imperative programming paradigm: C, FORTAN, Basic
Advantage
1. Very simple to implement
2. It contains loops, variables etc.
Disadvantage
1. Complex problem cannot be solved
2. Less efficient and less productive
3. Parallel programming is not possible
Figure 1.1 Types Programming Paradigms

 Imperative programming is divided into three broad categories: Procedural, OOP and parallel
processing. These paradigms are as follows:

Procedural programming paradigm


 This programming has a single program that is divided into small piece called procedure (also known as
functions, routines, subroutines). These procedures are combined into one single location with the help
of return statements.
 From the main controlling procedure, a procedure call is used to invoke the required procedure. After
the sequence is processed, the flow of control continues from where the call was made.
 The main program coordinates calls to procedures and hands over appropriate data as parameters.
 The data is processed by the procedures and once the program has finished, the resulting data is
displayed.
 Example: C, Pascal.

Object Oriented Programming

 It is a type of programming in which programmers define not only the data type of a data structure, but
also the types of operations (functions) that can be applied to the data structure.

 In this way, the data structure becomes an object that includes both data and functions. In addition,
programmers can create relationships between one object and another. For example, objects can inherit
characteristics from other objects.

 One of the principal advantages of object-oriented programming techniques over procedural


programming techniques is that they enable programmers to create modules that do not need to be
changed when a new type of object is added.
 This makes object-oriented programs easier to modify. The basic concepts of OOP are as follows:
1. Objects 2. Classes
3. Data abstraction and encapsulation 4. Inheritance
5. Polymorphism 6. Dynamic binding
7. Message passing

History of C Programming
 C is a general purpose structured programming language.

 C was developed by Dennis Ritchie at AT & T Bell laboratories in 1972. It is an outgrowth of an earlier
language called BCPL & B.

 It was named as C to present it as the successor of B language which was developed earlier by Ken
Thompson in 1970 at AT & T Bell laboratories.

 C is a highly portable, which means that C program written for one computer can be run on another with
little or no modification.

 C is well suited for structured programming; thus user has to think of a problem in terms of function
modules and blocks.

 The proper collection of these modules would make a complete program. This modular structure makes
program debugging, testing and maintenance easier.

 C program is basically a collection of functions that are supported by the C library. We can add our
own functions to the C library. With the availability of a large number of functions, the programming
task becomes simple.
Features of C Programming
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
Applications of C Language

1. Operating Systems

 The first operating system to be developed using a high-level programming language was UNIX, which
was designed in the C programming language. Later on, Microsoft Windows and various Android
applications were scripted in C.

2. Embedded Systems

 The C programming language is considered an optimum choice when it comes to scripting applications
and drivers of embedded systems, as it is closely related to machine hardware.

3. GUI

 GUI stands for Graphical User Interface. Adobe Photoshop, one of the most popularly used photo
editors since olden times, was created with the help of C.

 Later on, Adobe Premiere and Illustrator were also created using C.

4. Google

 Google file system and Google chromium browser were developed using C/C++. Not only this, the
Google Open Source community has a large number of projects being handled using C/C++.

5. Compiler Design

 One of the most popular uses of the C language was the creation of compilers.

 Several popular compilers were designed using C such as Bloodshed Dev-C, Clang C, MINGW, and
Apple C.

6. Gaming and Animation

 Since the C programming language is relatively faster than Java or Python, as it is compiler-based, it
finds several applications in the gaming sector.

 Some of the simplest games are coded in C such as Tic-Tac-Toe, The Dino game, The Snake game etc.,

Structure of C Program

 As C is a programming language, let us go into the concepts of programming in C and it is a structured


programming language.

 Every C program contains a number of building blocks.


1. Documentation section
 The documentation section is included in the comments, which contains the author name, the date of
development and the program details.
2. Preprocessor section
 The preprocessor section provides preprocessor statements which direct the compiler to link functions
from the system library.
3. Definition section
 The definition section defines all symbolic constants refer to assigning a macro of a name to a constant.
The general syntax of a symbolic constant is
#define constant_name constant_value

4. Global declaration section


 The global declaration section contains variable declarations which can be accessed anywhere
within the program.
5. Main section
 Main section is divided into two portions, the declaration part and the executable part. The declaration
part used to declare any variables in the main block of the program.
 The executable part contains set of statements within the open and close braces. Execution of the
program begins at the opening braces and ends at the closing braces.
6. User defined function section

 The user defined function section (or) the Sub program section contains user defined functions which
are called by the main function.

 Each user defined function contains the function name, the argument and the return value.
Example:

/* Program to find the area of a circle */


/* Documentation Section */
/* Preprocessor Section */
# include<stdio.h>
# include<conio.h>
/* Definition Section */
/* main( ) function */
void main()
{
/* Local variable declaration */
float area,r;
clrscr();
// Executable part of the program
printf("\n Enter the radius:\n"); scanf("%f",&r);
area= PI*(r*r);
printf("\n Area of the Circle = %8.2f", area); getch();
}
Output
Enter the radius: 4.5
Area of the Circle = 63.58

Lexical Elements /Tokens of C

 In ‘C’ language each and every individual unit is called as Token or Lexical element.

 The various ‘C’ Tokens are

i) Character set

ii) Delimiters

iii) Keywords

iv) Identifiers

v) Data types

vi) Constants

vii) Variables

Character Set

 It is the basic building block to form program elements. The set of characters used in a language is
known as its character set.

 The C character set consists of upper and lower case alphabets, digits, special characters and white
spaces.
 The alphabets and digits are together called the alphanumeric characters.
Delimiters

 In C programming, delimiters are special characters or symbols that serve to separate or define various
elements within the code, helping the compiler understand the structure and meaning of the
program. They mark the boundaries of different units, such as statements, blocks, expressions, and data
elements.

Keywords

 Keywords in C are predefined, reserved words that hold special meaning to the C compiler and are used
to perform specific tasks within a program.
 They are fundamental building blocks of the C language, and their meaning cannot be altered by the
programmer.
 Keywords are predefined or reserved words that have special meanings to the compiler
Example:

#include <stdio.h
int main() {
int return = 10;
printf("%d\n", return);
return 0;
}
Output
./Solution.c: In function 'main':
./Solution.[Link] error: expected identifier or '(' before 'return'
int return = 10;
^
./Solution.[Link] error: expected expression before 'return'
printf("%d\n", return);
^
Let's categorize all keywords based on context for a more clear understanding.
Category Keywords
Data Type Keywords char, int, float, double, void, short, long, signed, unsigned
Operator & Utility Keywords sizeof, return, goto, typedef
Control Flow Keywords if, else, switch, case, default, for, while, do, break, continue
Storage Class Keywords auto, register, static, extern
Type Qualifiers const, volatile
User Defined Types struct, union, enum

Identifiers

 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.).
Feature Keyword Identifier
Definition A keyword is a reserved word with a special An identifier is a user-defined name used to
meaning in C that cannot be used as an refer to variables, functions, arrays, etc.
identifier.
Usage Keywords are predefined in the C language Identifiers are used by programmers to
and are used to define the structure and name variables, functions, and other user-
control flow of the program (e.g., int, if, defined elements (e.g., age, sum, main).
while).
Example int, return, for, if, while totalAmount, studentAge, calculateTotal
Modification Keywords cannot be modified or used for Identifiers can be created and used as per
any other purpose. the programmer’s needs.
Position in Keywords are part of the syntax of C and Identifiers are used for variable names,
Code are used to structure the program. function names, and more throughout the
code.
Case Keywords are case-sensitive (e.g., int and Identifiers are also case-sensitive (e.g., age
Sensitivity Int are different). and Age are different).

Data types and Variables

 Data types in C refer to an extensive system used for declaring variables or functions of different types. The
type of a variable determines how much space it occupies in storage and how the bit pattern stored is
interpreted.
 A related concept is that of "variables", which refer to the addressable location in the memory of the
processor. The data captured via different input devices is stored in the computer memory. A symbolic name
can be assigned to the storage location called variable name.

[Link] Types & Description


.
1 Basic Types - They are arithmetic types and are further classified into: (a) integer types and (b)
floating-point types.
2 Enumerated types - They are again arithmetic types and they are used to define variables that can
only assign certain discrete integer values throughout the program.
3 The type void
The type specifier void indicates that no value is available.
4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function
types.

Integer Data Types in C


The following table provides the details of standard integer types with their storage sizes and value ranges −

Type Storage size Value range


char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 8 bytes -9223372036854775808 to
9223372036854775807
unsigned long 8 bytes 0 to 18446744073709551615
 To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator.
 The expressions sizeof(type) yields the storage size of the object or type in bytes.

Floating-Point Data Types in C

The following table provides the details of standard floating-point types with storage sizes and value ranges and
their precision:
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

 The header file "float.h" defines the macros that allow you to use these values and other details about the
binary representation of real numbers in your programs.
Note: "sizeof" returns "size_t". The type of unsigned integer of "size_t" can vary depending on platform. And, it
may not be long unsigned int everywhere. In such cases, we use "%zu" for the format string instead of
"%d".
User-defined Data Types in C
 There are two user-defined data types struct and union, that can be defined by the user with the help of
the combination of other basic data types.

Struct Data Type


 One of the unique features of C language is to store values of different data types in one variable. The
keywords struct and union are provided to derive a user-defined data type.
 For example,
struct student {
char name[20];
int marks, age;
};
Union Data Type
 A union is a special case of struct where the size of union variable is not the sum of sizes of individual
elements, as in struct, but it corresponds to the largest size among individual elements. Hence, only one
of elements can be used at a time.
 Look at following example:
union ab {
int a;
float b;
};

Void Data Type in C


 The void type specifies that no value is available. It is used in three kinds of situations −
S.N Types & Description
o
1 Function returns as void
There are various functions in C that do not return any value or you can say they return void. A
function with no return value has the return type as void. For example, void exit (int
status);
2 Function arguments as void
There are various functions in C which do not accept any parameter.
A function with no parameter can accept a void. For example, int rand(void);
3 Pointers to void
A pointer of type void * represents the address of an object, but not its type.
For example, a memory allocation function void *malloc( size_t size ); returns a pointer to
void which can be casted to any data type.

Arrays Data Type in C

 An array is a collection of multiple values of same data type stored in consecutive memory locations.
The size of array is mentioned in square brackets [].

 For example,
int marks[5];

 Arrays can be initialized at the time of declaration. The values to be assigned are put in parentheses.
 C also supports multi-dimensional arrays.
int marks[ ]={50,56,76,67,43};

Pointers Data Type in C

 A pointer is a special variable that stores address or reference of another variable/object in the memory.
The name of pointer variable is prefixed by asterisk (*).

 The type of the pointer variable and the variable/object to be pointed must be same.
int x;
int *y;
y = &x;

 Here, "y" is a pointer variable that stores the address of variable "x" which is of "int" type.
 Pointers are used for many different purposes.
 Text string manipulation and dynamic memory allocation are some of the processes where the use of
pointers is mandatory.
Constants
 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.
Example:

#include <stdio.h>
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;

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.
C Variable Initializatio n
 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
Scope of Variables in C
 We have told that a variable can be accessed anywhere once it is declared, but it is partially true.
 A variable can be accessed using its name anywhere in a specific region of the program called
its scope. It is the region of the program where the name assigned to the variable is valid.
 A scope is generally the area inside the {} curly braces.
Example:
// num cannot be accessed here
int main() {
// num cannot be accessed here
{
// Variable declaration
int num;
}
// Cannot be accessed here either
return 0;
}
Enumeration
 An enumeration (or enum) is a user defined data type that contains a set of named integer constants.
 It is used to assign meaningful names to integer values, which makes a program easy to read and
maintain.
Definition
 An enum must be defined before we can use it in program.
enum enum_name {
n1, n2, n3, ...
};
 where, n1, n2, n3, ... are names assigned to an integer value. By default, first name n1 is
assigned 0, n2 is assigned 1 and the subsequent ones are incremented by 1.
Example:
enum calculate {
SUM, DIFFERENCE, PRODUCT, QUOTIENT
};
 Here, the name SUM is automatically assigned 0, DIFFERENCE is assigned 1 and so on. Enum
names should follow the standard C variable naming rules. Uppercase is preferred for easy
identification.
 Also, enum names must be unique in their scope. For example, the below code fails as two
enums items and calculate have same named integer PRODUCT.
enum calculate {
SUM, DIFFERENCE, PRODUCT, QUOTIENT
};
enum item{
PRODUCT, SERVICE
};
Create enum Variables
After enum is defined, we can create variables of that enum by using its specified name.
enum_name v;
Initialization
An enum variable can be initialized either with a name defined in the enum definition or directly with its
Integer value.
Example:
#include <stdio.h>
// Defining enum
enum direction {
EAST, NORTH, WEST, SOUTH
};
int main() {
// Creating enum variable
enum direction dir = NORTH;
printf("%d\n", dir);
// This is valid too
dir = 3;
printf("%d", dir);
return 0; }
Output

1
3
Assign Values Manually
 We can also manually assign desired values to the enum names as shown:
enum enum_name {
n1 = val1, n2 = val2, n3, ...
};
 It is not mandatory to assign all constants. The next name will be automatically assigned a value by
incrementing the previous name's value by 1. For example, n3 here will be (val2 + 1). Also, we can
assign values in any order, but they must be integer only.
Example:
#include <stdio.h>
// Defining enum
enum enm {
a = 3, b = 2, c };
int main() {
// Creating enum variable
enum enm v1 = a;
enum enm v2 = b;
enum enm v3 = c;
printf("%d %d %d", v1, v2, v3);
return 0; }
Output

323

 In the above program, a is assigned the value 3, b is assigned 2, and c will automatically be assigned
the value 3, as the enum values increment from the last assigned value.
 We can also confirm here that two enum names can have same value.

Operators
 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

Unary, Binary and Ternary Operators


On the basis of the number of operands they work on, operators can be classified into three types :
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:
Arithmetic Operators
 The arithmetic operators are used to perform arithmetic/mathematical operations on operands.
Example:
#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++);
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.
Example:
#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;
}

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.
Symbol Operator Description Syntax
&& Logical AND Returns true if both the operands a && b
are true.
|| Logical OR Returns true if both or any o f a || b
the operand is true.
! Logical NOT Returns true if the operand is !a
false.

Example:
#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;
}
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.

Symbol Operator Description Syntax


& Bitwise AND Performs bit-by-bit AND operation and a & b
returns the result.
| Bitwise OR Performs bit-by-bit OR operation and a | b
returns the result.
^ Bitwise XOR Performs bit-by-bit XOR operation and a ^ b
returns the result.
~ Bitwise First Flips all the set and unset bits on the ~a
Complement number.
<< Bitwise Leftshift Shifts bits to the left by a given number of a << b
positions; multiplies the number by 2 for
each shift.
>> Bitwise Shifts bits to the right by a given number of a >> b
Rightshilft positions; divides the number by 2 for each
shift.

Example:
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
 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.
Symbol Operator Description Syntax
= Simple Assign the value of the right operand to the left a = b
Assignment operand.
+= Plus and assign Add the right operand and left operand and assign a += b
this value to the left operand.
-= Minus and assign Subtract the right operand and left operand and a -= b
assign this value to the left operand.
*= Multiply and Multiply the right operand and left operand and a *= b
assign assign this value to the left operand.
/= Divide and assign Divide the left operand with the right operand and a /= b
assign this value to the left operand.
%= Modulus and Assign the remainder in the division of left operand a %= b
assign with the right operand to the left operand.
&= AND and assign Performs bitwise AND and assigns this value to the a &= b
left operand.
|= OR and assign Performs bitwise OR and assigns this value to the a |= b
left operand.
^= XOR and assign Performs bitwise XOR and assigns this value to the a ^= b
left operand.
>>= Rightshift and Performs bitwise Rightshift and assign this value to a >>= b
assign the left operand.
<<= Leftshift and Performs bitwise Leftshift and assign this value to a <<= b
assign the left operand.

Example:
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

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.
dot (.) and arrow (->) Operators
Member operators are used to reference individual members of classes, structures, and unions.
 The dot operator is applied to the actual object.
 The arrow operator is used with a pointer to an object.
Syntax
structure_variable . member;
structure_pointer -> member;
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.
Precedence and Associativity

 Operator precedence and associativity are rules that decide the order in which parts of an expression
are calculated.

 Precedence tells us which operators should be evaluated first, while associativity determines the
direction (left to right or right to left) in which operators with the same precedence are evaluated.
Example:
#include <stdio.h>
int main() {
int a = 6, b = 3, c = 4;
int res;
// Precedence and associativity applied here
res = a + b * c / 2;
printf("%d", res);
return 0;
}
Output
12

 Explanation: The above expression is evaluated as 6 + ( (3 * 4) / 2) = 12, not (6 + 3) * (4 / 2) =


18. So what guided the compiler to evaluate the expression in this way? It is actually the precedence
and associativity of the operators used in this expression.
Operator Precedence
 Operator precedence determines which operation is performed first in an expression with more than
one operator with different precedence. Let's try to evaluate the following expression,
10 + 20 * 30
 The expression contains two operators, + (addition) and * (multiplication). According to operator
precedence, multiplication (*) has higher precedence than addition (+), so multiplication is checked
first.
 After evaluating multiplication, the addition operator is then evaluated to give the final result.

Operator Associativity
 Operator associativity is used when two operators of the same precedence appear in an expression.
Associativity can be either from Left to Right or Right to Left. Let's evaluate the following
expression,
100 / 5 % 2
 The division (/) and modulus (%) operators have the same precedence, so the order in which they are
evaluated depends on their left-to-right associativity.
 This means the division is performed first, followed by the modulus operation. After the calculations,
the result of the modulus operation is determined.
Operator Precedence and Associativity Table
The following tables list the C operator precedence from highest to lowest and the associativity for each of
the operators:
Precedence Operator Description Associativity
Higher to Lower
1 () Parentheses (function call) Left-to-Right
[] Array Subscript (Square Brackets)
. Dot Operator
-> Structure Pointer Operator
++ , -- Postfix increment, decrement
2 ++ / -- Prefix increment, decrement Right-to-Left
+/- Unary plus, minus
!,~ Logical NOT, Bitwise complement
(type) Cast Operator
* Dereference Operator
& Addressof Operator
sizeof Determine size in bytes
3 *,/,% Multiplication, division, modulus Left-to-Right
4 +/- Addition, subtraction Left-to-Right
5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right
6 < , <= Relational less than, less than or equal to Left-to-Right
> , >= Relational greater than, greater than or equal to
7 == , != Relational is equal to, is not equal to Left-to-Right
8 & Bitwise AND Left-to-Right
9 ^ Bitwise exclusive OR Left-to-Right
10 | Bitwise inclusive 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 assignment
*= , /= Multiplication, division assignment
%= , &= Modulus, bitwise AND assignment
^= , |= Bitwise exclusive, inclusive OR assignment
<<=, >>= Bitwise shift left, right assignment
15 , comma (expression separator) Left-to-Right
Bit manipulations
 In C, bitwise operators are used to perform operations directly on the binary representations of
numbers. These operators work by manipulating individual bits (0s and 1s) in a number.
Let’s look at the truth table of the bitwise operators.
X Y X&Y X|Y X^Y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Example of Bitwise Operators in C


#include <stdio.h>
int main()
{
// a = 5 (00000101 in 8-bit binary)
// b = 9 (00001001 in 8-bit binary)
unsigned int a = 5, b = 9;
// The result is 00000001
printf("a&b = %u\n", a & b);
// The result is 00001101
printf("a|b = %u\n", a | b);
// The result is 00001100
printf("a^b = %u\n", a ^ b);
// The result is 11111111111111111111111111111010
// (assuming 32-bit unsigned int)
printf("~a = %u\n", a = ~a);
// The result is 00010010
printf("b<<1 = %u\n", b << 1);
// The result is 00000100
printf("b>>1 = %u\n", b >> 1);
return 0;
}
Output

a&b = 1
a|b = 13
a^b = 12
~a = 4294967290
b<<1 = 18
b>>1 = 4

Expressions

 Expression: An expression is a combination of operators, constants and variables. An expression may


consist of one or more operands, and zero or more operators to produce a value.

 An expression in C is a combination of operands and operators – it computes a single value stored in


a variable. The operator denotes the action or operation to be performed. The operands are the items to
which we apply the operation.
An expression can be defined depending on the position and number of its operator and operands:
1. Infix Expression (operator is used between the operands): a=x+y
2. Postfix Expression (operator is used after the operands): xy+
3. Prefix Expression (operator is used before the operands): +xy
4. Unary Expression (one operator and one operand): x++
5. Binary Expression (one operator and two operands): x+y

Types of Expression

There are six types of expressions. These are shown below:


Input/output statements
Basic Input in C
 scanf() is used to read user input from the console. It takes the format string and the addresses of the
variables where the input will be stored.
Syntax
scanf("formatted_string", address_of_variables/values);
Remember that this function takes the address of the arguments where the read value is to be stored.
Examples of Reading User Input
The following examples demonstrate how to use the scanf for different user input in C:
Reading an Integer
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
// Reads an integer
scanf("%d", &age);
// Prints the age
printf("Age is: %d\n", age);
return 0;
}
Output
Enter your age:
25 (Entered by the user)
Age is: 25
Explanation: %d is used to read an integer; and &age provides the address of the variable where the input
will be stored.
Reading a Character
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: \n");
// Reads an Character
scanf("%c", &ch);
// Prints the Character
printf("Entered character is: %c\n", ch);
return 0;
}

Output
Enter a character:
a (Entered by the user)
Entered character is: a
Reading a string
The scanf() function can also be used to read string input from users. But it can only read single words.
#include <stdio.h>
int main() {
char str[100]; // Declare an array to hold the input string
printf("Enter a string: ");
scanf("%s", str); // Reads input until the first space or newline
printf("You entered: %s\n", str);
return 0; }
Output:
Enter a String:
Geeks (Entered by the user)
Entered string is: Geeks
 The scanf() function can not handle spaces and stops at the first blanksspace. to handle this situation
we can use fgets() which is a better alternative as it can handle spaces and prevent buffer overflow.
fgets()
 fgets() reads the given number of characters of a line from the input and stores it into the specified
string. It can read multiple words at a time.
Syntax
fgets(str, n, stdin);
 where buff is the string where the input will be stored and n is the maximum number of characters to
read. stdin represents input reading from the keyboard.
Example:
#include <stdio.h>
#include <string.h>
int main() {
// String variable
char name[20];
printf("Enter your name: \n");
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
return 0;
}

Output
Enter your name:
John (Entered by User)
Hello, John

 The printf() function is used to print formatted output to the standard output stdout (which is
generally the console screen). It is one of the most commonly used functions in C.
Syntax
printf("formatted_string", variables/values);
Where,
 Formatted String: string defining the structure of the output and include format specifiers
 variables/values: arguments passed to printf() that will replace the format specifiers in the formatted
string.
Examples
The following examples demonstrate the use of printf for output in different cases:
Printing Some Text
Example:
int main() {
// Prints some text
printf("First Print");
return 0; }
Output

First Print

Explanation: The text inside "" is called a string in C. It is used to represent textual information. We can
directly pass strings to the printf() function to print them in console screen.
fputs()
The fputs() function is used to output strings to the files but we can also use it to print strings to the console
screen.
Syntax:
fputs("your text here", stdout); // Where, the stdout represents that the text should be printed to console.
Example:
#include <stdio.h>
int main() {
fputs("This is my string", stdout);
return 0;
}
Output

This is my string
Assignment statements
In C, assignment operators are used to assign values to variables. The left operand is the variable and the right
operand is the value being assigned. The value on the right must match the data type of the variable
otherwise, the compiler will raise an error.
Example:
int main() {
// Assigning value 10 to a
// using "=" operator
int a = 10;
printf("%d", a);
return 0;
}
Output

10

Explanation: In the above example, the assignment operator (=) is used to assign the value 10 to the
variable a. The printf() function then prints the value of a, which is 10, to the console.
Syntax
variable = value;
Example:
#include <stdio.h>
int main() {
int x = 22;
// Assigning value 10 to a
// using "=" operator
int a = x;
printf("%d", a);
return 0; }
Output

22

Decision making statements ,Switch statement ,Looping statements


 In C, programs can choose which part of the code to execute based on some condition. This ability is
called decision making and the statements used for it are called conditional statements.

 These statements evaluate one or more conditions and make the decision whether to execute a block of
code or not.
 For example, consider that there is a show that starts only when certain number of people are present
in the audience.
Example:
#include <stdio.h>
int main() {
// Number of people in the audience
int num = 100;
// Conditional code inside decision making statement
if (num > 50) {
printf("Start the show");
}
return 0;
}
Output

Start the show

Types of Conditional Statements in C


1. if in C
 The if statement is the simplest decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a block of
statements is executed otherwise not. A condition is any expression that evaluates to either a true or
false (or values convertible to true or flase).
Example
int main() {
int i = 10;
// If statement
if (i < 18) {
printf("Eligible for vote");
}}
Output

Eligible for vote

The expression inside () parenthesis is the condition and set of statements inside {} braces is its body. If the
condition is true, only then the body will be executed.
If there is only a single statement in the body, {} braces can be omitted.
2. if-else in C
The if statement alone tells us that if a condition is true, it will execute a block of statements and if the
condition is false, it won’t. But what if we want to do something else when the condition is false? Here comes
the C else statement. We can use the else statement with the if statement to execute a block of code when the
condition is false. The if-else statement consists of two blocks, one for false expression and one for true
expression.
Example
#include <stdio.h>
int main() {
int i = 10;

if (i > 18) {
printf("Eligible for vote");
}
else {
printf("Not Eligible for vote");
}
return 0;
}
Output

Not Eligible for vote

The block of code following the else statement is executed as the condition present in the if statement is false.
3. Nested if-else in C
A nested if in C is an if statement that is the target of another if statement. Nested if statements mean an if
statement inside another if statement. Yes, C allow us to nested if statements within if statements, i.e, we can
place an if statement inside another if statement.
Example
#include <stdio.h>
int main(){
int i = 10;
if (i == 10) {
if (i < 18)
printf("Still not eligible for vote");
else
printf("Eligible for vote\n");
}
else {
if (i == 20) {
if (i < 22)
printf("i is smaller than 22 too\n");
else
printf("i is greater than 25");
}
}
return 0;
}

Output

Still not eligible for vote

4. if-else-if Ladder in C
 The if else if statements are used when the user has to decide among multiple options. The C if
statements are executed from the top down.
 As soon as one of the conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the
final else statement will be executed. if-else-if ladder is similar to the switch statement.
Example
#include <stdio.h>
int main() {
int i = 20;

// If else ladder with three conditions


if (i == 10)
printf("Not Eligible");
else if (i == 15)
printf("wait for three years");
else if (i == 20)
printf("You can vote");
else
printf("Not a valid age");
return 0;
}

Output

You can vote

5. switch Statement in C
 The switch case statement is an alternative to the if else if ladder that can be used to execute the
conditional code based on the value of the variable specified in the switch statement.
 The switch block consists of cases to be executed based on the value of the switch variable.

Example
int main() {
// variable to be used in switch statement
int var = 18;
// declaring switch cases
switch (var) {
case 15:
printf("You are a kid");
break;
case 18:
printf("Eligible for vote");
break;
default:
printf("Default Case is executed");
break;
}
return 0;
}

Output

Eligible for vote

Note: The switch expression should evaluate to either integer or character. It cannot evaluate any other data
type.
6. Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar to the if-else statement.
It is also known as the ternary operator as it works on three operands.
Example:
#include <stdio.h>
int main() {
int var;
int flag = 0;

// using conditional operator to assign the value to var


// according to the value of flag
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is 0: %d\n", var);
return 0;
}
Output
Value of var when flag is 0: 25

7. Jump Statements in C
These statements are used in C for the unconditional flow of control throughout the functions in a program.
They support four types of jump statements:
A) break
This loop control statement is used to terminate the loop. As soon as the break statement is encountered from
within a loop, the loop iterations stop there, and control returns from the loop immediately to the first
statement after the loop.
Example
#include <stdio.h>
int main() {
int arr[] = { 1, 2, 3, 4, 5, 6 };
int key = 3;
int size = 6;
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
printf("Element found at position: %d",
(i + 1));
break;
} }
return 0;
}
Output

Element found at position: 3

B) Continue
 This loop control statement is just like the break statement. The continue statement is opposite to that
of the break statement, instead of terminating the loop, it forces to execute the next iteration of the
loop.
 As the name suggests the continue statement forces the loop to continue or execute the next iteration.
 When the continue statement is executed in the loop, the code inside the loop following the continue
statement will be skipped and the next iteration of the loop will begin.
Example:
#include <stdio.h>
int main() {

for (int i = 1; i <= 10; i++) {


// If i is equals to 6,
// continue to next iteration
// without printing
if (i == 6)
continue;
else
printf("%d ", i);
}
return 0;
}
Output

1 2 3 4 5 7 8 9 10

C) goto
The goto statement in C also referred to as the unconditional jump statement can be used to jump from one
point to another within a function.
Examples:
#include <stdio.h>
int main() {
int n = 1;
label:
printf("%d ", n);
n++;
if (n <= 10)
goto label;
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10

D) return
 The return in C returns the flow of the execution to the function from where it is called. This statement
does not mandatorily need any conditional statements.
 As soon as the statement is executed, the flow of the program stops immediately and returns the
control from where it was called. The return statement may or may not return anything for a void
function, but for a non-void function, a return value must be returned.
Example:
#include <stdio.h>
int sum(int a, int b) {
int s1 = a + b;
return s1;
}
int main()
{
int num1 = 10;
int num2 = 10;
int sumOf = sum(num1, num2);
printf("%d", sumOf);
return 0;
}

Output

20

Preprocessor directives

 In C programming, the preprocessor is a program that process the source code before the actual
compilation begins.

 It uses preprocessor directives are commands that instruct the preprocessor to perform specific
actions. These directives start with the #
List of Preprocessor Directives

Preprocessor Directives Description


#define Used to define a macro.
#undef Used to undefine a macro.
#include Used to include a file in the source code program.
#ifdef Used to include a section of code if a certain macro is defined by #define.
#ifndef Used to include a section of code if a certain macro is not defined by
#define.
#if Check for the specified condition.
#else Alternate code that executes when #if fails.
#endif Used to mark the end of #if, #ifdef, and #ifndef.
#error Used to generate a compilation error message.
#line Used to modify line number and filename information.
#pragma once To make sure the header is included only once.
#pragma message Used for displaying a message during compilation.

#define
 In C, the #define preprocessor directive is used to define the macros and symbolic constants.
 The macros are the identifiers defined by #define which are replaced by their value before
compilation.
Example:
#include <stdio.h>
// Defining a macro for PI
#define PI 3.14159
int main()
{
// Using the PI macro to calculate
double r = 8.0;
10double area = PI * r * r;
printf("%f\n", a);
return 0;
}
Output
201.067
#include
 #include preprocessor directive is used to include the contents of a specified file into the source code
before compilation.
 It allows you to use functions, constants, and variables from external libraries or header files. There
are two types:
#include <file_name>
#include "filename"
 Here, file inclusion with double quotes ( ” ” ) tells the compiler to search for the header file in the
directory of source file while <> is used for system libraries.
Example:

// Including standard input output library


// using its header file
#include <stdio.h>
int main(){
// Using standard library functions
printf("Hello, Geek!\n");
return 0;
}
Output
Hello! Geek
Sum: 15
Compilation process
 A sequence of binary instructions consisting of 1 and 0 bits is called as machine code
 High-level programming languages such as C, C++, Java, etc. consist of keywords that are closer to
human languages such as English. Hence, a program written in C (or any other high-level language)
needs to be converted to its equivalent machine code. This process is called compilation.
 Note that the machine code is specific to the hardware architecture and the operating system. In other
words, the machine code of a certain C program compiled on a computer with Windows OS will not be
compatible with another computer using Linux OS.
 Hence, we must use the compiler suitable for the target OS.
C Compilation Process Steps

Example
Let us consider the following source code in C languge (main.c)
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello World! \n");
return 0; }
Output
Hello World!
Explanation:
 The ".c" is a file extension that usually means the file is written in C. The first line is the preprocessor
directive #include that tells the compiler to include the stdio.h header file. The text inside /* and */ are
comments and these are useful for documentation purpose.
 The entry point of the program is the main() function. It means the program will start by executing the
statements that are inside this functions block.
 Here, in the given program code, there are only two statements: one that will print the sentence "Hello
World" on the terminal, and another statement that tells the program to "return 0" if it exited or ended
correctly. So, once we compiled it, if we run this program we will only see the phrase "Hello World"
appearing.
What Goes Inside the C Compilation Process?
In order for our "main.c" code to be executable, we need to enter the command "gcc main.c", and the compiling
process will go through all of the four steps it contains.

Step 1: Preprocessing
The preprocessor performs the following actions −

 It removes all the comments in the source file(s).


 It includes the code of the header file(s), which is a file with extension .h which contains C function
declarations and macro definitions.
 It replaces all of the macros (fragments of code which have been given a name) by their values.
The output of this step will be stored in a file with a ".i" extension, so here it will be in "main.i".
In order to stop the compilation right after this step, we can use the option "-E" with the gcc command on the
source file, and press Enter.
gcc -E main.c
Step 2: Compiling
 The compiler generates the IR code (Intermediate Representation) from the preprocessed file, so this
will produce a ".s" file. That being said, other compilers might produce assembly code at this step of
compilation.
 We can stop after this step with the "-S" option on the gcc command, and press Enter.
gcc -S main.c
This is what the main.s file should look like −
.file "helloworld.c"
.text
.def __main; .scl 2; .type 32; .endef
.section .rdata,"dr"
.LC0:
.ascii "Hello, World! \0"
.text
.globl main
.def main; .scl 2; .type 32; .endef
.seh_proc main
main:
pushq %rbp
.seh_pushreg %rbp
movq %rsp, %rbp
.seh_setframe %rbp, 0
subq $32, %rsp
.seh_stackalloc 32
.seh_endprologue
call __main
leaq .LC0(%rip), %rcx
call puts
movl $0, %eax
addq $32, %rsp
popq %rbp
ret
.seh_endproc
.ident "GCC: (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0"
.def puts; .scl 2; .type 32; .endef

Step 3: Assembling
 The assembler takes the IR code and transforms it into object code, that is code in machine language
(i.e. binary). This will produce a file ending in ".o".
 We can stop the compilation process after this step by using the option "-c" with the gcc command, and
pressing Enter.

 Note that the "main.o" file is not a text file, hence its contents won't be readable when you open this file
with a text editor.
Step 4: Linking
 The linker creates the final executable, in binary. It links object codes of all the source files together.
The linker knows where to look for the function definitions in the static libraries or the dynamic
libraries.
 Static libraries are the result of the linker making a copy of all the used library functions to the
executable file. The code in dynamic libraries is not copied entirely, only the name of the library is
placed in the binary file.

 By default, after this fourth and last step, that is when you type the whole "gcc main.c" command
without any options, the compiler will create an executable program called [Link] (or [Link] in
case of Windows) that we can run from the command line.

 We can also choose to create an executable program with the name we want, by adding the "-o" option
to the gcc command, placed after the name of the file or files we are compiling.

gcc main.c -o [Link]


 So now we could either type "./[Link]" if you didnt use the "-o" option or "./hello" to execute the
compiled code. The output will be "Hello World" and following it, the shell prompt will appear again.

You might also like