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

C Programming Notes Unit 3

Uploaded by

lodhit567
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 Programming Notes Unit 3

Uploaded by

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

Unit -III

C -Programming Part-I
Topics
Operators :- Assignment operator, Bitwise operator,
sizeof() , Comma operator
Conditional Statement – If,If-else ,switch statement ,conditional operator
Iteration(Loop) Statement – while , do-while, for loop

Assignment Operator
 Assignment operators are used for assigning value to a variable.
 The left side operand of the assignment operator is a variable and right side operand of
the assignment operator is a value
 C provides compound assignment operators to assign a value to variable in order to
assign a new value to a variable after performing a specified operation.
Example- variable name=expression (or) value (or) variable
Operator Example Meaning

+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y X=x%y
working of Assignment operators

#include <stdio.h>

int main()
{

int a = 10;
printf("Value of a is %d\n", a);

a += 10;
printf("Value of a is %d\n", a);

a -= 10;
printf("Value of a is %d\n", a);
a *= 10;
printf("Value of a is %d\n", a);

a /= 10;
printf("Value of a is %d\n", a);

return 0;
}
output
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10

Bitwise operators
Bitwise operators in C-
• The bitwise operators are the operators used to perform the operations on the data at the
bit-level.

• When we perform the bitwise operations, then it is also known as bit-level programming.
It consists of two digits, either 0 or 1.

• It is mainly used in numerical computations to make the calculations faster


1.Bitwise AND (&) Operator-
The bitwise AND operator (&) in C performs a bitwise AND operation on each pair of
corresponding bits. The result is 1 if both bits are 1; otherwise, it's 0.

#include <stdio.h>
int main()
{
int num1 = 10; // Binary: 1010
int num2 = 3; // Binary: 0011
int result_and = num1 & num2; // Result: 0010 (decimal: 2)
printf("Bitwise AND Result: %d\n", result_and);
return 0;
}
Output
Bitwise AND Result: 2

2.Bitwise OR ( | ) Operator-
The bitwise OR operator (|) in C performs a bitwise OR operation on each pair of corresponding
bits. The result is 1 if at least one of the bits is 1.
#include <stdio.h>
int main() {
int num1 = 10; // Binary: 1010
int num2 = 3; // Binary: 0011
int result_or = num1 | num2; // Result: 1011 (decimal: 11)
printf("Bitwise OR Result: %d\n", result_or);
return 0;
}
Output
Bitwise OR Result: 11
Bit wise XOR operator, left shift
3. Bitwise XOR (^)
The bitwise XOR operator (^) in C performs a bitwise XOR operation on each pair of
corresponding bits. The result is 1 if the bits are different; otherwise, it's 0.
#include <stdio.h>
int main() {
int num1 = 10; // Binary: 1010
int num2 = 3; // Binary: 0011
int result_xor = num1 ^ num2; // Result: 1001 (decimal: 9)
printf("Bitwise XOR Result: %d\n", result_xor);
return 0;
}
Output
Bitwise XOR Result: 9

Left Shift (<<)


The left shift operator (<<) in C shifts the bits of a number to the left by a specified number of
positions. It effectively multiplies the number by 2 raised to the power of the shift amount.

#include <stdio.h>
int main() {
int num = 5; // Binary: 0101
int shift = 2;
int result_left_shift = num << shift; // Result: 10100 (decimal: 20)
printf("Left Shift Result: %d\n", result_left_shift);
return 0;
}
Output
20
Hint:- 5 x 22 =20

Lecture 16 Bit wise right shift and bitwise not operators.


Bitwise Right Shift (>>)
The bitwise right shift operator (>>) in C shifts the bits of a number to the right by a specified
number of positions. It effectively divides the number by 2 raised to the power of the shift
amount.
#include <stdio.h>
int main() {
int num = 20; // Binary: 10100
int shift = 2;
int result_right_shift = num >> shift; // Result: 5 (binary: 101)
printf("Right Shift Result: %d\n", result_right_shift);
return 0;
}
Output
5
Hint- 20/22 = 5

