Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

C Unit 2 notes

Uploaded by

shrushti0221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

C Unit 2 notes

Uploaded by

shrushti0221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

School of Computer Science and Application

NOTES

Subject: Problem Solving Using C Programming

UNIT 2: Operators and Control structures Module-1

An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. By
definition, an operator performs a certain operation on operands. An operator needs one or more operands
for the operation to be performed.

Depending on how many operands are required to perform the operation, operands are called as unary,
binary or ternary operators. They need one, two or three operands respectively.

 Unary operators − ++ (increment), -- (decrement), ! (NOT), ~ (compliment), & (address of), *


(dereference)
 Binary operators − arithmetic, logical and relational operators except !
 Ternary operators − The ? operator

C language is rich in built-in operators and provides the following types of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
 Arithmetic Operators

We are most familiar with the arithmetic operators. These operators are used to perform arithmetic
operations on operands. The most common arithmetic operators are addition (+), subtraction (-),
multiplication (*), and division (/).

Arithmetic operators

In addition, the modulus (%) is an important arithmetic operator that computes the remainder of a division
operation. Arithmetic operators are used in forming an arithmetic expression. These operators are binary in
nature in the sense they need two operands.

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer division. B%A=0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- =


Relational Operators

We are also acquainted with relational operators while learning secondary mathematics. These operators
are used to compare two operands and return a boolean value (true or false). They are used in a boolean
expression.

The most common relational operators are less than (<), greater than (>), less than or equal to (<=), greater
than or equal to (>=), equal to (==), and not equal to (!=). Relational operators are also binary operators,
needing two numeric operands.

Operator Description Example

Checks if the values of two operands are equal or not. If yes, then the (A == B) is not
==
condition becomes true. true.

Checks if the values of two operands are equal or not. If the values are
!= (A != B) is true.
not equal, then the condition becomes true.

Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand. If yes, then the condition becomes true. true.

Checks if the value of left operand is less than the value of right
< (A < B) is true.
operand. If yes, then the condition becomes true.

Checks if the value of left operand is greater than or equal to the value (A >= B) is not
>=
of right operand. If yes, then the condition becomes true. true.

Checks if the value of left operand is less than or equal to the value of
<= (A <= B) is true.
right operand. If yes, then the condition becomes true.

Logical Operators

These operators are used to combine two or more boolean expressions. We can form a compound Boolean
expression by combining Boolean expression with these operators. An example of logical operator is as
follows −

a >= 50 && b >= 50

The most common logical operators are AND (&&), OR(||), and NOT (!). Logical operators are also binary
operators.

Operator Description Example

(A &&
Called Logical AND operator. If both the operands are non-zero, then the
&& B) is
condition becomes true.
false.

Called Logical OR Operator. If any of the two operands is non-zero, then the (A || B)
||
condition becomes true. is true.

!(A &&
Called Logical NOT Operator. It is used to reverse the logical state of its
! B) is
operand. If a condition is true, then Logical NOT operator will make it false.
true.
Bitwise Operators

Bitwise operators let you manipulate data stored in computer’s memory. These operators are used to
perform bit-level operations on operands.

The most common bitwise operators are AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right
shift (>>). Here the "~" operator is a unary operator, while most of the other bitwise operators are binary in
narure.

Bitwise operator works on bits and perform bit−by−bit operation. The truth tables for &, "|", and "^" are as
follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows −

A = 0011 1100
B = 0000 1101
------------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
Operator Description Example

Binary AND Operator copies a bit to the result if it exists in both (A & B) = 12, i.e.,
&
operands. 0000 1100

(A | B) = 61, i.e.,
| Binary OR Operator copies a bit if it exists in either operand.
0011 1101

Binary XOR Operator copies the bit if it is set in one operand but (A ^ B) = 49, i.e.,
^
not both. 0011 0001

Binary One's Complement Operator is unary and has the effect of (~A ) = ~(60), i.e,.
~
'flipping' bits. -0111101

Binary Left Shift Operator. The left operands value is moved left A << 2 = 240 i.e.,
<<
by the number of bits specified by the right operand. 1111 0000

Binary Right Shift Operator. The left operands value is moved A >> 2 = 15 i.e.,
>>
right by the number of bits specified by the right operand. 0000 1111
Assignment Operators

