0% found this document useful (0 votes)
2 views130 pages

Problem Solving Using C NVG

The document provides an overview of the C programming language, including its history, features, and importance in modern programming. It discusses algorithms, pseudocode, flowcharts, and the structure of a C program, along with data types, variables, constants, and operators. Additionally, it covers the role of compilers and interpreters in translating C code into machine language.

Uploaded by

Mj Singh
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)
2 views130 pages

Problem Solving Using C NVG

The document provides an overview of the C programming language, including its history, features, and importance in modern programming. It discusses algorithms, pseudocode, flowcharts, and the structure of a C program, along with data types, variables, constants, and operators. Additionally, it covers the role of compilers and interpreters in translating C code into machine language.

Uploaded by

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

PROBLEM SOLVING USING C

Subject Code : UGCA1903

Course Instructor : Navkiran Kaur Gill


Email : navkiran@[Link]

PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY 1


TIMELINE

1960 1967 1969 1972

ALGOL BCPL B C

Algorithmic Language Basic Combined


Programming Language

PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY 2


➢ General purpose programming language
➢ Developed by Dennis Ritchie in 1972
➢ Created at Bell Labs, USA
➢ Originally designed for UNIX development

3
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
WHY SHOULD I LEARN C PROGRAMMING ?
➢ Foundation for Other Modern Languages
➢ System Level Programming
➢ Embedded Systems Development
➢ Core to Software Development
➢ Scientific and Engineering Libraries

4
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
FEATURES
OF C
LANGUAGE

5
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
6
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
ALGORITHM

An algorithm is a finite set of unambiguous instructions which, when


executed, performs a task correctly.

7
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
EXAMPLE
ALGORITHM ADD TWO NUMBERS

Step 0 : START
Step 1 : INPUT first number into variable A
Step 2 : INPUT second number into variable B
Step 3 : COMPUTE SUM = A + B
Step 4 : DISPLAY SUM
Step 5 : END

8
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
PSEUDOCODE
It is a means to represent an algorithm in coded form.

➢ Informal way of writing a program


➢ Written in English
➢ Cannot be compiled or interpreted
➢ Does not follow any syntax

9
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
EXAMPLE
PSEUDOCODE SUM OF TWO NUMBERS

