CP Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

CHAPTER 1

1.Algorithms:- A sequence of finite steps to solve a particular problem is known as algorithm.

1.1 Characteristics of an Algorithm:-


● Clear and Unambiguous: The algorithm should be unambiguous. Each of its steps should be clear in all
aspects and must lead to only one meaning
● Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
● Language Independent: The Algorithm designed must be language-independent,
● Input: An algorithm has zero or more inputs.
● Output: An algorithm produces at least one output.
● Definiteness: All instructions in an algorithm must be unambiguous, precise, and easy to interpret.
● Finiteness: An algorithm must terminate after a finite number of steps in all test cases.
● Effectiveness: An algorithm must be developed by using very basic, simple, and feasible operations
1. Flowchart :- A flowchart is a graphical representation of an algorithm.
2.Types ,Operators and expressions

1.Introduction

2.Features:-
3.The C Character Set :-

4.Identifier in C :- Identifiers are unique names that are assigned to variables, structs, functions, and other
entities.
Rules to Name an Identifier in C
A programmer has to follow certain rules while naming variables. For the valid identifier, we must follow the given below
set of rules.

2. An identifier can include letters (a-z or A-Z), and digits (0-9).


3. An identifier cannot include special characters except the ‘_’ underscore.
4. Spaces are not allowed while naming an identifier.
5. An identifier can only begin with an underscore or letters.
6. We cannot name identifiers the same as keywords because they are reserved words to perform a specific task. For
example, printf, scanf, int, char, struct, etc. If we use a keyword’s name as an identifier the compiler will throw an
error.
7. The identifier must be unique in its namespace.
8. C language is case-sensitive so, ‘name’ and ‘NAME’ are different identifiers.

5.Variable in C Language :-
“The name associated with some memory location to store data of different types.”
“Variables are containers for storing data values, like numbers and characters.”
Syntax :-
data_type variable_name = value; // defining single variable
or
data_type variable_name1, variable_name2; // defining multiple variable
Rules for constructing variable name:-
1. A variable name must only contain alphabets, digits, and underscore.
2. A variable name must start with an alphabet or an underscore only. It cannot 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.
Example :-
// Create integer variables
int length = 4;
int width = 6;
int area;
// Calculate the area of a rectangle
area = length * width;
// Print the variables
printf("Length is: %d\n", length);
printf("Width is: %d\n", width);
printf("Area of the rectangle is: %d", area);

Output:-
Length is: 4
Width is: 6
Area of the rectangle is: 24
6.Data Types :-
“The data type specifies the size and type of information the variable will store.”
The data types in C can be classified as follows:
Types Description
Primitive Data Types Basic data types such as integers, float, characters, etc.

User Defined Data Types Defined by the user himself.

Derived Types Derived from the primitive or built-in datatypes are referred to as Derived
Data Types.
Escape Sequence in C :-
7.Constants in C :-
The constants are the read-only variables whose values cannot be modified once they are declared in the C program.
7.1 define constant in C
There are two ways to define constant in C programming.
1. const keyword

2. #define preprocessor

7.2 List of Constants in C :-

8.Keywords in c :-
Keywords are predefined or reserved words that have special meanings to the compiler.
9.Operators in C :-
An operator is defined as the symbol that helps us to perform some specific mathematical, relational, bitwise,
conditional, or logical computations on values and variables.
9.1 Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y


% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

9.2 Assignment Operators


Assignment operators are used to assign values to variables.
Example :-
int x = 10;
A list of all assignment operators:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

9.3 Comparison Operators


Comparison operators are used to compare two values (or variables).
The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values are known
as Boolean values.
Example
int x = 5;
int y = 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
A list of all comparison operators:-

Operator Name Example Description

== Equal to x == y Returns 1 if the values are equal

!= Not equal x != y Returns 1 if the values are not equal

> Greater than x>y Returns 1 if the first value is greater than the second value

< Less than x<y Returns 1 if the first value is less than the second value

>= Greater than or equal to x >= y Returns 1 if the first value is greater than, or equal to, the second
value

<= Less than or equal to x <= y Returns 1 if the first value is less than, or equal to, the second value

9.4 Logical Operators


Test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:

Operator Name Example Description

&& Logical and x < 5 && x < 10 Returns 1 if both statements are true
|| Logical or x < 5 || x < 4 Returns 1 if one of the statements is true

! Logical not !(x < 5 && x < 10) Reverse the result, returns 0 if the result is 1

9.5 Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation.

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

Operator Description Example

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

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

~ (~A ) = ~(60), i.e,. -0111101


Binary One's Complement Operator is unary and
has the effect of 'flipping' bits.

