0% found this document useful (0 votes)
8 views151 pages

C Programming Basics and Applications

The document provides an overview of the basics of C programming, including its structure, data types, constants, and applications. It discusses the advantages and drawbacks of the C language, as well as its use in system programming, embedded systems, and game development. Additionally, it outlines the structure of a C program, including documentation, preprocessor directives, and the main function.

Uploaded by

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

C Programming Basics and Applications

The document provides an overview of the basics of C programming, including its structure, data types, constants, and applications. It discusses the advantages and drawbacks of the C language, as well as its use in system programming, embedded systems, and game development. Additionally, it outlines the structure of a C program, including documentation, preprocessor directives, and the main function.

Uploaded by

xakoto6864
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dept of MCA

Module 1: BASICS OF C PROGRAMMING

Unit1: Introduction to programming paradigms Applications of C


Language - Structure of C program

Unit2: C programming: Data Types - Constants Enumeration Constants -


Keywords
Dept of MCA

Unit3: Operators: Precedence and Associativity - Expressions -


Input/Output statements, Assignment statements Decision making
statements - Switch statement - Looping statements Preprocessor
directives - Compilation process
Unit1: introduction to C programming

Introduction to programming paradigms


Applications of C Language
Structure of C program

Dept of MCA
Introduction to programming paradigms
C is a general-purpose procedural programming language
initially developed by Dennis Ritchie in 1972 at Bell
Laboratories of AT&T Labs.
It was mainly created as a system programming language to
write the UNIX operating system.
C has now become a widely used professional language for
Dept of MCA
various reasons
• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low−level activities
• It can be compiled on a variety of computer platforms.
Advantages of C Language
The following are the advantages of C language
• Efficiency and speed − C is known for being high−performing and
efficient. It can let you work with memory at a low level, as well as
allow direct access to hardware, making it ideal for applications
requiring speed and economical resource use.
• Portable − C programs can be compiled and executed on different
platforms with minimal or no modifications. This portability is due to
the fact that the language has been standardized and compilers are
Dept of MCA
available for use on various operating systems globally.
• Close to Hardware − C allows direct manipulation of hardware
through the use of pointers and low−level operations. This makes it
suitable for system programming and developing applications that
require fine-grained control over hardware resources.
• Standard Libraries − For common tasks such as input/output
operations, string manipulation, and mathematical computations, C
comes with a large standard library which helps developers write
code more efficiently by leveraging pre−built functions.
• Structured Programming − C helps to organize code into modular and
easy−to−understand structures. With functions, loops,
and conditionals, developers can produce clear code that is easy to
maintain.
• Procedural Language − C follows a procedural paradigm that is often
simpler and more straightforward for some types of programming
tasks.
Dept of MCA • Versatility − C language is a versatile programming language and it
can be used for various types of software such as system applications,
compilers, firmware, application software, etc.
Drawbacks of C Language
The following are the disadvantages/drawbacks of C language
• Manual Memory Management − C languages need manual memory
management, where a developer has to take care of allocating and
deallocating memory explicitly.
• No Object−Oriented Feature − Nowadays, most of the programming
languages support the OOPs features. But C language does not
support it.
Dept of MCA
• No Garbage Collection − C language does not support the concept of
Garbage collection. A developer needs to allocate and deallocate
memory manually and this can be error-prone and lead to memory
leaks or inefficient memory usage.
• No Exception Handling − C language does not provide any library for
handling exceptions. A developer needs to write code to handle all
types of expectations.
Applications of C Language
The following are the applications of C language −
• System Programming − C language is used to develop system
software which are close to hardware such as operating systems,
firmware, language translators, etc.
• Embedded Systems − C language is used in embedded system
programming for a wide range of devices such as microcontrollers,
industrial controllers, etc.
Dept of MCA
• Compiler and Interpreters − C language is very common to develop
language compilers and interpreters.
• Database Systems − Since C language is efficient and fast for low-
level memory manipulation. It is used for developing DBMS and
RDBMS engines.
• Networking Software − C language is used to develop networking
software such as protocols, routers, and network utilities.
• Game Development − C language is widely used for developing
games, gaming applications, and game engines.
• Scientific and Mathematical Applications − C language is efficient in
developing applications where scientific computing is required.
Applications such as simulations, numerical analysis, and other
Dept of MCA scientific computations are usually developed in C language.
• Text Editor and IDEs − C language is used for developing text editors
and integrated development environments such as Vim and Emacs.
Structure of C program
The basic structure of a C program is divided into 6 parts which makes it
easy to read, modify, document, and understand in a particular format

Dept of MCA
1. Documentation
This section consists of the description of the program, the name of the
program, and the creation date and time of the program. It is specified
at the start of the program in the form of comments. Documentation
can be represented as:

// description, name of the program, programmer name, date, time etc.


Dept of MCA Or
/*
description, name of the program, programmer name, date, time etc.
*/

Anything written as comments will be treated as documentation of the


