You are on page 1of 102

Module 1 continuation ………..

Art of
Programming
Methodology

ATK
Introduction to the C Language

C is a structured oriented programming


language, used in general-purpose programming,
developed by Dennis Ritchie at AT&T Bell
Labs, the USA between 1969 and 1973.

ATK
Some Facts About C Programming Language

 In 1988, the American National Standards Institute (ANSI) had


formalized the C language.
 C was invented to write UNIX operating system.
 C is a successor of 'Basic Combined Programming Language' (BCPL)
called B language.
 Linux OS, PHP, and MySQL are written in C.

ATK
Uses of C Programming Language

In the beginning, C was used for developing system applications, e.g. :

 Database Systems
 Language Interpreters
 Compilers and Assemblers
 Operating Systems
 Network Drivers
 Word Processors

ATK
C Has Become Very Popular for Various Reasons

o One of the early programming languages.


o Still, the best programming language to learn quickly.
o C language is reliable, simple, and easy to use.
o C language is a structured language.
o Modern programming concepts are based on C.

ATK
Features of C Programming Language

• C is a robust language with a rich set of built-in functions and


operators.
• Programs written in C are efficient and fast.
• C is a collection of C library functions; we can also create our
function and add it to the C library.

ATK
Advantages of C

 C is the building block for many other programming languages.


 Several standard functions are there (like in-built) that can be used to
develop programs.
 C programs are collections of C library functions, and it's also easy to add
functions to the C library.
 The modular structure makes code debugging, maintenance, and testing
easier.

ATK
Disadvantages of C

• C does not provide Object Oriented Programming (OOP) concepts.

• There are no concepts of Namespace in C.

• C does not provide binding or wrapping up of data in a single unit.

• C does not provide Constructor and Destructor.

ATK
The limitations of C programming languages are as follows:

o Difficult to debug.
o C allows a lot of freedom in writing code, and that is why you can put an empty line or
white space anywhere in the program. And because there is no fixed place to start or
end the line, so it is difficult to read and understand the program.
o C compilers can only identify errors and are incapable of handling exceptions (run-
time errors).
o C provides no data protection.
o It also doesn't feature reusability of source code extensively.
o It does not provide strict data type checking
ATK
(for example an integer value can be passed for floating data type).
Structure of C Program

Documentation Section 1

Pre-processor/Link section 2

Definition section 3

Global declaration section 4

Main function 5

ATK Subprogram 6
1. Documentation Section

The documentation section is a part of the program, where the programmer writes everything about the program.
Typically, the programmer writes the name of the program, about the author of the program and other details such as
the date, and the program description.
In short, it gives the reader an overview of the program.

/* File Name: program.c


* Author: Programmer Name
* date: 09/08/2019
* description: a program to explain basic structure of c programming
*user enters the radius
**/
ATK
We usually use multiline Comments for documentation purposes. Comments are ignored by the compiler.
2. Link Section
The link section of the program is used to declare all the header files that will be used in the program
the link section provides instructions to the compiler to link functions from the system library.

#include<stdio.h>
#include<conio.h>
We use #include to declare header files in the link section.

ATK
3. Definition Section
This section of the program is used to declare the symbolic constant that will be used in the program. A
symbolic constant is a constant value given to a name that can't be changed in the program.

#define NAME value


#define NAME (expression)
We use #define to declare the symbolic constant in the Definition Section.

NOTE: Do not put a semicolon (;) at the end of the #define statements.

ATK
4.Global Declaration section

The Global Declaration section is a part of the program, where the programmer declares
variables that are used in more than one function.

Such variables are called global variables. User-defined functions are also declared in
this part of the code.

ATK
5.Main function section

• The main function is the section from where the actual program begins.
• The main function begins with opening curly braces and ends with closing curly braces.
• The program should have one main function.

• The main function consists of two parts.


1. A declaration part
2. An execution part.
• Declaration part where all variables are declared that are used in the executable part.
• The executable part contains at least one statement. All statements in the declaration and executable parts end
with a semicolon.

ATK
6.Sub program:

The subprogram section is a part of the program, where the programmer


declares all user-defined functions to perform a specific task. User-defined
functions are usually posted soon after the main () function.

ATK
ATK
ATK
FIGURE The Greeting Program
ATK
ATK
FIGURE Structure of a C Program
ATK
ATK
How to Write and Run a C Program in Linux

• Linux is an open-source and free operating system.