<< Binary Left Shift Operator. The left operands value


is moved left by the number of bits specified by the
right operand. A << 2 = 240 i.e., 1111 0000

>> Binary Right Shift Operator. The left operands value


is moved right by the number of bits specified by
the right operand. A >> 2 = 15 i.e., 0000 1111

9.6 Misc Operators ↦ sizeof & ternary

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 : otherwise
Conditional Expression.
value Y

Operators Precedence in C :-
Operator precedence determines the order in which operators are evaluated when an expression contains
multiple operators.
Operator precedence in which operators will be given priority when there are multiple operators in the
expression. It is very common to have multiple operators in C language and the compiler first evaluates the
operater with higher precedence.

Associativity of Operators
The associativity of operators determines the direction in which an expression is evaluated.

int x = 5 - 17* 6;

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

10.Basic input and output statements :-


● Formatted I/O Functions.
● Unformatted I/O Functions.

10.1 Formatted I/O Functions :- Formatted I/O functions are used to take various inputs from
the user and display multiple outputs to the user. These types of I/O functions can help to display the
output to the user in different formats using the format specifiers.

formatted I/O functions are:


1.printf()
2.scanf()

1. printf():
printf() function is used in a C program to display any value like float, integer, character,
string, etc on the console screen. It is a pre-defined function that is already declared in the
stdio.h(header file).
Syntax: printf(“Format Specifier”, var1, var2, …., varn);

Example:
// C program to implement printf() function
#include <stdio.h>
int main()
{
int a; // Declaring an int type variable
a = 20; // Assigning a value in a variable
printf("%d", a); // Printing the value of a variable
return 0;
}

Output :-
20
2. scanf():

scanf() function is used in the C program for reading or taking any value from the keyboard
by the user, these values can be of any data type like integer, float, character, string, and
many more. In scanf() function use &(address-of operator) which is used to store the
variable value on the memory location of that variable.

Syntax: scanf(“Format Specifier”, &var1, &var2, …., &varn);

Example:
// C program to implement scanf() function

#include <stdio.h>

int main()

int num1;

printf("Enter a integer number: ");

scanf("%d", &num1); // Taking an integer value from keyboard

printf("You have entered %d", num1); // Displaying the entered value

return 0;

Output
Enter a integer number: You have entered 0

Unformatted Input/Output functions:- Unformatted I/O functions are used only for
character data type or character array/string and cannot be used for any other datatype. These
functions are used to read single input from the user at the console and it allows to display the value
at the console.

These functions are called unformatted I/O functions because we cannot use format specifiers in these
functions and hence, cannot format these functions according to needs.

The following unformatted I/O functions will be :-

1. getchar()

2. putchar()

3. gets()

4. puts()

1.getchar()

The getchar() function is used to read only a first single character from the keyboard whether multiple
characters is typed by the user and this function reads one character at one time until and unless the
enter key is pressed. This function is declared in stdio.h(header file)

Syntax: Variable-name = getchar();

Example:

// C program to implement the getchar() function


#include <conio.h>

#include <stdio.h>

int main()

// Declaring a char type variable

char ch;

printf("Enter the character: ");

// Taking a character from keyboard

ch = getchar();

// Displays the value of ch

printf("%c", ch);

return 0;

Output:

Enter the character: a

2.putchar():
The putchar() function is used to display a single character at a time by passing that character directly
to it or by passing a variable that has already stored a character. This function is declared in
stdio.h(header file)

Syntax: putchar(variable_name);

Example:

// C program to implement the putchar() function

#include <conio.h>

#include <stdio.h>

int main()

char ch;

printf("Enter any character: ");

// Reads a character

ch = getchar();

// Displays that character

putchar(ch);

return 0;

Output:
Enter any character: Z

3.gets():
gets() function reads a group of characters or strings from the keyboard by the user and these
characters get stored in a character array.

Syntax: char str[length of string in number]; //Declare a char type variable of any length

gets(str);

Example:

// C program to implement the gets() function

#include <conio.h>

#include <stdio.h>

int main()

// Declaring a char type array of length 50 characters

char name[50];

printf("Please enter some texts: ");

gets(name); // Reading a line of character or a string

printf("You have entered: %s",name); // Displaying this line of character or a string

return 0;
}

Output:
Please enter some texts: geeks for geeks

You have entered: geeks for geeks

4.puts():
In C programming puts() function is used to display a group of characters or strings which is already
stored in a character array.

Syntax: puts(identifier_name );

Example:

// C program to implement the puts() function

#include <stdio.h>

int main()

char name[50];

printf("Enter your text: ");

gets(name); // Reads string from user