program and this will not interfere with the given code. Basically, it
gives an overview to the reader of the program.
2. Preprocessor Section
All the header files of the program will be declared in
the preprocessor section of the program. Header files help us to access
other's improved code into our code. A copy of these multiple files is inserted
into our program before the process of compilation.
Example :
#include<stdio.h>
#include<math.h>
3. Definition
Dept of MCA
Pre-processors are the programs that process our source code before the
process of compilation. There are multiple steps which are involved in the
writing and execution of the program.
Preprocessor directives start with the '#' symbol. The #define preprocessor is
used to create a constant throughout the program.
Whenever this name is encountered by the compiler, it is replaced by the
actual piece of defined code.
Example :
#define long long ll
4. Global Declaration
The global declaration section contains global variables, function declaration,
and static variables. Variables and functions which are declared in this scope
can be used anywhere in the program.
Example:
int num = 18;
5. Main() Function
Every C program must have a main function. The main() function of the
Dept of MCA program is written in this section.
Operations like declaration and execution are performed inside the curly
braces of the main program. The return type of the main() function can be int
as well as void too.
void() main tells the compiler that the program will not return any value. The
int main() tells the compiler that the program will return an integer value.
Example :
int main () or void main
6. Sub Programs
User-defined functions are called in this section of the program. The
control of the program is shifted to the called function whenever they
are called from the main or outside the main() function. These are
specified as per the requirements of the programmer.
Example:
int sum(int x, int y)
{
Dept of MCA return x+y;
}
Example : Structure of a c program
// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/
Dept of MCA
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
Dept of MCA }
// Subprogram
int sum(int y)
{
return y + X;
}
Dept of MCA
Unit1: Introduction to programming paradigms Applications of C
Language - Structure of C program

Unit2: C programming: Data Types - Constants Enumeration Constants -


Keywords
Dept of MCA

Unit3: Operators: Precedence and Associativity - Expressions -


Input/Output statements, Assignment statements Decision making
statements - Switch statement - Looping statements Preprocessor
directives - Compilation process
Unit2: C programming

Data Types
Constants
Enumeration Constants
Keywords
Dept of MCA
Data Types
It specifies the type of data that the variable can store like
integer, character, floating, double, etc.

Dept of MCA
Integer Data Type
• Stores whole numbers (positive, negative, or zero).
• We use int keyword to declare the integer variable:
• Size: 4 bytes, Range: -2,147,483,648 to 2,147,483,647.
• Format specifier: %d.
Format specifiers are the symbols that are used for printing
and scanning values of given data types.
Dept of MCA
#include <stdio.h>
int main() {
int var = 22;
printf("var = %d", var);
return 0;
}
Character Data Type
• Stores a single character (like ‘A’, ‘b’, or ‘5’).
• Size: 1 byte, Range: -128 to 127 (signed by default).
• Format specifier: %c.

#include <stdio.h>
Dept of MCA
int main() {
char ch = 'A';
printf("ch = %c", ch);
return 0;
}
Float Data Type
•Stores decimal numbers (numbers with fractional part).
•Size: 4 bytes, Approximate range: 3.4e-38 to 3.4e+38.
•Format specifier: %f.

#include <stdio.h>
int main() {
Dept of MCA
float val = 12.45;
printf("val = %f", val);
return 0;
}
Double Data Type
• Stores decimal numbers with more precision than float.
• Size: 8 bytes, Approximate range: 1.7e-308 to 1.7e+308.
• Format specifier: %lf.
#include <stdio.h>
int main() {
Dept of MCA
double val = 1.4521;
printf("val = %lf", val);
return 0;
}
Void Data Type
• Represents no value or empty type.
• Used in functions that do not return any value.
• Can also be used for generic pointers (void *) in memory operations.

#include <stdio.h>
// Function with void return type
void greet()
Dept of MCA
{
printf("Hello, welcome!\n");
}
int main()
{
greet();
return 0;
}
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.
Dept of MCA
These constants can be of various types, such as integer,
floating-point, string, or character constants.

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


#include <stdio.h>
int main() {
// Defining constant variable
const int a = 10;
printf("%d", a);
Dept of MCA
return 0;
}
1. Initialization with Declaration
We can only initialize the constant variable in C at the time of its
declaration. If we do not initialize it at the time of declaration, it will store
the garbage value that was previously stored in the same memory.

const int a = 10;

Dept of MCA 2. Immutability


The constant variables in C are immutable after its definition, i.e., they can be
initialized only once in the whole program. After that, we cannot modify the
value stored inside that variable.
// Declaring a constant variable
const int a;

// Initializing constant variable var after declaration


a = 20;
Constants Using #define
In C, the #define directive can also be used to define
symbolic constants that do not require a data type. They are
called macros and are replaced by their values at compile
time.
Syntax:

Dept of MCA #define CONSTANT_NAME value


#include <stdio.h>
#define PI 3.14
int main() {
printf("%.2f", PI);
return 0;
}
Enumeration (or enum) in C
An enumeration (or enum) is a user defined data type that contains a
set of named integer constants.

An enum is a special type that represents a group of constants


(unchangeable values).

To create an enum, use the enum keyword, followed by the name of


Dept of MCA
the enum, and separate the enum items with a comma.

It is used to assign meaningful names to integer values, which makes a


program easy to read and maintain.

An enum must be defined before we use it in the program.


Syntax:
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
Dept of MCA 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.
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
};
Dept of MCA

enum item{
PRODUCT, SERVICE
};
Create enum Variables
To access the enum, you must create a variable of it.
After enum is defined, we can create variables of that enum by using
its specified name.