SUM_TWO {
PRINT “Enter a value for number A : “
SCAN A
PRINT “Enter a value for number B : “
SCAN B
SUM A + B
PRINT “The sum is : “, SUM

10
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
PSEUDOCODE
ADVANTAGES DISADVANTAGES

● Easier to write ● Lacks graphical or visual

● Takes less time and effort


representation
● Bridge between algorithm and

program ● Lack of standardization

● Changes in logic can be easily


● Difficult to implement for beginners
modified 11
FLOWCHART

It is the graphical representation of an algorithm.

12
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
NOTATIONS USED IN FLOWCHART
SYMBOL
NAME

Terminal Symbol

Input / Output Box

Process Box

Decision Box

Arrows

Connector

Off-Page Connector
13
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
EXAMPLE
Start

Input A

FLOWCHART Input B
ADD TWO NUMBERS

SUM = A + B

Display SUM

End

14
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
FLOWCHART
ADVANTAGES DISADVANTAGES

● Easier technique to understand logic ● Time consuming

● Easy to draw ● Difficult to modify

● Easy to identify logical errors ● Difficult to draw for huge programs

● Makes testing & debugging easier


15
TRANSLATORS
1. COMPILER

➢ Translates the whole program


➢ Detects all errors at once

2. INTERPRETER
➢ Translates line by line
➢ Detects errors in current line

16
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
THE C COMPILER
➢ The source code written in the source file is the human-readable version
of your program

➢ It needs to be “compiled” into machine language

➢ The compiler compiles the source code into final executable program

17
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
18
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
STRUCTURE OF A C PROGRAM

19
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
C PROGRAM STRUCTURE
A C program basically consists of the following parts
➢ Preprocessor Commands

➢ Functions

➢ Variables

➢ Statements & Expressions

➢ Comments

20
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
COMMENTS
➢ Used to explain code, make it more readable
➢ Prevent execution when testing alternative code
➢ Comments can be classified as follows :
■ Single - line
○ Starts with two forward slashes - //
■ Multi - line
○ Starts with /* and ends with */
21
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
EXAMPLE OF COMMENTS
➢ // This is a single line comment
printf(“HELLO WORLD !”);
➢ /*
This is a multi line comment :
This code will print the words HELLO WORLD ! to the screen
*/
printf(“HELLO WORLD!”);
22
CHARACTER SET
➢ Set of all valid characters that can be used in source program

to form words, expressions, etc.

➢ C provides support to about 256 characters

23
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
CHARACTER SET INCLUDES
1. Alphabetical Characters
➢ Uppercase Letters : A - Z
➢ Lowercase Letters : a - z
2. Digits
➢ 0-9

24
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
CHARACTER SET INCLUDES
3. Special Characters

➢ !, ", #, $, %, &, ', (, ), *, +, ,, -, . /', :, ;, <, =, >,

?, @, [, `, ], ^, _, `, {, |, }, ~

4. Whitespaces

➢ Blank Space
➢ New Line
➢ Tab 25
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
ASCII
AMERICAN STANDARD CODE FOR INFORMATION INTERCHANGE

➢ Used to represent characters in standardized way


➢ Every character is associated with a unique numerical value
➢ Like
● A = 65, B = 66 , ..
● a = 97 , b = 98 , ..
● 0 = 48 , 1 = 49 , ..
26
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
KEYWORDS IN C

➢ Keywords are reserved words

➢ They have a special meaning to the compiler

➢ They cannot be used as identifiers

27
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
KEYWORDS IN C
There are 32 keywords in C Language

28
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
IDENTIFIERS IN C
➢ Names used to identify variables, functions, etc.

➢ Rules for naming identifiers are as follows :

○ Must begin with a letter or underscore ( _ )

○ Can contain alphabets, digits or underscores

○ Case-sensitive

○ No special characters except underscore are allowed

○ No reserved words or keywords can be used

○ No white spaces are allowed 29


QUIZ
Determine if the following identifiers are valid or invalid according to
C programming rules .

1. _count 6. float

2. highScore 7. float_number_1

3. total_value_ 8. sum#

4. _number_ 9. number 1

5. 2ndNumber 10. intValue1_


30
QUIZ
Determine if the following identifiers are valid or invalid according to
C programming rules .
1. _count VALID 6. float INVALID

2. 2ndNumber INVALID 7. float_number_1 VALID

3. total_value_ VALID 8. sum# INVALID

4. number 1 INVALID 9. _number_1 VALID

5. highScore VALID 10. intValue1_ VALID


31
DATA TYPES IN C
➢ Used to specify the type of data a variable can hold

➢ Types are as follows :

○ Primary Data Types - int, float, char, double

○ Derived Data Types - arrays, pointers, structures, unions

○ User-defined Data Types - enum

32
PRIMARY DATA TYPES
1. INT
➢ Used to store integers ( both positive and negative )
➢ Each int variable takes upto 4 bytes of memory ( 32 bits )
➢ Int can be classified as :
a. Signed
○ Range : -2,147,483,648 to 2,147,483,647
b. Unsigned :
○ Range : 0 to 4,294,967,295
➢ short int ( 2 bytes )
➢ long int ( 8 bytes ) 33
PRIMARY DATA TYPES
2. FLOAT
➢ Used to store single precision floating-point numbers (decimals)
➢ Size : 4 bytes of memory ( 32 bits )
➢ Precision : 6 - 7 decimal digits

3. DOUBLE
➢ Size : 8 bytes
➢ Precision : 15 - 16 decimal digits
➢ long double ( 10, 12 or 16 bytes )
34
PRIMARY DATA TYPES
4. CHAR
➢ Used to store a single character
➢ Each char variable takes upto 1 byte of memory ( 8 bits )
➢ Char can be classified as :
a. Signed
○ Range : -128 to 127
b. Unsigned :
○ Range : 0 to 255

35
VARIABLES IN C

➢ Variable is a name of the memory location

➢ It is used to store data

➢ Its value can be changed

➢ It can be reused

36
TYPES OF VARIABLES IN C

1. LOCAL VARIABLES

➢ Definition : Declared inside a function or block

➢ Scope : Accessible only within that function or block

➢ Lifetime : Exist only during the execution of that function

or block
37
TYPES OF VARIABLES IN C

2. GLOBAL VARIABLES

➢ Definition : Declared outside of all functions, usually at top

➢ Scope : Accessible from any function within the program

➢ Lifetime : Exist for the entire duration of the program’s

execution
38
TYPES OF VARIABLES IN C
3. STATIC VARIABLES

➢ Definition : Declared with the ‘ static ’ keyword

➢ Scope : Accessible from

○ within the function or block ( STATIC LOCAL )

○ within the program ( STATIC GLOBAL )

➢ Lifetime : Retain their value between function calls, and exist

for the duration of the program 39


TYPES OF VARIABLES IN C
4. AUTOMATIC VARIABLES

➢ Variables that are automatically created and destroyed when a

block is entered or exited

➢ All variables declared inside a block ( LOCAL ) are automatic by

default

➢ Declared using ‘ auto ‘ keyword

40
TYPES OF VARIABLES IN C
5. EXTERNAL VARIABLES

➢ Variables declared outside of a function and intended to be

shared across multiple files

➢ Accessible from any file where it is declared using ‘ extern ‘

keyword

➢ Exist for the entire duration of the program


41
TYPES OF VARIABLES IN C

6. REGISTER VARIABLES

➢ Variables stored in CPU registers for faster access

➢ Local to block or function where they are declared

➢ Declared using ‘ register ‘ keyword

42
CONSTANTS IN C

➢ Fixed values that do not change during program execution

➢ Declared using ‘ const ‘ keyword

➢ Eg const int roll_no = 2026601 ;

43
SYMBOLIC CONSTANTS IN C

➢ Constants defined using ‘ #define ‘ directive

➢ Replaced by their definition before compilation

➢ Eg #define PI 3.14159 ;

➢ It improves code modifiability and understandability

44
OPERATORS IN C
➢ Symbols that tell the compiler to perform specific operations

➢ Operations are performed on variables and values

➢ Used to manipulate data

➢ Can control the flow of the program

➢ Values and variables used with operators are called operands


45
TYPES OF OPERATORS IN C
C operators can be classified into a number of categories :

1. Arithmetic Operators 5. Increment & Decrement Operators

2. Relational Operators
6. Conditional Operators
3. Logical Operators

7. Bitwise Operators
4. Assignment Operators

46
ARITHMETIC OPERATORS
1. + (Addition) : Adds two operands
2. - (Subtraction) : Subtracts the second operand from the first
3. * (Multiplication) : Multiplies two operands
4. / (Division) : Divides first operand by the second
The result is an integer if both operands are integers
5. % ( Modulus ) : Returns the remainder of the division

47
RELATIONAL OPERATORS
These operators compare two operands (values) and return either
‘ true ’ ( 1 ) or ‘ false ‘ ( 0 )

1. == ( Equal to ) : Checks if two operands are equal

2. != ( Not equal to ) : Checks if two operands are not equal

3. > ( Greater than ) : Checks if first operand is greater than second

48
RELATIONAL OPERATORS
These operators compare two operands (values) and return either
‘ true ’ ( 1 ) or ‘ false ‘ ( 0 )

4. < ( Less than ) : Checks if first operand is less than second

5. >= ( Greater than or equal to ) : Checks if first operand is greater than or


equal to second

6. <= ( Less than or equal to ) : Checks if first operand is less than or equal
to
second
49
LOGICAL OPERATORS
These operators are used to combine multiple conditions.
They are essential for decision making based on multiple criteria.

1. && ( AND ) : Returns ‘ true ‘ if both conditions are true

2. || ( OR ) : Returns ‘ true ‘ if atleast one conditions is true

3. ! ( NOT ) : Inverts the truth value of a single condition.

50
ASSIGNMENT OPERATORS
These operators are used to assign the value or result of an expression to a variable.

1. = ( Assign ) : Assigns the value of right-hand operand to the left

Shorthand Assignment Operators

2. += : Adds right operand to left and assigns result to the left operand

3. -= : Subtracts right operand from left and assigns result to left operand

4. *= : Multiplies right operand with left and assigns result to the left operand

5. /= : Divides left operand by right and assigns result to the left operand

6. %= : Takes modulus of left operand with right and assigns result to the left operand
51
INCREMENT & DECREMENT
OPERATORS
1. ++ ( INCREMENT ) : Increase the value of the operand by 1

i. Pre-increment (++a)

ii. Post-increment(a++)

2. -- ( DECREMENT ) : Decreases the value of the operand by 1

i. Pre-decrement (--a)

ii. Post-decrement (a--)


52
CONDITIONAL OPERATORS
This operator allows you to make decision within a single line of code.

condition ? expression_true : expression_false ;

• condition : expression to evaluate ( returns true or false )


• expression_true : value or expression that is executed if condition is true
• expression_false : value or expression that is executed if condition is false
53
BITWISE OPERATORS
These operators work on binary representation of int, performing operations bit by bit.

1. & ( Bitwise AND ) : Perform AND operation on corresponding bits of two integers

2. | ( Bitwise OR ) : Perform OR operation on corresponding bits of two integers

3. ^ ( Bitwise XOR ) : Perform XOR operation on corresponding bits of two integers

4. ~ ( Bitwise NOT ) : Flips all the bits of an integer, turning ‘1’ to ‘0’ and vice versa

5. << ( Left Shift ) : Shifts the bits of a number to the left by specified no. of positions

6. >> ( Right Shift ) : Shifts the bits of a number to the right by specified no. of positions

54
QUIZ
Determine whether the following statements are True or False.

1. The assignment operator = is used to compare two values in C.

2. The ++ operator increments the value of a variable by 1.

3. The expression 7 / 2 in C will return 3.5.

4. The << operator is used for left bitwise shifting in C.

5. The ! operator is used to negate a boolean expression in C.


55
QUIZ
Determine whether the following statements are True or False.

6. The | operator is used to perform logical OR operations.

7. In C, the expression 5 % 2 will return 2.

8. The && operator is used to perform bitwise AND operations in C.

9. The ! operator is used to negate a boolean expression in C.

10. The / operator performs integer division when both operands are integers.
56
LIBRARY FUNCTIONS
➢ Pre-defined functions provided by C libraries

➢ Simplify programming by providing reusable code

➢ Increase efficiency by using optimized and tested functions

➢ Save time by avoiding writing common functions from scratch

➢ Accessible by including the corresponding header files


57
EXAMPLES OF C LIBRARIES

➢ stdio.h : Standard Input and Output library.

➢ stdlib.h : Standard Library for general utilities.

➢ string.h : String handling library.

➢ math.h : Mathematical functions library.

➢ time.h : Date and time utility functions.

➢ ctype.h : Character handling functions. 58


FUNCTIONS IN “ STDIO.H ” LIBRARY
1. printf : Prints formatted output to the screen.

2. scanf : Reads formatted input from the keyboard.

3. fprintf : Prints formatted output to a file.

4. fscanf : Reads formatted input from a file.

5. getchar : Reads a single character from standard input.

6. putchar : Writes a single character to standard output.


59
FUNCTIONS IN “ MATH.H ” LIBRARY
1. sqrt : Calculates the square root of a number.

2. pow : Raises a number to a power.

3. sin, cos, tan : Trigonometric functions.

4. abs : Returns the absolute value of an integer.

5. fmod : Returns the remainder of x divided by y.

6. ceil : Rounds x up to the nearest integer.

7. floor : Rounds x down to the nearest integer.


60
FUNCTIONS IN “ CTYPE.H ” LIBRARY
1. isdigit : Checks if a character is a digit.

2. isalpha : Checks if a character is alphabetic.

3. isalnum : Checks if a character is alphanumeric.

4. toupper : Converts a character to uppercase.

5. tolower : Converts a character to lowercase.


61
FORMATTED INPUT / OUTPUT
➢ Handles input and output with specific formatting rules

➢ Uses specifiers like %d, %f, %s to control data representation

➢ Formatted Input Functions : scanf , fscanf

➢ Formatted Output Functions : printf , fprintf

➢ Performs error checking for format specifier mismatches


62
UNFORMATTED INPUT / OUTPUT
➢ Handles raw input and output without specific formatting

➢ No format specifiers needed

➢ Unformatted Input Functions : getchar , gets , fgets

➢ Unformatted Output Functions : putchar , puts , fputs

➢ Deals directly with data, often with minimal error checking


63
64
CONDITIONAL STATEMENTS

➢ Used to make decisions in a program.

➢ Execute specific blocks of code based on conditions.

➢ Control the flow of the program.

65
THE ‘ IF ’ STATEMENT
Executes a block of code if a specified condition is true.

SYNTAX

if (condition) {
// Code to execute if condition is true
} 66
EXAMPLE
if (score > 50) {
printf("You passed the exam.\n");
}
➢ The if statement checks if score > 50.

➢ If true, it prints "You passed the exam."

➢ If false, nothing happens.


67
EXAMPLE

DESIGN A C PROGRAM THAT CHECKS IF A CHARACTER IS A VOWEL.

68
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: "); // Asking user for input
scanf("%c", &ch);
// Check if the character is a vowel or consonant
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ) {
printf("%c is a vowel.\n", ch);
}
return 0;
} 69
THE ‘ IF - ELSE ’ STATEMENT
Provides an alternative block of code if the ‘ if ’ condition is false.