printf("Your text is: ");

puts(name); // Displays string


return 0;

Output:
Enter your text: GeeksforGeeks

Your text is: GeeksforGeeks


10.Structure of c program :-

Documentation section :- The documentation section consists of a set of comment lines giving the
name of the program, the author and other details, which the programmer would like to use later.

Link section :- The link section provides instructions to the compiler to link functions from the system
library such as using the #include directive.

Definition section :- The definition section defines all symbolic constants such using the #define
directive.
Global declaration section:- There are some variables that are used in more than one function. Such
variables are called global variables and are declared in the global declaration section that is outside of
all the functions. This section also declares all the user-defined functions.

main () function section:-Every C program must have one main function section. This section
contains two parts; declaration part and executable part

Declaration part:-The declaration part declares all the variables used in the executable part.

Executable part:- There is at least one statement in the executable part. These two parts must
appear between the opening and closing braces. The program execution begins at the opening brace
and ends at the closing brace. The closing brace of the main function is the logical end of the program.
All statements in the declaration and executable part end with a semicolon.

Subprogram section:- If the program is a multi-function program then the subprogram section
contains all the user-defined functions that are called in the main () function. User-defined functions
are generally placed immediately after the main () function, although they may appear in any order.

All section, except the main () function section may be absent when they are not required.

Unit III Control Flow


1. Statements:
○ A statement is an executable part of a program that performs a specific action.
○ It represents a single operation or command.
○ Examples of statements include assignments, function calls, loops, and
conditional expressions.
○ Each statement typically ends with a semicolon (;).

For instance, consider the following examples:


int x = 10; // Assignment statement
printf("Hello, World!"); // Function call statement
while (x > 0) { // Loop statement
// ...
}


2. Blocks:
○ A block is a construct that groups multiple statements together.
○ It begins with an opening curly brace { and ends with a closing curly brace }.
○ Inside a block, you can have a series of statements and declarations.
○ Another term for blocks is compound statements.
○ Here are some key points about blocks:
■ A block can contain any kind of statement.
■ Although it doesn’t look like a normal statement (since it lacks a semicolon), you
can use it as a statement wherever required.
■ A function body is also a block, but it is not considered a regular statement.
■ Nested blocks (internal blocks) can be placed inside other blocks.

Decision Making statement:-

1. If Statement:
● It is used to decide whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statements is executed otherwise not.

Syntax:-
if(condition)

// Statements to execute if
// condition is true
}

Flowchart of if Statement :-

Example of if in C
// C program to illustrate If statement
#include <stdio.h>

int main()
{
int i = 10;

if (i > 15) {
printf("10 is greater than 15");
}

printf("I am Not in if");


}
Output
I am Not in if

2. if...else Statement:

The if...else statement is used for decision-making. It allows you to execute different
code blocks based on a condition.

Syntax:-
if (condition)

{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

Flowchart of if-else Statement


Example: // C program to illustrate If statement

#include <stdio.h>

int main()
{
int i = 20;

if (i < 15) {

printf("i is smaller than 15");


}
else {

printf("i is greater than 15");


}
return 0;
}

Output

i is greater than 15

3. Nested if-else in C
Nested if statements mean an if statement inside another if statement.

Syntax of Nested if-else

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}
Else
{
if (condition2)
{
// Executes when condition2 is true
}
else
{
// Executes when condition2 is false
}

Flowchart of Nested if-else


Example of Nested if-else

// C program to illustrate nested-if statement


#include <stdio.h>
int main()
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
printf("i is smaller than 15\n");
else
printf("i is greater than 15");
}
return 0;
}
Output :- i is smaller than 15

4. if-else-if Ladder in C
The if else if statements are used when the user has to decide among multiple options. The C if
statements are executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the C else-if ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed. if-else-if
ladder is similar to the switch statement.

Syntax of if-else-if Ladder

if (condition1)
statement1;
else
{
if (condition2)
Statement2;
else
{
if(condition 3)
Statement 3;
else
Statement 4;
}
}

Flowchart of if-else-if Ladder


Example of if-else-if Ladder

// C program to illustrate nested-if statement


#include <stdio.h>
int main()
{
int i = 20;
if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}

Output
i is 20

5. switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to execute
the conditional code based on the value of the variable specified in the switch statement. The
switch block consists of cases to be executed based on the value of the switch variable.

Syntax of switch

switch (expression) {

case value1:

statements;

case value2:

statements;

....

....

....

default:

statements;

}
Note: The switch expression should evaluate to either integer or character. It cannot evaluate any other data type.

Flowchart of switch
Example of switch Statement

// C Program to illustrate the use of switch statement