Syntax :
enum_name v;
Dept of MCA

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>
enum Level {
LOW,
MEDIUM,
HIGH
};
int main() {
Dept of MCA // Create an enum variable and assign a value to it
enum Level myVar = MEDIUM;

// Print the enum variable


printf("%d", myVar);

return 0;
}
Assign Values Manually
We can also manually assign desired values to the enum
names as shown:
enum enum_name {
n1 = val1, n2 = val2, n3, ...
};
Dept of MCA 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.
#include <stdio.h>
// Defining enum
enum enm {
a = 3, b = 2, c
};
Dept of MCA
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;
}
Size of Enums
Enum definition is not allocated any memory, it is only allocated for
enum variables.
enums are implemented as integers, so their size is same as that of int.
We can use the sizeof operator to check the size of enum variable.
Example:
#include <stdio.h>
// Defining enum
enum direction {
Dept of MCA
EAST, NORTH, WEST, SOUTH
};
int main() {
enum direction dir = NORTH;
// Checking the size of enum
printf("%ld bytes", sizeof(dir));
return 0;
}
Enum and Typedef
The typedef keyword can be used to define an alias for an enum
so that we can avoid using the keyword enum again and again.

#include <stdio.h>
// Defining enum
typedef enum direction {
EAST, NORTH, WEST, SOUTH
Dept of MCA }Dirctn;
int main() {
Dirctn dir = NORTH;

// Checking the size of enum


printf("%d", dir);
return 0;
}
In the above program, typedef is used to create a nickname
Dirctn for the direction enum so that we can directly refer to
it by using the nickname. It enhances the code readability.

Dept of MCA
Dept of MCA
Dept of MCA
Dept of MCA
Unit1: Introduction to programming paradigms Applications of C
Language - Structure of C program

Unit2: C programming: Data Types - Constants Enumeration Constants -


Keywords
Dept of MCA

Unit3: Operators: Precedence and Associativity - Expressions -


Input/Output statements, Assignment statements Decision making
statements - Switch statement - Looping statements Preprocessor
directives - Compilation process
Unit3: Operators
Precedence and Associativity
Expressions
Input/output statements
Assignment statements
Decision making statements
Dept of MCA
Switch statement
Looping statements
Pre-processor directives
Compilation process
Operators
Operators are the 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.
Dept of MCA
Example:
sum = 10 + 20;
Where sum , 10 and are the operands ,
= and + are the operators.
On the basis of the number of operands they work on,
operators can be classified into three types :
• Unary Operators: Operators that work on single operand.
Example: Increment( ++ ) , Decrement( -- )
• Binary Operators: Operators that work on two operands.
Example: Addition ( + ), Subtraction( - ) , Multiplication ( * )
Dept of MCA
• Ternary Operators: Operators that work on three operands.
Example: Conditional Operator( ? : )
Types of Operators in C
Operators that can be classified into 6 types based on their
functionality:
Arithmetic Operators
Arithmetic operators are the type of operators used to
perform basic math operations like addition, subtraction, and
multiplication. T
Dept of MCA hey are used with numeric variables to perform calculations
in programs.
There are 9 arithmetic operators in C language. These can be
classified into two types based on the number of operands
they work on:
• Binary Arithmetic Operators
• Unary Arithmetic Operators
1. Binary Arithmetic Operators
The binary arithmetic operators work on two operands. C
provides 5 such operators for performing arithmetic
functions which are as follows:
Name Operator Arithmetic Operation Syntax
Addition + Add two operands. x+y

Dept of MCA Subtract the second operand from


Subtraction - x-y
the first operand.

Multiplication * Multiply two operands. x*y

Divide the first operand by the


Division / x/y
second operand.

Calculate the remainder when the


Modulus % first operand is divided by the x%y
second operand.
2) Unary Arithmetic Operators
The unary arithmetic operators work with a single operand.
In C, we have four such operators which are as follows:
Operato
Name Description Syntax
r
Decreases the integer value of
Decrement -- --a or a--
the variable by one.
Dept of MCA
Increases the integer value of
Increment ++ ++a or a++
the variable by one.

Returns the value of its


Unary Plus + +a
operand.

Unary Returns the negative of the


- -a
Minus value of its operand.
example:
#include <stdio.h>

int main() {
int a = 25, b = 5;
a + b = 30
// using operators and printing results a - b = 20
printf("a + b = %d\n", a + b); a * b = 125
printf("a - b = %d\n", a - b); a / b = 5
a % b = 0
Dept of MCA printf("a * b = %d\n", a * b);
+a = 25
printf("a / b = %d\n", a / b); -a = -25
printf("a %% b = %d\n", a % b); a++ = 25
printf("+a = %d\n", +a); a-- = 26

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


printf("a++ = %d\n", a++);
printf("a-- = %d\n", a--);
return 0;
}
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.

Dept of MCA • Equal to operator (==)


• Not equal to operator (!=)
• Greater than operator (>)
• Less than operator (<)
• Greater than or equal to operator (>=)
• Less than or equal to the the operator (<=)
example:
#include <stdio.h>
int main() {
int a = 25, b = 5;
// using operators and printing results a < b : 0
printf("a < b : %d\n", a < b); a > b : 1
printf("a > b : %d\n", a > b); a <= b: 0
Dept of MCA
a >= b: 1
printf("a <= b: %d\n", a <= b); a == b: 0
printf("a >= b: %d\n", a >= b); a != b: 1
printf("a == b: %d\n", a == b);
printf("a != b : %d\n", a != b);
return 0;
}
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