• We use Linux command-line tool, the Terminal, in order to compile a simple C program. To
open the Terminal, you can use the Ctrl+Alt+T shortcut.

ATK
1.Write a simple C program

After installing the essential packages, let us write a simple C program.


Open Ubuntu’s graphical Text Editor and write or copy the following sample program into it:

Then save the file with .c extension. In this example, it is saved as sampleProgram.c
ATK
ATK
2.Compile the C program with gcc Compiler

In your Terminal, enter the following command in order to make an executable version of
the program you have written:
gcc filename.c

ATK
How to Write and Run a C Program in Windows

ATK
Step 1: Creating a Source Code

Source code is a file with C programming instructions in a high-level language. To create source code, we use any text editor
to write the program instructions. The instructions written in the source code must follow the C programming language
rules. The following steps are used to create a source code file in Windows OS…

•Click on the Start button


•Select Run
•Type cmd and press Enter
•Type cd c:\TC\bin in the command prompt and press Enter
•Type TC press Enter
•Click on File -> New in C Editor window
•Type the program
•Save it as FileName.c (Use shortcut key F2 to save)
ATK
Step 2: Compile Source Code (Alt + F9)

The compilation is the process of converting high-level language instructions into low-level language
instructions. We use the shortcut key Alt + F9 to compile a C program in Turbo C.

The compilation is the process of converting high-level language instructions into low-level
language instructions.

ATK
• Whenever we press Alt + F9, the source file is going to be submitted to the Compiler.

• On receiving a source file, the compiler first checks for the Errors. If there are any
Errors then compiler returns List of Errors, if there are no errors then the source code is
converted into object code and stores it as a file with .obj extension.

• Then the object code is given to the Linker. The Linker combines both the object
code and specified header file code and generates an Executable file with
a .exe extension

ATK
ATK
ATK
The file which contains c program instructions in a high-level language is said
to be source code. Every c program source file is saved with .c extension, for
example, Sample.c.

Whenever we press Alt + F9 the source file is submitted to the compiler.


Compiler checks for the errors, if there are any errors, it returns a list of errors,
otherwise generates object code in a file with name Sample.obj and submit it to
the linker. The linker combines the code from specified header file into an
object file and generates executable file as Sample.exe. With this compilation
process completes.

Now, we need to run the executable file (Sample.exe). To run a program we


press Ctrl + F9. When we press Ctrl + F9 the executable file is submitted to the
CPU. Then CPU performs the task according to the instructions written in that
program and place the result into UserScreen.
ATK
Comments in C
• Comments in C language are used to provide information about lines of code. It is
widely used for documenting code. There are 2 types of comments in the C language.
1. Single Line Comments
Single line comments are represented by double slash \\. Let's see an example of
a single line comment in C.
2. Multi-Line Comments
Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy
many lines of code, but it can't be nested

ATK
printf() and scanf() in C

The printf() and scanf() functions are used for input and output in C language. Both functions are inbuilt library
functions, defined in stdio.h (header file).

printf() function
The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