As the name suggests, an assignment operator "assigns" or sets a value to a named variable in C. These
operators are used to assign values to variables. The "=" symbol is defined as assignment operator in C,
however it is not to be confused with its usage in mathematics.

Operator Description Example

Simple assignment operator. Assigns values from right side C = A + B will assign
=
operands to left side operand the value of A + B to C

Add AND assignment operator. It adds the right operand to C += A is equivalent to


+=
the left operand and assign the result to the left operand. C=C+A

Subtract AND assignment operator. It subtracts the right


C -= A is equivalent to
-= operand from the left operand and assigns the result to the left
C=C-A
operand.

Multiply AND assignment operator. It multiplies the right


C *= A is equivalent to
*= operand with the left operand and assigns the result to the left
C=C*A
operand.

Divide AND assignment operator. It divides the left operand


C /= A is equivalent to
/= with the right operand and assigns the result to the left
C=C/A
operand.

Modulus AND assignment operator. It takes modulus using C %= A is equivalent to


%=
two operands and assigns the result to the left operand. C=C%A

C <<= 2 is same as C =
<<= Left shift AND assignment operator.
C << 2

C >>= 2 is same as C =
>>= Right shift AND assignment operator.
C >> 2

C &= 2 is same as C =
&= Bitwise AND assignment operator.
C&2

C ^= 2 is same as C = C
^= Bitwise exclusive OR and assignment operator.
^2

C |= 2 is same as C = C
|= Bitwise inclusive OR and assignment operator.
|2

Misc Operators ↦ sizeof & ternary

Besides the operators discussed above, there are a few other important operators including sizeof and ?
: supported by the C Language.

Operator Description Example

sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4.

&a; returns the actual address of the


& Returns the address of a variable.
variable.
* Pointer to a variable. *a;

If Condition is true ? then value X :


?: Conditional Expression.
otherwise value Y

Expressions in C:

1. Arithmetic Expressions

These involve arithmetic operators to perform mathematical operations.

 Operators: +, -, *, /, %
 Example: a + b * (c - d) / e

2. Relational Expressions

These compare two values and yield a boolean result (true or false).

 Operators: ==, !=, >, <, >=, <=


 Example: x >= y

3. Logical Expressions

These use logical operators to combine or invert boolean expressions.

 Operators: && (logical AND), || (logical OR), ! (logical NOT)


 Example: (a > b) && (c < d)

4. Bitwise Expressions

These operate on the binary representations of integers.

 Operators: & (bitwise AND), | (bitwise OR), ^ (bitwise XOR), ~ (bitwise NOT), << (left shift), >>
(right shift)
 Example: x & y

5. Assignment Expressions

These assign a value to a variable. Assignment operators can also combine assignment with arithmetic
operations.

 Operators: =, +=, -=, *=, /=, %= etc.


 Example: a = b + c or a += b

6. Conditional Expressions (Ternary Operator)


A shorthand for simple if-else statements.
 Operator: ?:
 Example: result = (a > b) ? a : b;

7. Comma Expressions
These allow multiple expressions to be evaluated in a single statement, with the result being the value of
the last expression.

 Operator: ,
 Example: a = (b = 2, b + 3); (Here, b is first assigned 2, then b + 3 is evaluated, resulting in 5.)
8. Unary Expressions

These involve a single operand and an operator.

 Operators: + (positive), - (negative), ++ (increment), -- (decrement), & (address-of), *


(dereference), ! (logical NOT), ~ (bitwise NOT)
 Example: ++a or !flag

9. Pointer Expressions

These involve pointers and operations on them.

 Operators: * (dereference), & (address-of), -> (member access through pointer), [] (array
subscripting)
 Example: *(ptr + 2)

10. Function Calls

These involve calling functions and using their return values in expressions.

 Example: max(a, b) + 10 where max is a function that returns the maximum of a and b.

Operators Precedence in C

Operator precedence determines the grouping of terms in an expression and decides how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than
+, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.

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 , Left to right

Character INPUT and OUTPUT IN C:


Character Input

1. Using getchar()