Dept of MCA
&& Logical AND Returns true if both the operands are true. a && b

Returns true if both or any of the operand


|| Logical OR a || b
is true.

! Logical NOT Returns true if the operand is false. !a


Example:
#include <stdio.h>
int main() {
int a = 25, b = 5;
// using operators and printing results
printf("a && b : %d\n", a && b);
Dept of MCA
printf("a || b : %d\n", a || b); a && b : 1
a || b : 1
printf("!a: %d\n", !a); !a: 0

return 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.
• The & (bitwise AND) in C takes two numbers as operands
and does AND on every bit of two numbers. The result of
Dept of MCA
AND is 1 only if both bits are 1.
• The | (bitwise OR) in C takes two numbers as operands and
does OR on every bit of two numbers. The result of OR is 1
if any of the two bits is 1.
• The ^ (bitwise XOR) in C takes two numbers as operands
and does XOR on every bit of two numbers. The result of
XOR is 1 if the two bits are different.
• The << (left shift) in C takes two numbers, the left shifts the
bits of the first operand, and the second operand decides
the number of places to shift.
• The >> (right shift) in C takes two numbers, right shifts the
bits of the first operand, and the second operand decides
the number of places to shift.
Dept of MCA
• The ~ (bitwise NOT) in C takes one number and inverts all
bits of it.
Example:
#include <stdio.h>
int main() {
int a = 25, b = 5;

// using operators and printing results


printf("a & b: %d\n", a & b); a & b: 1
printf("a | b: %d\n", a | b); a | b: 29
Dept of MCA a ^ b: 28
printf("a ^ b: %d\n", a ^ b);
~a: -26
printf("~a: %d\n", ~a);
a >> b: 0
printf("a >> b: %d\n", a >> b);
a << b: 800
printf("a << b: %d\n", a << b);

return 0;
}
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
Dept of MCA an error.
Symbol Operator Description Syntax

Assign the value of the right operand


= Simple Assignment a=b
to the left operand.

Add the right operand and left


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

Subtract the right operand and left


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

Multiply the right operand and left


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

Divide the left operand with the right


/= Divide and assign operand and assign this value to the a /= b
left operand.
Assign the remainder in the division
Modulus and
%= of left operand with the right a %= b
assign
operand to the left operand.
AND and Performs bitwise AND and assigns
&= a &= b
assign this value to the left operand.
Performs bitwise OR and assigns this
|= OR and assign a |= b
value to the left operand.
Dept of MCA
XOR and Performs bitwise XOR and assigns
^= a ^= b
assign this value to the left operand.

Rightshift and Performs bitwise Rightshift and


>>= a >>= b
assign assign this value to the left operand.

Leftshift and Performs bitwise Leftshift and assign


<<= a <<= b
assign this value to the left operand.
#include <stdio.h>
int main() {
int a = 25, b = 5;
// using operators and printing results
a = b: 5
printf("a = b: %d\n", a = b); a += b: 10
printf("a += b: %d\n", a += b); a -= b: 5
printf("a -= b: %d\n", a -= b); a *= b: 25
a /= b: 5
printf("a *= b: %d\n", a *= b);
a %= b: 0
Dept of MCA printf("a /= b: %d\n", a /= b); a &= b: 0
printf("a %%= b: %d\n", a %= b); a |= b: 5
printf("a &= b: %d\n", a &= b); a ^= b: 0
a >>= b: 0
printf("a |= b: %d\n", a |= b); a <<= b: 0
printf("a ^= b: %d\n", a ^= b);
printf("a >>= b: %d\n", a >>= b);
printf("a <<= b: %d\n", a <<= b);
return 0;
}
SPECIAL OPERATORS
C supports some special operators such as
1. Comma operator
2. Size of operator
3. Pointer operators(& and *) and
4. Member selection operators(. and ->)
Dept of MCA
[Link] Comma Operator
Comma operator is used to link the expression together and
entire
expression is evaluated from left to right.
Eg: value = (x = 10, y = 5, x + y);
Dept of MCA This statement first assigns the value 10 to x, then assigns 5
to y, and
finally assigns 15(i.e, 10+5) to value.
[Link] Size of Operator
The size of is a compiler time operator and, which gives the
bytes
occupied by the operand in memory.
Eg:
Dept of MCA m = sizeof(sum);
n = sizeof(long int)
k = sizeof(235L)
Operator Precedence
When a calculation contains more than one operator, C
follows order of operations rules to decide which part to
calculate first.
Operator precedence and associativity are rules that decide
which operator is applied first and in which direction
operators of the same precedence are evaluated.
Dept of MCA

2 + 3 * 4; //
#include <stdio.h>
int main()
{
int a = 6, b = 3, c = 4;
int res;
// Precedence and associativity applied here
Dept of MCA
res = a + b * c / 2;
printf("%d", res);
return 0;
}
Operator Precedence
• Operator precedence decides which operation is performed
first in an expression with multiple operators.
• In the expression 10 + 20 * 30, the * (multiplication)
operator has higher precedence than + (addition).
• Therefore, multiplication is evaluated first, followed by
Dept of MCA addition to get the final result.
Operator Associativity
• Operator associativity decides the order of evaluation
when two operators of the same precedence appear in an
expression.
• Associativity can be left-to-right or right-to-left depending
on the operator.
• In the expression 100 / 5 % 2, both / (division) and %
Dept of MCA (modulus) have the same precedence.
• Since they have left-to-right associativity, division is
performed first, followed by modulus to get the final
result.
Dept of MCA
#include <stdio.h>
int main()
{
// Verifying the result of the same expression
printf("%d", 100 / 5 % 2);
Dept of MCA return 0;
}
Example of Operator Precedence and Associativity
• Operator precedence and associativity work together to
determine the order of evaluation in expressions.
• In exp = 100 + 200 / 10 - 3 * 10, division (/) and
multiplication (*) are evaluated before addition (+) and
subtraction (-).
• Due to left-to-right associativity, division is done first, then
Dept of MCA multiplication, followed by addition and subtraction to get
the final result.
Dept of MCA
#include <stdio.h>
int main()
{
// getting the result of the same expression as the example
int exp = 100 + 200 / 10 - 3 * 10;
Dept of MCA printf("%d", exp);

return 0;
}
Prece
Operator Associativity
dence Description

() Parentheses (function call)


Array Subscript (Square
[]
Brackets)
Dept of MCA 1 Left-to-Right
. Dot Operator
-> Structure Pointer Operator
++ , -- Postfix increment, decrement
Prefix increment,
++ / --
decrement
+/- Unary plus, minus
Logical NOT, Bitwise
!,~
complement
Right-to-Left
(type) Cast Operator
Dept of MCA
* Dereference Operator
& Addressof Operator
Determine size in
sizeof
bytes
3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

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

Relational less than, less than or


Dept of MCA < , <=
equal to
6 Left-to-Right
Relational greater than, greater
> , >=
than or equal to

Relational is equal to, is not equal


7 == , != Left-to-Right
to
8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

Dept of MCA 11 && Logical AND Left-to-Right

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left


= Assignment
+= , -= Addition, subtraction assignment
*= , /= Multiplication, division assignment

14 %= , &= Modulus, bitwise AND assignment Right-to-Left


Dept of MCA Bitwise exclusive, inclusive OR
^= , |=
assignment
Bitwise shift left, right assignment
<<=, >>=

15 , comma (expression separator) Left-to-Right


Dept of MCA
Unit1: Introduction to programming paradigms Applications of C
Language - Structure of C program

Unit2: C programming: Data Types - Constants Enumeration Constants -


Keywords
Dept of MCA

Unit3: Operators: Precedence and Associativity - Expressions -


Input/Output statements, Assignment statements Decision making
statements - Switch statement - Looping statements Preprocessor
directives - Compilation process
Unit3: Operators
Precedence and Associativity
Expressions
Input/output statements
Assignment statements
Decision making statements
Dept of MCA
Switch statement
Looping statements
Pre-processor directives
Compilation process
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.
Example :
a+b
Dept of MCA
c
s-1/7*f . . etc
Types of Expressions
Constant expressions: Constant Expressions consists of only
constant values. A constant value is one that doesn't change.
Examples:
5,
10 + 5 / 6.0,
Dept of MCA ‘x’
Integral expressions: Integral Expressions are those which
produce integer results after implementing all the automatic
and explicit type conversions.
x, x * y, x + int( 5.0)
where x and y are the integers.
Floating expressions: Float Expressions are which produce
floating point results after implementing all the automatic
and explicit type conversions.
Examples:where x and y are floating point variables.
x + y, 10.75
Relational expressions: Relational Expressions yield results of
Dept of MCA type bool which takes a value true or false.
When arithmetic expressions are used on either side of a
relational operator, they will be evaluated first and then the
results compared. Relational expressions are also known as
Boolean expressions.
Examples:
x <= y, x + y > 2
Logical expressions: Logical Expressions combine two or
more relational expressions and produces bool type results.
Examples:
x > y && x == 10, x == 10 || y == 5
Pointer expressions: Pointer Expressions produce address
Dept of MCA values.
Examples : where x is a variable and ptr is a pointer.
&x, ptr, ptr++
Bitwise expressions: Bitwise Expressions are used to
manipulate data at bit level. They are basically used for
testing or shifting bits.
Examples:
x << 3 shifts three bit position to left
Dept of MCA y >> 1
shifts one bit position to right.
Input/output statements
Basic input and output statements :
Input statements : scanf()
Output statements : printf()
These functions are part of the standard input/output
library <stdio.h>.
Dept of MCA scanf() takes user inputs (typed using keyboard)
printf() displays output on the console or screen.
Basic Output in C
printf() function is used to print formatted output to the
standard output stdout (which is generally the console
screen).
Syntax of printf()
• The printf() function is defined inside <stdio.h> header file.
Dept of MCA printf("format_string", args...);
Parameter:
• formatted_string: It is a string that specifies the data to be
printed. It may also contain a format specifier as a
placeholder to print the value of any variable or value.
• args...: These are the variable/values corresponding to the
format specifier.
#include <stdio.h>
int main() {
printf("Hi! welcome");
return 0;
}
fputs()
Dept of MCA
The fputs() function is used to output strings to the files but we
can also use it to print strings to the console screen.
#include <stdio.h>
int main() {
fputs("This is my string", stdout);
return 0;
}
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);
Dept of MCA
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
// Reads an integer
Dept of MCA scanf("%d", &age);
// Prints the age
printf("Age is: %d\n", age);
return 0;
}
Where %d is used to read an integer; and &age provides the
address of the variable where the input will be stored.
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.
#include <stdio.h>
#include <string.h>
int main() {
Dept of MCA // String variable
char name[20];
printf("Enter your name: \n");
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
return 0;
}
READING A CHARACTER
Reading a single character can be done by using the function
getchar.
The getchar takes the following form:
variable_name = getchar();
Eg:
Dept of MCA char name;
name=getchar();
Program
/*Reading a character from terminal*/ #include<stdio.h>
main()
{
char ans;
printf(“Would you like to know my name? \n”);
Dept of MCA
printf(“Type Y for yes and N for no”);
OUTPUT
ans=getchar(); Would you like to know my
name?
if(ans ==’Y’ || ans = =’y’) Type Y for yes and N for no:Y
printf(“\n\n My name is India \n”); My name is India
Would you like to know my
else name?
printf(“\n\n You are good for nothing \n”); Type Y for yes and N for no:n
You are good for nothing
}
WRITING A CHARACTER
The function putchar is for writing characters one at a time to
the terminal.
It takes the form as shown below:
putchar (variable_name);