SYNTAX
if (condition) {
// Code to execute if condition is true
}
else {
// Code to execute if condition is false
} 70
EXAMPLE
if (score > 50) {
printf("You passed the exam.\n");
}
else {
printf("You failed the exam.\n");
}
➢ If score > 50, it prints "You passed the exam.
➢ If score <= 50, it prints "You failed the exam.
71
EXAMPLE

DESIGN A C PROGRAM THAT CHECKS IF A NUMBER IS DIVISIBLE BY 2.

72
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: "); // Asking user for input
scanf("%d", &number);
if (number % 2 == 0) { // Check if the number is divisible by 2
printf("%d is divisible by 2.\n", number);
} else {
printf("%d is not divisible by 2.\n", number); }
return 0; }
73
EXAMPLE

DESIGN A C PROGRAM THAT CHECKS IF A PERSON IS ELIGIBLE TO VOTE.

74
#include <stdio.h>
int main() {
int age; // Asking user for input
printf("Enter your age: ");
scanf("%d", &age);
if (age >= 18) { // Check if the person is eligible to vote
printf("You are eligible to vote.\n"); }
else {
printf("You are not eligible to vote.\n"); }
return 0; }
75
THE ‘ IF - ELSE LADDER’
SYNTAX
if (condition1) {
// Block of code executed if condition1 is true
} else if (condition2) {
// Block of code executed if condition1 is false and condition2 is true
} else if (condition3) {
// Block of code executed if conditions 1 and 2 are false and condition3 is true
} else {
// Block of code executed if none of the above conditions are true
} 76
EXAMPLE

