0% found this document useful (0 votes)
16 views12 pages

Week-3 Operators and Basic of C

Uploaded by

vedantrathi2006
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)
16 views12 pages

Week-3 Operators and Basic of C

Uploaded by

vedantrathi2006
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
You are on page 1/ 12

Weekk-2 Week-4

Week 3 Notes
Week 3 Notes
C Program Structure
Keywords in C
Variables in C
Data Types in C
Operators in C
Expressions:
Operator Precedence and associativity
Input/Output (I/O) in C

C Program Structure
A C program consists of several components that determine its structure and behavior:

1. Preprocessor Directives:

Preprocessor directives are instructions to the preprocessor, which is a separate


program that processes the source code before actual compilation.

They start with a # symbol.

Common directives include #include for including header files and #define for
defining constants.

Example:

1 #include <stdio.h>
2 #define PI 3.14159

2. Global Declarations:

Global declarations include variable and function declarations that are accessible
throughout the program.

Global variables are defined outside of any function.

Global functions are declared before the main() function.

Example:

1 int globalVar = 10; // Global variable


2 int add(int a, int b); // Global function declaration

3. Function Declarations and Definitions:

Functions are blocks of code that perform specific tasks.


They can be declared and defined.

The main() function is the entry point of the program.

Example:

1 // Function declaration
2 int add(int a, int b);
3
4 // Function definition
5 int add(int a, int b)
6 {
7 return a + b;
8 }
9
10 int main()
11 {
12 // Main function code
13 return 0;
14 }

4. Statements and Expressions:

Statements are individual lines of code that perform actions.

Expressions are combinations of values, operators, and function calls.

Example:

1 int x = 5; // Statement
2 int sum = add(3, 4); // Expression using the add() function

5. Comments:

Comments are used for documentation and to improve code readability.

Single-line comments start with // , and multi-line comments are enclosed in /* */ .

Example:

1 // This is a single-line comment


2
3 /*
4 This is a
5 multi-line comment
6 */

6. Return Statement:

The return statement is used to specify the value to be returned from a function.

In the main() function, it indicates the program's exit status.

Example:
1 int add(int a, int b)
2 {
3 return a + b; // Return the sum of a and b
4 }
5
6 int main()
7 {
8 return 0; // Indicates successful program execution
9 }

Example Program:

Here's a complete C program with all the components discussed:

1 #include <stdio.h>
2
3 // Global variable declaration
4 int globalVar = 10;
5
6 // Function declaration
7 int add(int a, int b);
8
9 int main()
10 {
11 // Local variable declaration
12 int x = 5;
13
14 // Function call
15 int result = add(x, globalVar);
16
17 // Output
18 printf("Result: %d\n", result);
19
20 return 0; // Indicates successful program execution
21 }
22
23 // Function definition
24 int add(int a, int b)
25 {
26 return a + b;
27 }

Keywords in C
Keywords, also known as reserved words, are special words in C that have predefined meanings
and cannot be used as identifiers (variable names, function names, etc.). They serve as
fundamental building blocks of the language.

1. auto

2. break

3. case

4. char
5. const

6. continue

7. default

8. do

9. double

10. else

11. enum

12. extern

13. float

14. for

15. goto

16. if

17. inline

18. int

19. long

20. register

21. restrict

22. return

23. short

24. signed

25. sizeof

26. static

27. struct

28. switch

29. typedef

30. union

31. unsigned

32. void

33. volatile

34. while

Please note that the list above includes the standard C keywords, and some compilers or
environments may introduce additional keywords or extensions. It's important to avoid using
these reserved keywords as identifiers in your C programs to ensure correct and predictable
behavior.
Variables in C
1. What Are Variables:

Variables are named storage locations in computer memory that hold data.

They are used to store and manipulate data in a program.

2. Variable Declaration:

Before using a variable, you must declare it, specifying its data type.

Syntax: data_type variable_name;

Example:

1 int age; // Declaring an integer variable named 'age'

3. Variable Initialization:

Variables can be assigned initial values at the time of declaration.

Syntax: data_type variable_name = initial_value;

Example:

1 int count = 0; // Initializing an integer variable 'count' with the value


0

4. Naming Rules:

Variable names must follow certain rules:

They can include letters, digits, and underscores.

They must start with a letter or an underscore.

Variable names are case-sensitive (e.g., myVar and myvar are different).

C has reserved keywords that cannot be used as variable names (e.g., int , if ,
while , etc.).

Data Types in C
Data types define the type of data that can be stored in a variable. C provides several fundamental
data types:

1. int (Integer):

Used to store whole numbers (positive, negative, or zero).

Typically, 4 bytes in most systems.

Example:

1 int age = 25;

2. float (Floating-Point):

Used to store decimal numbers with single precision.

Typically, 4 bytes.
Example:

1 float price = 19.99;

3. double (Double Precision):

Used to store decimal numbers with double precision.

Typically, 8 bytes.

Example:

1 double pi = 3.14159265359;

4. char (Character):

Used to store single characters, enclosed in single quotes.

Typically, 1 byte.

Example:

1 char grade = 'A';

5. _Bool (Boolean):

Used for Boolean values, which are true (1) or false (0).

Typically, 1 byte.

Example:

1 _Bool isTrue = true;


2 _Bool isFalse = false;

6. void (Void):

Represents the absence of a value.

Typically used for functions that do not return a value.

Example:

1 void printMessage()
2 {
3 printf("Hello, World!\n");
4 }

7. Custom Data Types:

Programmers can define their own custom data types using struct , enum , and
typedef keywords.

Example (using struct ):


1 struct Point
2 {
3 int x;
4 int y;
5 };
6 struct Point p1;
7 p1.x = 5;
8 p1.y = 3;

Modifiers for Data Types:

C also provides modifiers that can be applied to data types:

1. short:

Used to reduce the storage size of an integer.

Example:

1 short int smallNumber = 100;

2. long:

Used to increase the storage size of an integer.

Example:

1 long int bigNumber = 1000000;

3. signed and unsigned:

Used with integer data types to indicate whether they can represent negative numbers
( signed ) or only non-negative numbers ( unsigned ).

Example:

1 unsigned int positiveNumber = 42;


2 signed int anyNumber = -10;

4. const:

Used to define constants that cannot be modified.

Example:

1 const double pi = 3.14159;

Operators in C
1. Arithmetic Operators:

Perform basic arithmetic operations.

Examples:

+ (Addition)
- (Subtraction)

* (Multiplication)

/ (Division)

% (Modulo, remainder)

Example:

1 int x = 5;
2 int y = 3;
3 int sum = x + y; // Addition
4 int diff = x - y; // Subtraction
5 int product = x * y; // Multiplication
6 int quotient = x / y; // Division
7 int remainder = x % y; // Modulo

2. Relational Operators:

Compare values and return true (1) or false (0).

Examples:

== (Equal to)

!= (Not equal to)

< (Less than)

> (Greater than)

<= (Less than or equal to)

>= (Greater than or equal to)

Example:

1 int a = 10;
2 int b = 5;
3 _Bool isEqual = (a == b); // Equal to (false)
4 _Bool isNotEqual = (a != b); // Not equal to (true)

3. Logical Operators:

Combine conditions and return true (1) or false (0).

Examples:

&& (Logical AND)

|| (Logical OR)

! (Logical NOT)

Example:

1 _Bool isTrue = 1;
2 _Bool isFalse = 0;
3 _Bool result1 = (isTrue && isFalse); // Logical AND (false)
4 _Bool result2 = (isTrue || isFalse); // Logical OR (true)
5 _Bool result3 = !isTrue; // Logical NOT (false)

4. Assignment Operators:
Assign values to variables and perform operations in one step.

Examples:

= (Assignment)

+= (Add and assign)

-= (Subtract and assign)

*= (Multiply and assign)

/= (Divide and assign)

%= (Modulo and assign)

Example:

1 int num = 5;
2 num += 3; // Add and assign (num is now 8)
3 num -= 2; // Subtract and assign (num is now 6)

5. Increment and Decrement Operators:

Increase or decrease variable values by 1.

Examples:

++ (Increment by 1)

-- (Decrement by 1)

Example:

1 int count = 10;


2 count++; // Increment by 1 (count is now 11)
3 count--; // Decrement by 1 (count is now 10 again)

Pre-increment ( ++var ) and Post-increment ( var++ ) Operators:

In C, the increment operator ( ++ ) is used to increase the value of a variable by 1. There are two
forms of the increment operator: pre-increment and post-increment.

1. Pre-increment ( ++var ):

In pre-increment, the value of the variable is incremented before its current value is
used in an expression.

The variable is increased by 1, and the updated value is used immediately.

Example:

1 int x = 5;
2 int y = ++x; // Pre-increment: x is incremented to 6, and then assigned
to y
3 // x is now 6, y is 6

2. Post-increment ( var++ ):

In post-increment, the value of the variable is used in an expression first, and then it is
incremented by 1.

The current value is used, and then the variable is increased.

Example:
1 int x = 5;
2 int y = x++; // Post-increment: x (5) is assigned to y first, then x is
incremented to 6
3 // x is now 6, y is 5

Key Points:

Both pre-increment and post-increment operators increase the value of the variable by 1.

The key difference lies in when the increment occurs in relation to the use of the variable in
an expression.

Pre-increment updates the variable and then uses it, while post-increment uses the variable
and then updates it.

Expressions:
An expression is a combination of values, variables, operators, and function calls that results in a
single value.

Example:

1 int x = 5;
2 int y = 3;
3 int result = x + y; // Expression that calculates the sum of x and y

Operator Precedence and associativity


Operator precedence defines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated first. Here is a summary of operator precedence
in C:

1. Parentheses () (highest precedence)

2. Unary Operators ++ , -- , + , - , !

3. Multiplication \* , Division / , Modulo %

4. Addition + , Subtraction -

5. Relational Operators < , <= , > , >=

6. Equality Operators == , !=

7. Logical AND &&

8. Logical OR ||

9. Assignment Operators = , += , -=

10. Comma , (lowest precedence)

Example:

1 int a = 5, b = 3, c = 10;
2 int result = (a + b) * c; // Parentheses have the highest precedence

Associativity in C:
Associativity refers to the order in which operators with the same precedence are evaluated in an
expression. In C, most operators have left-to-right associativity, meaning they are evaluated from
left to right within the expression. However, there are exceptions where operators have right-to-
left associativity.

Left-to-Right Associativity:

Operators with left-to-right associativity are evaluated from left to right when they have the same
precedence. Some common operators with left-to-right associativity include:

1. Arithmetic Operators:

Addition ( + )

Subtraction ( - )

Multiplication ( * )

Division ( / )

Modulo ( % )

Example:

1 int result = 5 + 3 - 2; // Left-to-right: (5 + 3) - 2 = 6

2. Logical Operators:

Logical AND ( && )

Logical OR ( || )

Example:

1 _Bool a = 1, b = 0, c = 1;
2 _Bool result = a && b || c; // Left-to-right: (a && b) || c

Right-to-Left Associativity:

Operators with right-to-left associativity are evaluated from right to left when they have the same
precedence. The most common operator with right-to-left associativity is the assignment operator
( = ).

Example:

1 int x, y, z;
2 x = y = z = 5; // Right-to-left: z is assigned 5, then y is assigned the
value of z (5), and finally x is assigned the value of y (5)

Input/Output (I/O) in C
Input and output operations are fundamental for interacting with users and handling data in C
programs. The C standard library provides functions for performing I/O operations.

Standard I/O Functions:

1. printf():
Used for formatted output.

Format specifiers are placeholders for values.

Example:

1 int age = 25;


2 printf("My age is %d years old.", age);

2. scanf():

Used for formatted input.

Requires format specifiers to read data into variables.

Example:

1 int num;
2 printf("Enter a number: ");
3 scanf("%d", &num);

3. getchar() and putchar():

Used for character input and output.

getchar() reads a single character from input.

putchar() displays a single character as output.

Example:

1 char ch;
2 printf("Enter a character: ");
3 ch = getchar();
4 putchar(ch);

You might also like