Dept of MCA Eg: answer=’y’;


putchar(answer);
will display the character y on the screen. The statement
putchar(‘\n’);
would cause the cursor on the screen to move to the
beginning of the next line.
WRITING A CHARACTER
The function putchar is for writing characters one at a time to
the terminal.
It takes the form as shown below:
putchar (variable_name);

Dept of MCA Eg: answer=’y’;


putchar(answer);
will display the character y on the screen. The statement
putchar(‘\n’);
would cause the cursor on the screen to move to the
beginning of the next line.
Example :
#include<stdio.h>
#include<ctype.h>
main() OUTPUT
{ Enter An alphabet a A
Enter An alphabet Q q
char alphabet; Enter An alphabet z Z
printf(“Enter an alphabet”);
Dept of MCA putchar(‘\n’);
alphabet = getchar();
if(islower(alphabet))
putchar(toupper(alphabet));
else
putchar(tolower(alphabet));
}
Assignment Statement (=) in C Language
The process of assigning the value to a variable using the
assignment(=) operator is known as an assignment statement
in C.
Assignment Statement in C language is a statement that
assigns or set a value to a variable during program execution.
Assignment statements in programming allows the
Dept of MCA programmer to change or set the value stored in variable
using Assignment(=) Operator.
Assignment(=) Operator Assigns The value or value in a
variable on right hand side to the variable on the left hand
side.
The data type of the variable on right hand side should match
to the data type of variable or constant or expression on right
hand side.
Syntax :
Data Type Variable_name = variable/ constant /expression;
[Link] Assignment or Basic Form var =val;
[Link] Assignment
Syntax:
expression1+= expression2;
Dept of MCA 3. Conditional Assignment .
var1=Condition ? exp1 : exp2;
[Link] Assignment .
Syntax:
var++;
++var;;
var--
--var
Dept of MCA
Unit1: Introduction to programming paradigms Applications of C
Language - Structure of C program