Bitwise NOT (~)


The bitwise NOT operator (~) in C flips each bit of the operand, changing 0s to 1s and 1s to 0s.
If n=10 then (~n) = -(n+1)
#include <stdio.h>
int main() {
int num = 10; // Binary: 1010
int result_not = ~num; // Result: -11 (binary: 11111111111111111111111111110101)
printf("Bitwise NOT Result: %d\n", result_not);
return 0;
}
Output
-11

**Complete Example of bitwise operators


#include<stdio.h>
#include<conio.h>
void main()
{
int a=30,b=15;
clrscr();
printf("Bitwise OR=%d\n",(a|b));
printf("Bitwise AND=%d\n",(a&b));
printf("Bitwise NOT=%d\n",(~a));
printf("Bitwise XOR=%d\n",(a^b));
printf("Bitwise Right shift=%d\n",(a>>2));
printf("Bitwise left shift=%d\n",(b<<3));
getch();
}
Output-
Bitwise OR=31
Bitwise AND=14
Bitwise NOT=-31
Bitwise XOR=17
Bitwise Right shift=7
Bitwise left shift=120

Lecture 17 sizeof() and comma as a operator.


• Sizeof is a much-used operator in the C
• It is a compile-time unary operator which can be used to compute the size of its operand
• Syntax:
sizeof(Expression);
• where ‘Expression‘ can be a data type or a variable of any type

Usage of sizeof() operator


1. When the operand is a Data
When sizeof() is used with the data types such as int, float, char… etc it simply returns
the amount of memory allocated to that data types

#include <stdio.h>
int main()
{
printf("Size of char: %d bytes\n", sizeof(char))
printf("Size of int: %i bytes\n", sizeof(int));
printf("Size of float: %i bytes\n", sizeof(float));
printf("Size of double: %i bytes\n", sizeof(double));
return 0;
}
Output:-
Size of char: 1 bytes
Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes

2. When the operand is an expression: When sizeof() is used with the expression, it returns
the size of the expression.

#include <stdio.h>
int main()
{
int a = 0;
double d = 10.21;
printf("%lu", sizeof(a + d));
return 0;
}
Output
8
3.Type of operator
sizeof() is a compile-time operator. compile time refers to the time at which the source
code is converted to a binary code. It doesn’t execute (run) the code inside ().

#include <stdio.h>
int main()
{
int y;
int x = 11; // value of x doesn't change
y = sizeof(x++); // prints 4 and 11
printf("%i %i", y, x);
return 0;
}
Output
4 11

Comma as an operator
 A comma operator in C is a binary operator. It evaluates the first operand & discards
the result, evaluates the second operand & returns the value as a result
 It has the lowest precedence among all C++ Operators
 It is left-associative
 Used to evaluate multiple expression.
Example-1
int a=5,6,7; //error not allowed at declaration time.
Example-2
int a=(5,6,7);
//a=7 allowed at declaration time within parenthesis(left to right, rightmost value assigned).
Example-3
int a;
a=(5,6,7); //a=7 allowed and assign rightmost value to a.

Example-4
int a;
a=5,6,7; //a=5 allowed and without parenthesis assign leftmost value to a.

let us take an another example-


#include<stdio.h>
#include<conio.h>
void main()
{
int a = 5, b = 10, c = 15;
int result;
clrscr();
result = a++, b++, c++;
printf("%d",result); //5
getch();
 }
Output
5
Lecture 18 conditional statements-if, if-else with programs
Control statements are used to specify the flow of execution of a C program. They allow the
programmer to make decisions, repeat code, and jump to different parts of the program.
There are three main types of control statements in C:
 Conditional statements: These statements allow the programmer to make decisions
based on the value of a variable or expression. The most common conditional statements
in C are- if statement, if -else, nested if, if ladder and the switch statement.
 Loop statements: These statements allow the programmer to repeat a block of code