DESIGN A C PROGRAM TO DETERMINE THE GRADE BASED ON A SCORE USING


AN IF-ELSE LADDER.

77
#include <stdio.h>
int main() {
int score;
printf("Enter your score: "); // Input the score
scanf("%d", &score);
if (score >= 90) { // Determine the grade using if-else ladder
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;
} 78
THE ‘ NESTED IF ’
SYNTAX
if (condition1) {
// Block of code executed if condition1 is true
if (condition2) {
// Block of code executed if condition1 and condition2 are true
} else {
// Block of code executed if condition1 is true and condition2 is false
}
} 79
EXAMPLE

DESIGN A C PROGRAM TO DETERMINE IF A STUDENT IS ELIGIBLE FOR A


SCHOLARSHIP BASED ON THEIR AVERAGE GRADE AND THEIR ATTENDANCE
PERCENTAGE.

80
#include <stdio.h>
int main() {
float averageGrade;
float attendance;
printf("Enter your average grade: "); // Input average grade
scanf("%f", &averageGrade);
printf("Enter your attendance percentage: "); //Input attendance percentage
scanf("%f", &attendance);
if (averageGrade >= 85) { // Check scholarship eligibility
if (attendance >= 75) {
printf("Congratulations! You are eligible for the scholarship.\n");
} else {
printf("You are not eligible for the scholarship due to insufficient attendance.\n");
}}
else {
printf("You are not eligible for the scholarship due to insufficient grades.\n");
}
return 0; } 81
SWITCH CASE
SYNTAX
switch (expression) {
case value1:
// Block of code executed if expression equals value1
break;
case value2:
// Block of code executed if expression equals value2
break;
default:
// Block of code executed if expression does not match any case
} 82
#include <stdio.h>
int main() {
int day;
printf("Enter a number (1-7) to get the day of the week: "); // Input day of the week as a number (1 to 7)
scanf("%d", &day);
switch (day) { // Determine the day of the week using switch statement
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; } 83
LOOPING STATEMENTS
Loops are used to execute a block of code repeatedly based on a
condition.

84
FOR LOOP
The for loop is used when you know in advance how many times
you want to execute a block of code.

SYNTAX
for (initialization ; terminatingCondition ; increment/decrement) {

// Block of code to be executed


}

85
EXAMPLE

DESIGN A C PROGRAM TO PRINT MULTIPLICATION TABLE FOR THE NUMBER 5


USING FOR LOOP.

86
#include <stdio.h>
int main() {
int i;
int number = 5;

// Loop to print the multiplication table for the number 5

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


printf("%d x %d = %d\n", number, i, number * i);
}
return 0;
}
87
WHILE LOOP
The while loop is used when the number of iterations is not known
and depends on a condition.

SYNTAX
while (condition) {
// Code to be executed
// Update condition variable
}
88
EXAMPLE

DESIGN A C PROGRAM TO FIND SUM OF N NATURAL NUMBERS


USING WHILE LOOP.

89
#include <stdio.h>
int main() {
int n, i = 1, sum = 0;
// Ask the user to input the value of N
printf("Enter a positive integer: ");
scanf("%d", &n);
while (i <= n) { // Using a while loop to calculate the sum
sum += i; // Add i to sum
i++; // Increment i
}
// Print the sum of first N natural numbers
printf("The sum of the first %d natural numbers is: %d\n", n, sum);
return 0;
} 90
DO - WHILE LOOP
The do-while loop is similar to while, but guarantees that the loop
executes at least once.

SYNTAX
do {
// Code to be executed
// Update condition variable
} while (condition);
91
EXAMPLE

DESIGN A C PROGRAM WHERE WE REPEATEDLY ASK THE USER TO ENTER A


NUMBER AND PRINT IT UNTIL THEY ENTER ZERO USING DO-WHILE LOOP.

92
#include <stdio.h>
int main() {
int number;
do { // Using do-while loop to print numbers until the user enters 0
printf("Enter a number (0 to quit): ");
scanf("%d", &number);
if (number != 0) {
printf("You entered: %d\n", number);
}
} while (number != 0); // Loop continues until the user enters 0
printf("You have exited the loop.\n");
return 0;
}
93
ENTRY CONTROL LOOP EXIT CONTROL LOOP

● The loop condition is checked before ● The loop condition is checked after
entering the loop body. executing the loop body.

● for loop, while loop ● do-while loop

● The loop body may not execute if the ● The loop body is executed at least
condition is false initially. once, regardless of the condition.

● Preferred when the number of ● Useful when the loop must execute at
iterations is uncertain or based on a least once, like user input validation.
condition. 94
NESTED LOOPS
➢ Nested Loop: A loop inside another loop.

➢ Types of Loops: Any loop can be nested inside another.

➢ Execution Flow: The inner loop completes all its iterations for

each iteration of the outer loop.


95
EXAMPLE
#include <stdio.h>
int main() { OUTPUT
int i, j; *
// Outer loop for rows **
for (i = 1; i <= 5; i++) { ***
// Inner loop for columns ****
for (j = 1; j <= i; j++) { *****
printf("* ");
}
printf("\n"); // Newline after each row
}
return 0;
}
96
JUMP STATEMENTS
➢ Break : Exits a loop or switch statement

➢ Continue : Skips the current iteration of a loop

➢ Goto : Jumps to a labeled statement

➢ Return : Exits a function and optionally returns a value

97
FUNCTIONS
➢ A block of code designed to perform a specific task.

➢ Functions help in dividing a large program into smaller and

manageable pieces of code.

➢ They enhance code reusability, readability, and

maintainability.

98
99
KEY ELEMENTS OF FUNCTIONS

➢ Function Declaration

➢ Function Definition

➢ Function Call

100
FUNCTION DECLARATION
➢ The function declaration informs the compiler about the function’s

name, return type, and parameters.

➢ It’s usually placed before the main() function.

➢ SYNTAX

return_type function_name(param_type1, param_type2,..);

101
FUNCTION DEFINITION
➢ The function definition contains the actual code or logic of the function.

➢ It includes the function body.

➢ SYNTAX

return_type function_name(param_type1 param1, param_type2 param2,.. ) {

// Function body (statements)

102
FUNCTION CALL

➢ A function call is used to execute the function.

➢ The arguments are passed in the parentheses.

➢ SYNTAX

function_name(argument1, argument2,..);

103
EXAMPLE

int add(int, int); // DECLARATION

int add(int a, int b) { // DEFINITION


return a + b;
}

int result = add(5, 3); // CALL

104
#include <stdio.h>

// Function declaration (prototype)


int sum(int a, int b);
EXAMPLE
int main() {
int num1, num2, result;
// Input two numbers from the user
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
// Function call to calculate the sum
result = sum(num1, num2);
// Display the result
printf("The sum of %d and %d is: %d\n", num1, num2, result);
return 0;
}

// Function definition
int sum(int a, int b) {
return a + b; // Returns the sum of a and b
}
105
CATEGORIES OF FUNCTIONS

➢ Functions with No Arguments and No Return Value

➢ Functions with Arguments but No Return Value

➢ Functions with No Arguments but Return Value

➢ Functions with Arguments and Return Value


106
RECURSION
➢ Recursion is a technique where a function calls itself to solve a problem.

➢ Recursion breaks down complex problems into smaller, manageable

subproblems of the same type.

➢ It consists of two main parts : a base case that stops the recursion and a

recursive case that continues calling the function with modified inputs.

➢ Recursion simplifies code, makes certain algorithms easier to implement


and understand.
107
EXAMPLE
int factorial (int n) {

if (n == 1) // Base case
{
return 1;
}
else
{
return n * factorial(n - 1); // Recursive case
}
}
108
#include <stdio.h>

int factorial(int); // function prototype

int factorial(int n) { // function definition


if (n == 1) { // base case
return 1;
} else { // recursive case
return n * factorial(n - 1);
}
}

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

printf("Factorial of %d is %d\n", num, factorial(num));

return 0;
}
109
ARRAYS
An array is a finite collection of homogeneous elements stored
in contiguous memory locations.

SYNTAX FOR ARRAY DECLARATION

data_type variable_name[ size ];

110
In C, you can declare and initialize an array as follows :

int numbers[5] = {10, 20, 30, 40, 50} ;

numbers

10 20 30 40 50
index 0 1 2 3 4

size = 5

111
TYPES OF ARRAYS

One - Dimensional Multi - Dimensional

112
STRINGS
➢ In C, array of characters terminated by a null character (‘\0’) is known as a string.

➢ The null character signifies the end of the string.

➢ char name[20]; /* Declares a character array that can hold up to 19 characters plus the null terminator */

➢ char name[6] = "Alice"; // Initialization

OR

char name[6] = {'A', 'l', 'i', 'c', 'e', '\0'};

OR

char name[] = "Alice"; // Automatically allocates space for 6 characters ('A', 'l', 'i', 'c', 'e', '\0') 113
FUNCTIONS IN “ STRING.H ” LIBRARY
1. strcat : Concatenates (appends) one string to the end of another.

2. strcpy : Copies one string into another.

3. strcmp : Compares two strings. It returns 0 if the strings are equal, a

negative value if the first string is less than the second, and a positive value

if the first string is greater.

4. strrev : used to reverse a string

5. strlen : Calculates the length of a string (excluding the null terminator '\0')
114
#include <stdio.h>
#include <string.h>

int main() {
char str1[100], str2[100], str3[100];

// Input strings
printf("Enter the first string: ");
gets(str1);
printf("Enter the second string: ");
gets(str2);

// 1. Compare two strings


if (strcmp(str1, str2) == 0) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}

// 2. Reverse the first string


strcpy(str3, str1); // Copy str1 into str3 to preserve the original
strrev(str3); // Reverse the string
printf("Reversed first string: %s\n", str3);

// 3. Copy second string to first string


strcpy(str1, str2);
printf("First string after copying second string: %s\n", str1);

// 4. Join (concatenate) two strings


strcat(str1, str2); // Concatenate str2 to str1
printf("Concatenated string: %s\n", str1);

return 0;
} 115
STRUCTURES
➢ A structure is a user-defined data type in C that allows the grouping of variables