Unit2: C programming: Data Types - Constants Enumeration Constants -


Keywords
Dept of MCA

Unit3: Operators: Precedence and Associativity - Expressions -


Input/Output statements, Assignment statements Decision making
statements - Switch statement - Looping statements Preprocessor
directives - Compilation process
Unit3: Operators
Precedence and Associativity
Expressions
Input/output statements
Assignment statements
Decision making statements
Dept of MCA
Switch statement
Looping statements
Pre-processor directives
Compilation process
Decision making statements
Decision-making statements in C allow programs to control
the flow of execution based on conditions. These statements
evaluate expressions and execute specific blocks of code
depending on whether the condition is true or false.
The main types of decision-making statements in C are:
1. if Statement
Dept of MCA
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement
if Statement
• 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).
Dept of MCA
The syntax of the ‘if’ statement is:
if(test condition)
{
Block Statement-1
}
Statement-2
Example :
if(marks < 40)
{
printf(“Not eligible to promote\n”);
}
Dept of MCA printf(“Total Marks = %d\n”,marks);

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.
if-else statement
The if else in C is an extension of the if statement which not only
allows the program to execute one block of code if a condition is
true, but also a different block if the condition is false.
if the condition is true, then the code inside the if block is
executed, otherwise the code inside the else block is executed.
if(test condition)
{
Dept of MCA Block Statement-1
}
Else
{
Block Statement-2
}
Statement-3
Example:
if(marks < 40)
{
printf(“You are fail\n”);
}
Else
Dept of MCA
{
printf(“You are pass\n”);
}
printf(“Total Marks = %d\n”,marks);
Nested if-else statement
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.
Syntax :
if(test condition-1)
{
if(test condition-2)
{
Block Statement-1
Dept of MCA }
else {
Block Statement-2
}
}
else {
Block Statement-3
}
Statement-4
If the condition is true then computer check another ‘test
condition 2’.
If ‘test condition-2’ is true then it will execute ‘Block
Statement-1’ otherwise execute the ‘Block Statement-2’.
If ‘test-condition1’ is false then it will execute ‘Block
Statement-3’.
Dept of MCA
After completing the nested ‘if...else’ statement execution
computer will execute ‘Statemetn-4’.
Example :
if(no1>=no2)
{
if(no1>=no3)
{
printf(“Number1 is Maximum\n”);
Dept of MCA
}
else
{
printf(“Number3 is Maximum\n”);
}
}
else
{
if(no2>=no3)
{
printf(“Number2 is Maximum\n”);
Dept of MCA
}
else
{
printf(“Number3 is Maximum\n”);
}
}
if-else-if statement
• It is used to test a series of conditions sequentially,
executing the code for the first true condition. A condition
is checked only if all previous ones are false.
• Once a condition is true, its code block executes, and the
ladder ends.