multiple number of time or until a certain condition is met. The most common loop
statements in C are- for loop, while loop, and do-while loop.
 Jump statements: These statements allow the programmer to jump to a different part of
the program. The most common jump statement in C is the goto statement.

if statement syntax-
if(condition)
{
// Statements to execute if condition is true
}
Ex:
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf("Please Enter a Number");
scanf("%d",&n);
if(n>=15)
{
printf("Greater or equal to 15");
}
getch();
}

if---else statement-
syntax-
if (condition)
{
// Executes this block if condition is true
}
else
{
// Executes this block if condition is false
}

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int age;
clrscr();
printf("Please Enter your age");
scanf("%d",&age);
if(age>=18)
{
printf("You can vote");
}
else
{
printf("You can’t Vote");
}
getch();
}

Lecture 19 nesting of if else


nested if..else statement-
syntax:
if (condition1)
{
// Executes when condition1 is true
}
else
{
if (condition2)
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}
}
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int Num=15;
clrscr();
if(Num>10)
{
printf("greater 10");
}
else
{
if(Num>=6)
{
printf("Number is greater or equal to 6");
}
else
{
printf("Number is less than 6");
}
}
getch();
}

Lecture 20
if else-if ladder
if---else if ladder-
syntax:
if (condition)
{
statement;
}
else if (condition)
{
statement;
}.
……..
else
{
statement;
}
Example: program for leap year
#include<stdio.h>
#include<conio.h>
void main()
{
int year=1600;
if(year%400==0)
{
printf("%d is leap year",year);
}
else if(year%4==0 && year%100!=0)
{
printf("%d is leap year",year);
}
else
{
printf("%d is not a leap year",year);
}
getch();
}

Lecture 21 Switch statement in C.


The switch statement in C programming provides an alternative way to make decisions based on
the value of a variable. It's particularly useful when you have multiple conditions to check
against the same variable.
Here's the basic syntax of the switch statement:
switch (expression) {
case constant1:
// code to be executed if expression equals constant1
break;
case constant2:
// code to be executed if expression equals constant2
break;
// more cases can be added as needed
default:
// code to be executed if expression doesn't match any case
}
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int Num=3;
clrscr();
switch(Num)
{
case 1:printf("Monday"); break;
case 2:printf("Tuesday"); break;
case 3:printf("Wednesday"); break;
case 4:printf("Thursday"); break;
case 5:printf("Friday"); break;
case 6:printf("Saturday"); break;
case 7:printf("Sunday"); break;
default:printf("Wrong"); break;
}
getch();
}

Rules for writing switch() statement.


1 : The expression in switch statement must be an integer value or a character constant.
2 : No real numbers are used in an expression.
3 : The default is optional and can be placed anywhere, but usually placed at end.
4 : The case keyword must terminate with colon ( : ).
5 : No two case constants are identical.

Valid Switch Invalid Switch Valid Case Invalid Case


switch(x) switch(f) case 3; case 2.5;
switch(x>y) switch(x+2.5) case 'a'; case x;
switch(a+b-2) case 1+2; case x+2;

Points to Remember
It isn't necessary to use break after each block, but if you do not use it, all the consecutive block
of codes will get executed after the matching block.

int i = 1;
2. switch(i)
3. {
4. case 1:
5. printf("A"); // No break
6. case 2:
7. printf("B"); // No break
8. case 3:
9. printf("C");
10. break;
11. }
Output : A B C
The output was supposed to be only A because only the first case matches, but as there is no
break statement after the block, the next blocks are executed, until the cursor encounters a break.
default case can be placed anywhere in the switch case. Even if we don't include the default case
switch statement works.

Conditional Operator/ Ternary operator:


 conditional operator checks the condition and executes the statement depending of the
condition. A conditional operator is a ternary operator, that is, it works on 3 operands.
 Conditional operator consist of two symbols.