#include<stdio.h>
int main()
{
// variable to be used in switch statement
int var = 2;

// declaring switch cases


switch(var)
{
case 1:
printf("Case 1 is executed");
break;
case 2:
printf("Case 2 is executed");
break;
default:
printf("Default Case is executed");
Break;
}
return 0;
}

Output
Case 2 is executed

7. Jump Statements in C
These statements are used in C for the unconditional flow of control throughout the functions in a program. They support four
types of jump statements:

A) break

This loop control statement is used to terminate the loop. As soon as the break statement is encountered from within a loop,
the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop.

Syntax of break

break;

Basically, break statements are used in situations when we are not sure about the actual number of iterations for the loop or
we want to terminate the loop based on some condition.
Example of break
#include <stdio.h>

int main() {
printf("break in for loop\n");
for (int i = 1; i < 5; i++) {
if (i == 3) {
break;
} else {
printf("%d ", i);
}
}

printf("\nbreak in while loop\n");


int i = 1;
while (i < 20) {
if (i == 3)
break;
else
printf("%d ", i);
i++;
}

return 0;
}

Output:
break in for loop
1 2
break in while loop
1 2

B) continue

This loop control statement is just like the break statement. The continue statement is opposite to that of the break
statement, instead of terminating the loop, it forces to execute the next iteration of the loop.
As the name suggests the continue statement forces the loop to continue or execute the next iteration. When the continue
statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next
iteration of the loop will begin.

Syntax of continue

continue;

Flowchart of Continue
Example of continue

/ C program to explain the use


// of continue statement
#include <stdio.h>

int main()
{
// loop from 1 to 10
for (int i = 1; i <= 10; i++) {

// If i is equals to 6,
// continue to next iteration
// without printing
if (i == 6)
continue;

else
// otherwise print the value of i
printf("%d ", i);
}

return 0;
}

Output

1 2 3 4 5 7 8 9 10

C) goto

The goto statement in C is a jump statement that allows you to transfer control from one part of your code to another. It’s sometimes
referred to as an unconditional jump statement because it can be used to jump from anywhere to anywhere within a function.

Syntax of goto

Syntax1 | Syntax2

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

goto label; | label:

. | .

. | .

. | .
label: | goto label;

In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a label. Here, a label is a
user-defined identifier that indicates the target statement. The statement immediately followed after ‘label:’ is the destination
statement. The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.

Examples of goto
// C program to check if a number is
// even or not using goto statement
#include <stdio.h>
// function to check even or not
void checkEvenOrNot(int num)
{
if (num % 2 == 0)
// jump to even
goto even;
else
// jump to odd
goto odd;
even:
printf("%d is even", num);
// return if even
return;
odd:
printf("%d is odd", num);
}
int main()
{
int num = 26;
checkEvenOrNot(num);
return 0;
}
Output:
26 is even
D) return

The return in C returns the flow of the execution to the function from where it is called. This statement does not mandatorily
need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and
returns the control from where it was called. The return statement may or may not return anything for a void function, but for
a non-void function, a return value must be returned.

Flowchart of return
Syntax of return
return [expression];

Example of return
For Loop:-

The for loop allows you to repeatedly execute a block of code a specified number of
times.

Syntax:
for (initialization; condition; increment/decrement)
{
// Code to execute in each iteration
}
Flowchart :-
Example:-

//Printing numbers from 1 to 10


#include<stdio.h>
int main()
{
int i;
for(i = 1; i <= 10; i++)
{
printf("%d ", i);
}
return 0;
}
Output :-
1 2 3 4 5 6 7 8 9 10

while Loop:

The while loop repeatedly executes a block of code as long as a condition remains true.

Syntax:
while (condition)
{
// Code to execute while the condition is true
}

Example:

#include <stdio.h>
int main()
{
int i = 0;
while (i < 5)
{
printf("GeeksforGeeks\n");
i++;
}
return 0;
}

Output:-
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

Do-while Loop:

The do…while loop in C is an exit-controlled or post-tested loop. Here’s how it works:


1. The body of the loop is executed first.
2. After executing the body, the test condition is checked.
3. If the condition is true, the program control goes back to the start of the loop, and the body
is executed again.
4. This process repeats until the test condition becomes false.
5. Once the condition is false, the program control moves on to the statements after the loop.

Syntax:-
do {
// Body of the do...while loop
} while (condition);

Example:- Printing “Geeks” Three Times

#include <stdio.h>
int main() {
int i = 0;
do {
printf("Geeks\n");
i++;
} while (i < 3);
return 0;
}

Output :-
Geeks
Geeks
Geeks

You might also like