Dept of MCA
Dept of MCA
If the condition is true then computer will execute ‘Block
Statement-1’ otherwise it will check the ‘test condition-2’.
If the condition is true then computer will execute ‘Block
Statement-2’ otherwise it will check the ‘test condition-3’.
If condition is true then it will execute ‘Block Statement-3’
otherwise it will execute ‘Block Statement-4’.
Dept of MCA
The example of this statement is:
if(percentage >=70)
{ printf(“Distinction\n”); }
elseif(percentage >= 60)
{ printf(“First Class\n”); }
elseif(percentage >= 50)
Dept of MCA
{ printf(“Second Class\n”); }
elseif(percentage >=40)
{ printf(“Pass Class\n”); }
else
{ printf(“Fail\n”); }
switch Statement
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.
Dept of MCA
When there is multiple conditions in the ‘if’ statement it is
become difficult to read and understand program. In this
condition we can use ‘switch’ statement, which allows
checking the value of variable against the multiple case
value.
Here if the value of variable= = v1 then ‘Block Statement-1’
Dept of MCA will be executed. If variable= = v2 then ‘Block Statement-2’
will be executed.
If at last no match found for the variable then default
statement is executed.
Here we have to put the ‘break’ statement to complete the
execution of ‘switch’ .
Dept of MCA
switch(month)
{
case 1 :printf(“January”); break;
case 2 :printf(“February”); break;
case 5 :printf(“May”); break;
Dept of MCA
case 10 : printf(“October”); break;
default :printf(“You have entered wrong value”);
break;
Conditional Operator OR ?: Operator
‘C’ provides the facility of the operator to check the
condition by using the conditional operator having three
operands.
The format of the condition:
(Condition)? Statement1 : Statement2
Dept of MCA If condition is true then statement1 will be executed
otherwise statement2 will be executed.
Here you can also represent the condition for assignment
operation:
variable = (Condition)? Value1 : Value2
Consider the following example to understand the
conditional operator:
commission = (sales > 50000) ? 2000 : 0;

If the sales is greater than 50000 the commission is 2000


Dept of MCA otherwise commission is 0.

The advantage of the conditional operator is that you can


represent the condition in shorter form.
Dept of MCA
Unit1: Introduction to programming paradigms Applications of C
Language - Structure of C program

Unit2: C programming: Data Types - Constants Enumeration Constants -


Keywords
Dept of MCA

Unit3: Operators: Precedence and Associativity - Expressions -


Input/Output statements, Assignment statements Decision making
statements - Switch statement - Looping statements Preprocessor
directives - Compilation process
Unit3: Operators
Precedence and Associativity
Expressions
Input/output statements
Assignment statements
Decision making statements
Dept of MCA
Switch statement
Looping statements
Pre-processor directives
Compilation process
Looping statements
Loops in C programming are used to repeat a block of code
until the specified condition is met.
It allows programmers to execute a statement or group of
statements multiple times without writing the code again
and again.
There are mainly two kinds of loops:
Dept of MCA
1) Entry-controlled loop:
In entry-controlled loop we first check the condition and
then the body of loop is executed. If at first time condition is
false then the body of loop not executed any time. ‘While’
loop and ‘for’ loop is example of entry controlled loop.
2) Exit-controlled loop:
In exit-controlled loop we first execute the body of the loop
and then check the condition and if condition is true then
next again executed the body of the loop otherwise not.
In exit-controlled loop it is sure the body of loop is executed
once. ‘do...while’ loop is example of the exit-controlled loop.
Dept of MCA
Types of Loops in C
There are 3 looping statements in C:
• for Loop
• while Loop
• do-while Loop
for Loop
the 'for' loop is a control flow statement that is used to
repeatedly execute a block of code as many times as
instructed.
It uses a variable (loop variable) whose value is used to
decide the number of repetitions.
It is commonly used to iterate over a sequence such as an
Dept of MCA
array or list.
Syntax :
for(initialization; test expression; inc/dec )
{
// Body of the loop
}
where,
• Initialization: This step is executed first, and it is typically
used to initialize a loop control variable.
• Condition: This conditional expression is evaluated before
each iteration. and if the condition is true, the loop body
executes. if it's false, the loop terminates.
Dept of MCA
• Inc/dec: This step is used to update the loop control
variable and is executed after each iteration.
• body: The body of the loop are the set of statements that
are executed when the condition is true
Dept of MCA
#include
int main()
{
int n, i, sum=0;
printf("Enter the value of n.\n");
scanf("%d",&n);
Dept of MCA
for(i=1;i<=n;++i) //for loop terminates if i>n
{
Enter the value of n.
sum+=i; 2
Sum=3
}
printf("Sum=%d",sum);
return 0;
}
While loop
In the beginning of while loop, test expression is checked.
If it is true, codes inside the body of while loop, i.e, code/s
inside parentheses are executed and again the test
expression is checked and process continues until the test
expression becomes false.
Syntax:
Dept of MCA
while (test expression)
{
statements to be executed.
}
#include <stdio.h>
int main()
{
int number,factorial;
printf("Enter a number.\n");
scanf("%d",&number); Enter a number.
5
factorial=1;
Dept of MCA Factorial=120
while (number>0)
{
factorial=factorial*number;
--number;
}
printf("Factorial=%d",factorial);
return 0;
}
do...while loop
In C, do...while loop is very similar to while loop. Only
difference between these two loops is that, in while loops,
test expression is checked at first but, in do...while loop code
is executed at first then the condition is checked.
So, the code are executed at least once in do...while loops.
Syntax :
Dept of MCA do {
statements;
}while (test expression)
At first codes inside body of do is executed. Then, the test
expression is checked.
If it is true, code/s inside body of do are executed again and
the process continues until test expression becomes
false(zero).
Dept of MCA
#include <stdio.h>
int main() Enter a number
{ 2
Enter a number
int sum=0,num; 2
Enter a number
do { 2
Enter a number
Dept of MCA printf(“Enter a number\n”); 0
scanf(“%d”,&num); sum=6

sum+=num;
} while(num!=0);
printf(“sum=%d”,sum);
return 0;
}
Dept of MCA
Unit1: Introduction to programming paradigms Applications of C
Language - Structure of C program