1 : question mark (?).
2 : colon ( : ).
Syntax : condition ? exp1 : exp2;

 It first evaluate the condition, if it is true (non-zero) then the “exp1” is evaluated, if the
condition is false (zero) then the “exp2” is evaluated.

#include <stdio.h>
int main(){
char February;
int days;
printf("If this year is leap year, enter 1. If not enter any integer: ");
scanf("%c",&February);
days = (February == '1') ? 29 : 28;
printf("Number of days in February = %d",days);
return 0;
}
Output
If this year is leap year, enter 1. If not enter any integer: 1
Number of days in February = 29

Lecture 22 conditional statement based programs.


1. Find the largest number among three numbers
2. Check if the given year is a leap year or not?
3. Check given number is even or odd
4. Check given number is positive or negative
5. Check given alphabet is vowel or consonant
Lecture 23 switch based programs.
1. Print day name according to day number.
2. Print month name according to month number.
3. Perform arithmetic operation according to given choice using switch.
4. Perform arithmetic operation according to given choice using switch.
5. Perform bitwise operation according to given choice using switch.

Iteration Statements/ Loop Control Statements


How it Works

 A sequence of statements are executed until a specified condition is true. This


sequence of statements to be executed is kept inside the curly braces { } known as the
Loop body.
 After every execution of loop body, condition is verified, and if it is found to be true
the loop body is executed again. When the condition check returns false, the loop
body is not executed.
 The loops in C language are used to execute a block of code or a part of the program
several times. In other words, it iterates/repeat a code or group of code many times.
 Or Looping means a group of statements are executed repeatedly, until some logical
condition is satisfied.
C language provides three iterative/repetitive loops.
Why use loops in C language?
Suppose that you have to print table of 2, then you need to write 10 lines of code.By using the
loop statement, you can do it by 2 or 3 lines of code only.

A looping process would include the following four steps.


1 : Initialization of a condition variable.
2 : Test the condition.
3 : Executing the body of the loop depending on the condition.
4 : Updating the condition variable.

Types of Loops
Entry Controlled loops: In Entry controlled loops the test condition is checked before
entering the main body of the loop. For Loop and While Loop is Entry-controlled loops
 Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the end
of the loop body. The loop body will execute at least once, irrespective of whether the
condition is true or false. do-while Loop is Exit Controlled loop.

While Loop

 The while loop is an entry controlled loop statement, i.e means the condition is
evaluated first and it is true, then the body of the loop is executed.
 After executing the body of the loop, the condition is once again evaluated and if it is
true, the body is executed once again, the process of repeated execution of the loop
continues until the condition finally becomes false and

While Loop: Syntax :

variable initialization ;
while (condition)
{
statements ;
variable increment or decrement
}
while loop can be addressed as an entry control loop. It is completed in 3 steps.
Variable initialization.( e.g int x=0; )

condition( e.g while( x<=10) )

Variable increment or decrement ( x++ or x-- or x=x+2 )

Flow chart of using While Loop