printf("format string",argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.


ATK
scanf() function
The scanf() function is used for input. It reads the input data from the
console.

scanf("format string",argument_list);

ATK
#include<stdio.h>
int main(){
int number;
printf("enter a number:");
scanf("%d",&number);
printf("cube of number is:%d ",number*number*number);
return 0;
}

ATK
#include<stdio.h>
int main(){
int x=0,y=0,result=0;
printf("enter first number:");
scanf("%d",&x);
printf("enter second number:");
scanf("%d",&y);
result=x+y;
printf("sum of 2 numbers:%d ",result);
return 0;
}
ATK
Variables in C
• A variable is a name of the memory location. It is used to store data. Its value can be
changed, and it can be reused many times.
• It is a way to represent memory location through symbol so that it can be easily identified.
• Let's see the syntax to declare a variable:
type variable_list;

int a=10,b=20;//declaring 2 variable of integer


type
float f=20.8;
char c='A';

ATK
Rules for defining variables
1. A variable can have alphabets, digits, and underscore.
2. A variable name can start with the alphabet, and underscore only. It can't
start with a digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or keyword, e.g. int, float,
etc.
Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable
• A variable that is declared inside the function or block is called a
local variable.
• It must be declared at the start of the block.

void function1(){
int x=10;//local variable
}
Global Variable
• A variable that is declared outside the function or block is
called a global variable. Any function can change the value of
the global variable. It is available to all the functions.
• It must be declared at the start of the block.

int value=20;//global variable


void function1(){
int x=10;//local variable
}
Static Variable
A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented
value in each function call, e.g. 11, 12, 13 and so on.
Automatic Variable
All variables in C that are declared inside the block, are automatic
variables by default. We can explicitly declare an automatic variable using
auto keyword.
void main(){
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
External Variable
We can share a variable in multiple C source files by using an external variable. To declare an external
variable, you need to use extern keyword.

myfile.h
extern int x=10;//external variable (also global)

program1.c
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}
Data Types in C
Signed Data Type:

• A signed data type can represent both positive and negative numbers.
• The most significant bit (MSB) is used as the sign bit, indicating whether
the number is positive or negative.
• For example, in a 4-bit signed integer, the range of representable values is
from -8 (-2^3) to 7 (2^3 - 1).

Unsigned Data Type:

• An unsigned data type can represent only non-negative (zero and positive)
numbers.
• All bits are used to represent magnitude, and there is no sign bit.
• For example, in a 4-bit unsigned integer, the range of representable values
is from 0 to 15 (2^4 - 1).
Types Data Types
Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Enumeration Data Type enum
Void Data Type void
Basic Data Types
• The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.
• The memory size of the basic data types may change according to 32 or 64-bit operating
system.
Integer Types:

• int: Represents signed integers (whole numbers) with at least 16 bits.


• short: Represents signed integers with at least 16 bits (usually 16 bits).
• long: Represents signed integers with at least 32 bits (usually 32 bits).
• long long: Represents signed integers with at least 64 bits (usually 64 bits).
Floating-Point Types:
float: Represents single-precision floating-point numbers.
double: Represents double-precision floating-point numbers.
long double: Represents extended-precision floating-point
numbers.

Void Type:
void: Represents the absence of type. It is often used to indicate
that a function does not return any value.
Derived Types:
Arrays: A collection of elements of the same data type.
Pointers: Variables that store memory addresses of other variables.
Structures: User-defined data types that can store multiple variables of different
types under one name.
Unions: Similar to structures but can only store one value at a time, sharing the
same memory for all its members.
Enumerations: User-defined data types that consist of named integer constants.
#include <stdio.h>

int main() {
int num1 = 1000;
short num2 = 200;

printf("num1 (int): %d\n", num1);


printf("num2 (short): %hd\n", num2);

return 0;
} Output

num1 (int): 1000


num2 (short): 200
#include <stdio.h>

int main() {
int num1 = 2147483647;
long num2 = 2147483648L; // Note the "L" suffix for a long constant.

printf("num1 (int): %d\n", num1);


printf("num2 (long): %ld\n", num2);

return 0;
}

Output:
num1 (int): 2147483647
num2 (long): 2147483648
Keywords in C
• A keyword is a reserved word. You cannot use it as a variable name,
constant name, etc. There are only 32 reserved words (keywords) in the C
language.
• A list of 32 keywords in the c language is given below:

auto break case char const continue default do


double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
Identifiers
• An identifier is a collection of alphanumeric characters that begins either
with an alphabetical character or an underscore, which are used to represent
various programming elements such as variables, functions, arrays,
structures, unions, labels, etc.
• There are 52 alphabetical characters (uppercase and lowercase), underscore
character, and ten numerical digits (0-9) that represent the identifiers. There
is a total of 63 alphanumerical characters that represent the identifiers.
Rules for constructing C identifiers

1. The first character of an identifier should be either an alphabet or an


underscore, and then it can be followed by any of the character, digit,
or underscore.
2. It should not begin with any numerical digit.
3. In identifiers, both uppercase and lowercase letters are distinct.
Therefore, we can say that identifiers are case sensitive.
4. Commas or blank spaces cannot be specified within an identifier.
5. Keywords cannot be represented as an identifier.
6. The length of the identifiers should not be more than 31 characters.
7. Identifiers should be written in such a way that it is meaningful, short,
and easy to read.
Differences between Keyword and Identifier

Keyword Identifier
Keyword is a pre-defined word. The identifier is a user-defined word
It must be written in a lowercase letter. It can be written in both lowercase and
uppercase letters.
Its meaning is pre-defined in the c Its meaning is not defined in the c
compiler. compiler.
It is a combination of alphabetical It is a combination of alphanumeric
characters. characters.
It does not contain the underscore It can contain the underscore character.
character.
C Operators

ATK
ATK
The precedence and associativity of C operators
category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right


Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= | Right to left
=
Comma
ATK , Left to right
Arithmetic Operators:

1) + : Addition
2) - : Subtraction
3) * : Multiplication
4) / : Division (integer division truncates the decimal part)
5) % : Modulus (remainder after integer division)