getchar() reads a single character from standard input (usually the keyboard). It returns the
character read as an int, which allows it to return EOF if there’s an error or if the end of the file is
reached.

Example:

#include <stdio.h>

int main() {
int c;

printf("Enter a character: ");


c = getchar(); // Read a single character

printf("You entered: ");


putchar(c); // Print the character

return 0;
}

2. Using scanf()

scanf() can also be used to read characters. Use %c as the format specifier.

#include <stdio.h>

int main() {
char ch;

printf("Enter a character: ");


scanf("%c", &ch); // Read a single character

printf("You entered: %c\n", ch); // Print the character

return 0;
}
Character Output

1. Using putchar()

putchar() prints a single character to standard output.

#include <stdio.h>

int main() {
char ch = 'A';

printf("The character is: ");


putchar(ch); // Output the character
putchar('\n'); // Print a newline character

return 0;
}

2. Using printf()

printf() can be used for more complex formatting. Use %c to print a character.

#include <stdio.h>

int main() {
char ch = 'B';

printf("The character is: %c\n", ch); // Output the character with formatting

return 0;
}
Handling Multiple Characters

 Inputting a String

To read a string (an array of characters), use %s with scanf(). Note that scanf() will stop reading at
the first whitespace character.

#include <stdio.h>

int main() {
char str[100];

printf("Enter a string: ");


scanf("%s", str); // Read a string

printf("You entered: %s\n", str); // Output the string

return 0;
}
 Reading a Line

To read a whole line of input, including spaces, use fgets().

#include <stdio.h>

int main() {
char line[100];

printf("Enter a line of text: ");


fgets(line, sizeof(line), stdin); // Read a whole line of input

printf("You entered: %s", line); // Output the line

return 0;
}

String Input and Output in C:

1. String Input

Using scanf()

scanf() can be used to read strings, but it will stop reading at the first whitespace character.

#include <stdio.h>

int main() {
char str[100];

printf("Enter a string: ");


scanf("%s", str); // Read a string (stops at whitespace)

printf("You entered: %s\n", str); // Output the string

return 0;
}

Note:
scanf("%99s", str); // Read up to 99 characters, leaving space for the null terminator

Using fgets()

fgets() reads a whole line, including spaces, until a newline character or the end of the file is encountered,
or until the specified number of characters are read.

#include <stdio.h>
int main() {
char str[100];
printf("Enter a line of text: ");
fgets(str, sizeof(str), stdin); // Read a whole line (including spaces)
printf("You entered: %s", str); // Output the string
return 0;
}
Note: fgets() includes the newline character if it fits in the buffer, so you might need to remove it if
it's not desired:

#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a line of text: ");
if (fgets(str, sizeof(str), stdin)) {
// Remove trailing newline character if present
size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n') {
str[len - 1] = '\0';
}
}
printf("You entered: %s\n", str);

return 0;
}

2. String Output

Using printf()

To print strings, use the %s format specifier with printf():

c
Copy code
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
printf("The string is: %s\n", str); // Output the string
return 0;
}

Using puts()

puts() prints a string followed by a newline character.

#include <stdio.h>
int main() {
char str[] = "Hello, World!";

puts(str); // Output the string followed by a newline

return 0;
}
Formatted input and output in C

Formatted input and output in C are handled using the printf and scanf family of functions from the C
Standard I/O library (<stdio.h>). These functions allow you to format data for output and interpret
formatted data from input.

1. Formatted Output with printf()

The printf() function allows you to format data before printing it to the standard output (usually the
console). Here are some common format specifiers and options:

Basic Format Specifiers

 %d or %i: Integer
 %f: Floating-point number
 %c: Character
 %s: String
 %u: Unsigned integer
 %x or %X: Hexadecimal integer
 %o: Octal integer
 %p: Pointer address

Formatting Options

 Field Width: Specifies the minimum number of characters to be printed. Example: %5d prints an
integer in a field of at least 5 characters wide.
 Precision: For floating-point numbers, it specifies the number of digits after the decimal point.
Example: %.2f prints a float with 2 decimal places.
 Flags: Control alignment and padding.
o -: Left-align the output (default is right-align).
o 0: Pad the output with zeros instead of spaces.

Examples:

#include <stdio.h>