Example : Program to print first 10 natural numbers
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
x=1;
while(x<=10)
{
printf("%d\t", x);
x++;
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
Program to Print sum of the number from 1 to 10
#include<stdio.h>
int main()
{
int i=1;
int sum=0;
while(i<=10)
{
sum=sum+i;
i++;
}
printf("the sum of number from 1 to 10 is %d",sum);

return 0;
}
Output
The sum of number from 1 to 10 is 55

3. write a C program to display the multiplication table entered by the user

#include<stdio.h>
int main()
{
int num;
int i=1;

printf("enter the table you want to display");


scanf("%d",&num);
while(i<=10)
{
printf("%d *%d=%d \n",num,i,num*i);
i++;
}
return 0;
}
Ouput
Enter the table you want to display -2
2* 1=2
2* 2=4
2* 3=6

For Loop:
This is an entry controlled looping statement.

In this loop structure, more than one variable can be initialized.

One of the most important features of this loop is that the three actions can be taken at a time
like variable initialization, condition checking and increment/decrement.

The for loop can be more concise and flexible than that of while and do-while loops.

Syntax : for(initialization; condition; increment/decrement)


{

statements
}
Various forms of FOR LOOP
I am using variable num in all the below examples –
1) Here instead of num++, I‟m using num=num+1 which is nothing but same as num++.
for (num=10; num<20; num=num+1)
2) Initialization part can be skipped from loop as shown below, the counter variable is declared
before the loop itself.
int num=10;
for (;num<20;num++)
Must Note: Although we can skip init part but semicolon (;) before condition is must, without
which you will get compilation error.
Like initialization, you can also skip the increment part as we did below. In this case semicolon
(;) is must, after condition logic. The increment part is being done in for loop body itself.
for (num=10; num<20; )
{
//Code
num++;
}
4) Below case is also possible, increment in body and init during declaration of counter variable.
int num=10;
for (;num<20;)
{
//Statements
num++;
}
5) Counter can be decremented also, In the below example the variable gets decremented each
time the loop runs until the condition num>10 becomes false.
for(num=20; num>10; num--)
Program to calculate the sum of first n natural numbers

Example:
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
for(x=1; x<=10; x++)
{
printf("%d\t",x);
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10

Factorial Program using loop


#include<stdio.h>
#include<conio.h>
void main(){
int i,fact=1,number;
clrscr();
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
getch();
}
Output:
Enter a number: 5
Factorial of 5 is: 120

Infinitive for loop in C


If you don't initialize any variable, check condition and increment or decrement variable in for
loop, it is known as infinitive for loop. In other words, if you place 2 semicolons in for loop, it is
known as infinitive for loop.
for(; ;){
printf("infinitive for loop example by javatpoint")
}

Diffrence Between for and while Loop

for Loop while Loop

Initialization may be either in the loop


Initialization is always outside the loop.
statement or outside the loop.

Once the statement(s) is executed then The increment can be done before or after the
increment is done. execution of the statement(s).

It is normally used when the number of It is normally used when the number of
iterations is known. iterations is unknown.

The condition may be an expression or non-


Condition is a relational expression.
zero value.

It is used when initialization and updation


It is used for complex initialization.
of conditions are simple.

For loop is entry controlled loop. While loop is also entry controlled loop.

Syntax: for ( init ; condition ; iteration ) {


Syntax: while ( condition ) { statement(s); }
statement(s); }

The for loop is used when the number of The while loop is used when the number of
iterations is known. iterations is unknown.
Do-While loop :-

 It is a Exit-Controlled Loop
 The do-while loop is similar to a while loop but the only difference lies in the do-while
loop test condition which is tested at the end of the body
 In the do-while loop, the loop body will execute at least once irrespective of the test
condition.

Synatax:-

initialization_expression;
do
{
// body of do-while loop

update_expression;

} while (test_expression);

Flow chart of Do-while loop


Example : Program to print first ten multiple of 5
#include<stdio.h>
#include<conio.h>
void main()
{
int a,i;
a=5;
i=1;
do
{
printf("%d\t",a*i);
i++;
}while(i <= 10);
getch();
}
Output
5 10 15 20 25 30 35 40 45 50

Program to print the number from 1 to 10

#include<stdio.h>
int main()
{

int a=1;
do
{
printf(“%d\n”,a);
a++;

}
while(i<=10);
return 0;

}
Output

12345678910

More Program based on loop condition

1. Write a program to print factorial of a number which is input by the user.


2. Write a program to print the reverse of a number.
3. Write a program to check whether the given user number is prime or not
4. Write a program to print Fibonocci series of the given number which is inpute by user
5. Write a program to check whether the given number is palindrome or not
6. Write a program to check whether the number is Armstrong number or not

------------------------------------------------------------------------------------------------------------

You might also like