ATK
#include <stdio.h>
int main() {
int a = 10, b = 3;
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;

printf("Sum: %d\n", sum);


printf("Difference: %d\n", difference);
printf("Product: %d\n", product);
printf("Quotient: %d\n", quotient);
printf("Remainder: %d\n", remainder);
return 0;
}
ATK
Relational Operators:

1) == : Equal to
2) != : Not equal to
3) > : Greater than
4) < : Less than
5) >= : Greater than or equal to
6) <= : Less than or equal to
• Relational operators in C are used to compare two values and
determine the relationship between them.
• These operators return a Boolean result (1 for true or 0 for false)
based on whether the specified condition is satisfied or not.
• Relational operators are commonly used in conditional
statements, loops, and decision-making processes.
if (num1 == num2) {
printf("%d is equal to %d\n", num1,
#include <stdio.h> num2);
} else {
int main() { printf("%d is not equal to %d\n", num1,
int num1, num2; num2);

// Prompt the user to enter two numbers if (num1 > num2) {


printf("Enter the first number: "); printf("%d is greater than %d\n", num1,
scanf("%d", &num1); num2);
} else {
printf("Enter the second number: "); printf("%d is less than %d\n", num1,
scanf("%d", &num2); num2);
}
// Check and display the comparison results }
return 0;
}
Logical Operators:

1. && : Logical AND (returns true if both operands are true)


2. || : Logical OR (returns true if at least one operand is
true)
3. ! : Logical NOT (inverts the truth value of the
operand)

ATK
• Logical operators in C are used to perform logical operations on Boolean
expressions or values (true or false).
• These operators are used in conditional statements to combine multiple
conditions and make decisions based on the truth values of those
conditions.
• The logical AND operator && takes two operands (Boolean expressions)
and returns 1 (true) if both operands are true. Otherwise, it returns 0
(false).
• The logical OR operator || takes two operands (Boolean expressions)
and returns 1 (true) if at least one of the operands is true. If both
operands are false, it returns 0 (false).
• The logical NOT operator ! takes a single operand (Boolean
expression) and returns 1 (true) if the operand is false. If the operand
is true, it returns 0 (false).
• It basically inverts the truth value of the operand.
#include <stdio.h>

int main() {
int num1 = 5, num2 = 10;

if (num1 > 0 && num2 < 20) {


printf("Both conditions are true.\n");
} else if (num1 > 0 || num2 < 0) {
printf("At least one condition is true.\n");
} else {
printf("Neither condition is true.\n");
}
return 0;
}
Bitwise Operators:

1) & : Bitwise AND


2) | : Bitwise OR
3) ^ : Bitwise XOR (exclusive OR)
4) ~ : Bitwise NOT (ones' complement)
5) << : Left shift
6) >> : Right shift
• Bitwise operators in C are used to perform operations at the binary level
on individual bits of integer data types. These operators treat operands as
sequences of bits and manipulate them bitwise
Bitwise AND (&):

• The bitwise AND operator & performs a bitwise AND operation between the
corresponding bits of two operands.
• Each bit of the result is set to 1 only if the corresponding bits of both
operands are 1; otherwise, it is set to 0.
• For example: int result = 12 & 6; will assign 4 to the variable result since the
binary representation of 12 is 1100, and 6 is 0110. Performing bitwise AND
on these yields 0100, which is 4 in decimal.
Bitwise OR (|):

• The bitwise OR operator | performs a bitwise OR operation between the