of different data types under a single name.

➢ Structures are declared using the struct keyword followed by the structure name

and its members (variables).

➢ Each member of the structure occupies memory based on its data type. The total

memory used by the structure is the sum of the sizes of its members.

➢ Members of a structure are accessed using the dot (.) operator.

116
SYNTAX
struct structure_name {
data_type member1;
data_type member2;
// ...
};

EXAMPLE
struct Person {
char name[50];
int age;
float height;
};

struct Person p1 = {"John", 30, 5.9};


printf("Name: %s, Age: %d, Height: %.1f", [Link], [Link], [Link]);
117
UNIONS
➢ A union is a user-defined data type in C that allows storing different data types in the
same memory location, but only one member of the union can hold a value at any
given time.
➢ All members of a union share the same memory space, so the size of the union is
determined by the size of its largest member.
➢ Unions save memory since they allow multiple data types to use the same memory
location.
➢ Only one member can store a value at any given time. Assigning a value to one
member will overwrite the value of the previous member.
➢ Members of a union are accessed using the dot (.) operator, similar to structures.
118
SYNTAX
union union_name {
data_type member1;
data_type member2;
// ...
};

EXAMPLE
union Person {
char name[50];
int age;
float height;
};

union Person p;
[Link] = 25; // Accessing the 'age' member
119
STRUCTURE UNION