int main() {
int num = 42;
float pi = 3.14159;
char ch = 'A';
char str[] = "Hello, World!";

// Integer with field width


printf("Integer: %5d\n", num);

// Floating-point number with precision


printf("Pi: %.2f\n", pi);

// Character
printf("Character: %c\n", ch);

// String
printf("String: %s\n", str);
// Hexadecimal and octal
printf("Hexadecimal: %x\n", num);
printf("Octal: %o\n", num);

// Padding with zeros


printf("Padded number: %05d\n", num);

// Left alignment
printf("Left-aligned: %-5d\n", num);

return 0;
}
2. Formatted Input with scanf()

The scanf() function reads formatted input from the standard input. It uses format specifiers to interpret the
data entered by the user.

Basic Format Specifiers

 %d or %i: Integer
 %f: Floating-point number
 %c: Character
 %s: String (stops at whitespace)
 %u: Unsigned integer
 %x or %X: Hexadecimal integer

Examples:

#include <stdio.h>

int main() {
int num;
float pi;
char ch;
char str[100];

// Read an integer
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %d\n", num);

// Read a floating-point number


printf("Enter a float: ");
scanf("%f", &pi);
printf("You entered: %.2f\n", pi);

// Read a single character


printf("Enter a character: ");
scanf(" %c", &ch); // Note the space before %c to skip whitespace
printf("You entered: %c\n", ch);

// Read a string (up to whitespace)


printf("Enter a string: ");
scanf("%s", str);
printf("You entered: %s\n", str);
return 0;
}
Subject: Problem Solving Using C Programming

UNIT 2: Operators and Control structures Module-2

In programming, we come across situations when we need to make some decisions. Based on these
decisions, we decide what should we do next. Similar situations arise in algorithms too where we need to
make some decisions and based on these decisions, we will execute the next block of code.

The next instruction depends on a Boolean expression, whether the condition is determined to be True or
False. C programming language assumes any non-zero and non-null values as True, and if it is either zero
or null, then it is assumed as a False value.

C programming language provides the following types of decision-making statements.

Sr.No. Statement & Description

if statement
1
An if statement consists of a boolean expression followed by one or more statements.

if...else statement
2 An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.

nested if statements
3
You can use one if or else-if statement inside another if or else-if statement(s).

switch statement
4
A switch statement allows a variable to be tested for equality against a list of values.

nested switch statements


5
You can use one switch statement inside another switch statement(s).

If Statement in C Programming

The if statement is used for deciding between two paths based on a True or False outcome. It is represented
by the following flowchart −
Syntax
if (Condition){
expression;
...
}
Example:
#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

if (num > 0) {
printf("The number is positive.\n");
}

return 0;
}

If...else Statement in C Programming

The if–else statement offers an alternative path when the condition isn't met.
Syntax