corresponding bits of two operands.
• Each bit of the result is set to 1 if at least one of the corresponding bits of
the operands is 1; otherwise, it is set to 0.
• For example: int result = 12 | 6; will assign 14 to the variable result since
the binary representation of 12 is 1100, and 6 is 0110. Performing
bitwise OR on these yields 1110, which is 14 in decimal.
Bitwise XOR (exclusive OR) (^):
• The bitwise XOR operator ^ performs a bitwise exclusive OR operation
between the corresponding bits of two operands.
• Each bit of the result is set to 1 only if the corresponding bits of the
operands are different (one bit is 1 and the other is 0); otherwise, it is set
to 0.
• For example: int result = 12 ^ 6; will assign 10 to the variable result since
the binary representation of 12 is 1100, and 6 is 0110. Performing bitwise
XOR on these yields 1010, which is 10 in decimal.
Bitwise NOT (ones' complement) (~):

• The bitwise NOT operator ~ is a unary operator that performs a bitwise


complement operation on a single operand.
• It flips each bit of the operand, i.e., changes all 1s to 0s and all 0s to 1s.
• For example: int result = ~12; will assign -13 to the variable result. In
binary representation, 12 is 00001100, and the bitwise NOT operation
flips all the bits to 11110011, which represents -13 in two's complement
form.
Left Shift (<<):

• The left shift operator << shifts the bits of the left operand to the
left by the number of positions specified by the right operand.
• Zeroes are filled in on the right side.
• For example: int result = 5 << 2; will assign 20 to the variable
result. In binary representation, 5 is 00000101, and left shifting it
by 2 positions gives 00010100, which represents 20 in decimal.
Right Shift (>>):

• The right shift operator >> shifts the bits of the left operand to the right by
the number of positions specified by the right operand.
• For signed integers, the sign bit (most significant bit) is replicated on the
left side when shifting right.
• For unsigned integers, zeroes are filled in on the left side.
• For example: int result = 16 >> 2; will assign 4 to the variable result. In
binary representation, 16 is 00010000, and right shifting it by 2 positions
gives 00000100, which represents 4 in decimal.
Assignment Operators:
1) = : Simple assignment
2) += : Add and assign
3) -= : Subtract and assign
4) *= : Multiply and assign
5) /= : Divide and assign
6) %= : Modulus and assign
7) &= : Bitwise AND and assign
8) |= : Bitwise OR and assign
9) ^= : Bitwise XOR and assign
10)<<= : Left shift and assign
11)>>= : Right shift and assign
• Assignment operators in C are used to assign values to
variables and perform specific operations in a single
statement.
• They combine the assignment operation (=) with another
operation (e.g., addition, subtraction, etc.) and assign the
result back to the variable on the left side of the operator.
#include <stdio.h>

int main() {
int x = 5; // Initialize x with 5

// Add and Assign


x += 3; // Equivalent to x = x + 3
printf("Add and Assign: x = %d\n", x); // Output: x = 8

// Subtract and Assign


x -= 2; // Equivalent to x = x - 2
printf("Subtract and Assign: x = %d\n", x); // Output: x = 6

// Multiply and Assign


x *= 4; // Equivalent to x = x * 4
printf("Multiply and Assign: x = %d\n", x); // Output: x = 24

// Divide and Assign


x /= 3; // Equivalent to x = x / 3
printf("Divide and Assign: x = %d\n", x); // Output: x = 8

// Modulus and Assign


x %= 5; // Equivalent to x = x % 5
printf("Modulus and Assign: x = %d\n", x); // Output: x = 3
// Bitwise AND and Assign
x &= 1; // Equivalent to x = x & 1
printf("Bitwise AND and Assign: x = %d\n", x); // Output: x = 1

// Bitwise OR and Assign


x |= 4; // Equivalent to x = x | 4
printf("Bitwise OR and Assign: x = %d\n", x); // Output: x = 5

// Bitwise XOR and Assign


x ^= 2; // Equivalent to x = x ^ 2
printf("Bitwise XOR and Assign: x = %d\n", x); // Output: x = 7

// Left Shift and Assign


x <<= 1; // Equivalent to x = x << 1
printf("Left Shift and Assign: x = %d\n", x); // Output: x = 14

// Right Shift and Assign


x >>= 2; // Equivalent to x = x >> 2
printf("Right Shift and Assign: x = %d\n", x); // Output: x = 3

return 0;
ATK
}
Increment and Decrement Operators:

1) ++ : Increment
by 1
2) -- : Decrement
by 1
3) ++var and var++ : Pre-increment and post-
increment
4) --var and var-- : Pre-decrement and post-
decrement
Increment (++):

• The increment operator ++ is used to increase the value of a


variable by one.
• It can be used in two forms: prefix and postfix.
• The prefix form (++var) increments the value of the variable var
before its value is used in an expression.
• The postfix form (var++) increments the value of the variable var
after its value is used in an expression.
Decrement (--):

• The decrement operator -- is used to decrease the value of a variable


by one.
• Like the increment operator, it can also be used in both prefix and
postfix forms.
• The prefix form (--var) decrements the value of the variable var
before its value is used in an expression.
• The postfix form (var--) decrements the value of the variable var
after its value is used in an expression.
Conditional (Ternary) Operator:

condition ? expr1 : expr2 ;

If the condition is true, evaluate expr1, otherwise evaluate expr2.


#include <stdio.h>
int main() {
int num1, num2;

// Input two numbers


printf("Enter the first number: ");
scanf("%d", &num1);

printf("Enter the second number: ");


scanf("%d", &num2);

int greaterNumber = (num1 > num2) ? num1 : num2;

printf("The greater number is: %d\n", greaterNumber);


return 0;
}
Comma Operator:

, : Comma operator is used to separate expressions, and


it evaluates each expression from left to right and returns the
value of the rightmost expression

Evaluation Order: The comma operator evaluates each expression in


sequence from left to right. The expressions are evaluated one by one, and
the result of each expression is discarded, except for the last expression.
Return Value: The value of the entire comma expression is the value of the
last expression in the sequence. This means that if you use the comma
operator within a larger expression, the value of the entire expression will
be the value of the last expression.

Side Effects: While the comma operator is mainly used to sequence


expressions, it can also be used for its side effects. For example, if an
expression changes the value of a variable or performs some action, the
comma operator can be used to ensure that those changes or actions occur
before moving to the next expression.
#include <stdio.h>
int main() {
int x = 5, y = 10;
// Use of the comma operator with multiple expressions
int result = (x += 3, y += 5, x + y);
printf("x = %d, y = %d\n", x, y); // Output: x = 8, y = 15
printf("Result = %d\n", result); // Output: Result = 23
return 0;
}
Special operators
1. Comma operator
2. Type cast operator (cast)
3. Reference operator (&)
4. Dereference operator (*)
5. Double pointer operator ()**
6. sizeof operator (sizeof)
• Comma operator (,): The comma operator allows you to evaluate
multiple expressions in a single statement. The expressions are
evaluated from left to right, and the value of the last expression is
returned.
• Type cast operator (cast): The type cast operator allows you to convert
a value from one type to another. For example, you could cast an
integer to a float.
• Reference operator (&): The reference operator returns the address of
a variable. This can be useful for passing variables to functions by
reference.
Dereference operator (*): The dereference operator returns the value
of the variable that a pointer is pointing to.
Double pointer operator ()**: The double pointer operator creates a
pointer to a pointer. This can be useful for accessing data structures
that are nested within each other.
sizeof operator (sizeof): The sizeof operator returns the size of a
variable or data type. This can be useful for determining how much
memory a variable or data type takes up.
Type conversion

Type conversion in C, also known as type casting, is the process of converting a


value of one data type to another data type. C allows implicit type conversion and
explicit type casting to handle different data types and ensure proper compatibility
when performing operations.
Two types :
1. Implicit type conversion
2. Explicit type cast
ATK
Implicit Type Conversion:
• Implicit type conversion, also known as automatic type conversion or
coercion, is performed automatically by the compiler when the data types
of operands in an expression are different.
• The compiler converts the operands to a common data type according to a
set of rules called "usual arithmetic conversions" to perform the operation.
For example, when you add an integer to a floating-point number, the
integer is implicitly converted to a floating-point number before
performing
ATK
the addition.
#include <stdio.h>
int main() {
int num1 = 5;
double num2 = 3.14;
// Implicit conversion of int to double
double result = num1 + num2;
printf("Result: %lf\n", result); // Output: Result: 8.140000
return 0;
}
ATK
Explicit Type Casting:

Explicit type casting allows you to explicitly convert a value of one data type to another
data type using a cast operator.
The cast operator has the syntax (type) expression, where type is the target data type, and
expression is the value to be converted.
Explicit type casting is useful when you want to override the default implicit conversions
or when you need to ensure that a particular type of operation is performed.

ATK
#include <stdio.h>

int main() {
double num1 = 3.14;
int num2;

// Explicit conversion of double to int


num2 = (int)num1;

printf("num2: %d\n", num2); // Output: num2: 3

return 0;
}
ATK
#include <stdio.h>

int main() {
// Implicit Type Conversion
int num1 = 5;
double num2 = 3.14;
double result = num1 + num2;
printf("Implicit Type Conversion:\n");
printf("num1 + num2 = %lf\n\n", result);

// Explicit Type Casting


double num3 = 10.75;
int num4;
num4 = (int)num3; // Explicitly cast double to int
printf("Explicit Type Casting:\n");
printf("num3 (double) = %lf\n", num3);
printf("num4 (int) = %d\n", num4);

return 0;
}

ATK

You might also like