● Each member has its own memory ● All members share the same memory
location. location.

● The size of a structure is the sum of ● The size of a union is the size of its
the sizes of all its members. largest member.

● All members can store values ● Only one member can store a value at
independently at the same time. a time (others are overwritten).
120
POINTERS
➢ Pointers store the memory address of another variable.

➢ Declared using (*) and initialized with the address-of operator (&)

➢ Access the value at the pointed address using (*)

➢ Can navigate through memory by incrementing or decrementing.

121
SYNTAX
➢ DECLARATION

dataType * pointerName ;

➢ INITIALIZATION

pointerName = &variableName ;

➢ DEREFERENCING

* pointerName ;
122
POINTER TO POINTER
A pointer to a pointer is a variable that stores the

address of another pointer

int var = 10;

int *ptr = &var; // Pointer to int

int **pptr = &ptr; // Pointer to pointer to int


123
POINTER TO ARRAY
A pointer to an array is a pointer that points to the first element of

an array

int arr[5] = {1, 2, 3, 4, 5};


int *ptr = arr; // Points to the first element of arr
for (int i = 0; i < 5; i++) {
printf(“%d”, *ptr);
ptr ++; // Move the pointer to the next element in the array
} 124
POINTER TO STRUCTURE
A pointer that points to a structure

struct Person {
char name[20];
int age;
};
Person person = {"Alice", 30};
Person *ptr = &person; // ptr points to the structure instance
printf(“%s”,ptr->name); // Accesses the 'name' member of the structure
printf(“%d”,ptr->age); // Accesses the 'age' member of the structure
125
CALL BY VALUE CALL BY REFERENCE

● Directly pass the argument to the ● Pass the address of the argument
function. using pointers.
● A copy of the actual argument is ● The address (reference) of the actual
passed to the function. argument is passed to the function.
● The actual argument remains ● The actual argument can be changed.
unchanged. ● More efficient, as only the address
● Requires more memory as a copy of (pointer) of the argument is passed.
the argument is made. ● Changes made to the parameter in the
● Changes made to the parameter in function affect the original argument.
126
FILE HANDLING

127
128
129
130

You might also like