if (condition){

expression;

...

else{

expression;

. . .\

An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.

Example:

#include <stdio.h>

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

if (num % 2 == 0) {

printf("The number is even.\n");

} else {

printf("The number is odd.\n");

return 0;

}
Nested If Statements in C Programming

Nested if statements are required to build intricate decision trees, evaluating multiple nested conditions for
nuanced program flow.

You can use one if or else-if statement inside another if or else-if statement(s).

Syntax
The syntax of nested if statements is as follows –

if (condition-1){

if (condition- 2){

block to be executed when

expr1 and expr2 are true

else{

block to be executed when

expr1 is true but expr2 is false

Example:

#include <stdio.h>

int main() {

int score;

printf("Enter your score (0-100): ");

scanf("%d", &score);
if (score >= 90) {

printf("Grade: A\n");

} else if (score >= 80) {

printf("Grade: B\n");

} else if (score >= 70) {

printf("Grade: C\n");

} else if (score >= 60) {

printf("Grade: D\n");

} else {

printf("Grade: F\n");

return 0;

Switch Statement in C Programming

A switch statement simplifies multi-way choices by evaluating a single variable against multiple values,
executing specific code based on the match. It allows a variable to be tested for equality against a list of
values.
Syntax

switch(expression) {

case constant-expression:

statement(s);

break; /* optional */

case constant-expression:

statement(s);

break; /* optional */

/* you can have any number of case statements */

default: /* Optional */

statement(s);

As in if statements, you can use one switch statement inside another switch statement(s).

Example:

#include <stdio.h>

int main() {

int day;

printf("Enter a number (1-7) for the day of the week: ");

scanf("%d", &day);

switch (day) {

case 1:

printf("Monday\n");

break;

case 2:

printf("Tuesday\n");

break;

case 3:

printf("Wednesday\n");

break;
case 4:

printf("Thursday\n");

break;

case 5:

printf("Friday\n");

break;

case 6:

printf("Saturday\n");

break;

case 7:

printf("Sunday\n");

break;

default:

printf("Invalid input. Please enter a number between 1 and 7.\n");

break;

return 0;

The ?: Operator in C Programming

We have covered the conditional operator (?:) in the previous chapter which can be used to replace if-
else statements. It condenses an if-else statement into a single expression, offering compact and readable
code.

It has the following general form −

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon (:). The value of a
"?" expression is determined like this −

Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression.

If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the : expression.
Loop control structures

Loop control structures in C are used to execute a block of code repeatedly based on certain conditions.
The primary loop control structures in C are for, while, and do-while loops. Here’s an overview of each,
along with examples.

1. for Loop

The for loop is used when the number of iterations is known beforehand. It consists of three parts:
initialization, condition, and iteration expression.

Syntax:

for (initialization; condition; iteration) {

// Code to be executed

Example: Print numbers from 1 to 5.

#include <stdio.h>

int main() {

int i;

for (i = 1; i <= 5; i++) {

printf("%d\n", i);

return 0;

2. while Loop

The while loop is used when the number of iterations is not known and depends on a condition. The loop
continues as long as the condition is true.

Syntax:

while (condition) {

// Code to be executed

Example: Print numbers from 1 to 5.

#include <stdio.h>

int main() {

int i = 1;
while (i <= 5) {

printf("%d\n", i);

i++; // Increment the variable

return 0;

3. do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the block of code will be executed at
least once before the condition is tested.

Syntax:

do {

// Code to be executed

} while (condition);

Example: Print numbers from 1 to 5.

#include <stdio.h>

int main() {

int i = 1;

do {

printf("%d\n", i);

i++; // Increment the variable

} while (i <= 5);

return 0;

The break and continue statements in C are used to alter the flow of execution within loops. They are
useful for controlling the flow of your program and handling specific conditions during iteration.

1. break Statement

The break statement is used to exit from the nearest enclosing loop or switch statement. When break is
encountered, the control flow immediately jumps to the statement following the loop or switch.

Syntax:

break;
Example: Using break to exit a for loop when a condition is met.

#include <stdio.h>

int main() {

int i;

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

if (i == 6) {

break; // Exit the loop when i equals 6

printf("%d\n", i);

printf("Loop exited because i reached %d\n", i);

return 0;

Explanation: In this example, the for loop will iterate from 1 to 10. However, when i equals 6, the break
statement is executed, which exits the loop. The program then prints a message indicating that the loop was
exited.

2. continue Statement

The continue statement is used to skip the current iteration of the nearest enclosing loop and proceed with
the next iteration. It does not exit the loop but rather jumps to the next iteration.

Syntax:

continue;

Example: Using continue to skip printing the number 3 in a for loop.

#include <stdio.h>

int main() {

int i;

for (i = 1; i <= 5; i++) {

if (i == 3) {

continue; // Skip the current iteration when i equals 3

printf("%d\n", i);
}

return 0;

The goto statement

The goto statement in C is a form of unconditional branching that allows you to jump to a different part of
the program. While it can be useful in certain scenarios, its use is generally discouraged because it can
make code less readable and harder to maintain. Instead, structured control flow statements like loops and
conditionals are often preferred.

Syntax of goto

goto label;

Label Syntax:

label_name:

// Code to be executed

Basic Example

Here's a simple example that demonstrates the use of goto to jump to a specific point in the program:

#include <stdio.h>

int main() {

int num = 5;

if (num > 0) {

goto positive;

} else {

goto non_positive;

positive:

printf("The number is positive.\n");

goto end;

non_positive:

printf("The number is zero or negative.\n");

end:

printf("End of program.\n");
return 0;

You might also like