Unit2: C programming: Data Types - Constants Enumeration Constants -


Keywords
Dept of MCA

Unit3: Operators: Precedence and Associativity - Expressions -


Input/Output statements, Assignment statements Decision making
statements - Switch statement - Looping statements Preprocessor
directives - Compilation process
Unit3: Operators
Precedence and Associativity
Expressions
Input/output statements
Assignment statements
Decision making statements
Dept of MCA
Switch statement
Looping statements
Pre-processor directives
Compilation process
Pre-processor directives
Preprocessors are programs that process the source code
before the actual compilation begins. They are not part of
the compilation process but operate separately, allowing
programmers to modify the code before compilation.
• It is the first step that the C source code goes through when
being converted into an executable file.
Dept of MCA
• Main types of Preprocessor Directives are Macros, File
Inclusion, Conditional Compilation and Other directives like
#undef, #pragma, etc.
• Mainly these directives are used to replace a given section
of C code with another C code.
• For example, if we write "#define PI 3.14", then PI is
replaced with 3.14 by the preprocessor.
Dept of MCA
Types of C Preprocessors
All the above preprocessors can be classified into 4 types :
Macros
• Macros are used to define constants or create functions
that are substituted by the preprocessor before the code is
compiled.
The two preprocessors #define and #undef are used to
Dept of MCA
create and remove macros in C.
#define token value
#undef token
where after preprocessing, the token will be expanded to
its value in the program.
Example:
#include <stdio.h>
// Macro Definition
#define LIMIT 5
int main(){
for (int i = 0; i < LIMIT; i++) {
Dept of MCA
printf("%d \n", i);
}
return 0;
}

o/p: 0 1 2 3 4
File Inclusion
File inclusion allows you to include external files (header
files, libraries, etc.) into the current program. This is typically
done using the #include directive, which can include both
system and user-defined files.
Syntax

There are two ways to include header files.


Dept of MCA #include <file_name>
#include "filename"

The '<' and '>' brackets tell the compiler to look for the file in
the standard directory while double quotes ( " " ) tell the
compiler to search for the header file in the source file's
directory.
// Includes the standard I/O library
#include <stdio.h>
int main() {
printf("Hello World");
return 0;
Dept of MCA
}
Macros With Arguments
We can also pass arguments to macros. These macros work
similarly to functions.
For example,
#define foo(a, b) a + b

Dept of MCA #define func(r) r * r


#include <stdio.h>
// macro with parameter
#define AREA(l, b) (l * b)
int main(){
int a = 10, b = 5;
// Finding area using above macro
Dept of MCA
printf("%d", AREA(a, b));
return 0;
}
Area of rectangle is: 50
Compilation process
Step 1: Creating a C Source File
vi filename.c
Step 2: Compiling using GCC compiler
gcc filename.c –o filename
Step 3: Executing the program
Dept of MCA
After compilation executable is generated and we run the
generated executable using the below command.
./filename // for linux
filename // for windows
A compiler converts a C program into an executable. There
are four phases for a C program to become an executable:
• Pre-processing
• Compilation
• Assembly
Dept of MCA • Linking
gcc -Wall -save-temps filename.c –o filename
1. Pre-processing
This is the first phase through which source code is passed.
This phase includes:
• Removal of Comments
• Expansion of Macros
Dept of MCA • Expansion of the included files.
• Conditional compilation
2. Compiling
• The next step is to compile filename.i and produce an;
intermediate compiled output file filename.s. This file is in
assembly-level instructions.
3. Assembling
Dept of MCA • In this phase the filename.s is taken as input and turned
into filename.o by the assembler. This file contains
machine-level instructions. At this phase, only existing code
is converted into machine language, and the function calls
like printf() are not resolved.
• Linking
• This is the final phase in which all the linking of function
calls with their definitions is done
Linking can be of two types:
• Static Linking: All the code is copied to the single file and
then executable file is created.
• Dynamic Linking: Only the names of the shared libraries is
added to the code and then it is referred during the
execution.
Dept of MCA

You might also like