Problem Solving Using C NVG
Problem Solving Using C NVG
ALGOL BCPL B C
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
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.
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
12
PCTE INSTITUTE OF ENGINEERING & TECHNOLOGY
NOTATIONS USED IN FLOWCHART
SYMBOL
NAME
Terminal Symbol
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
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
➢ 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
➢ 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
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
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.
○ Case-sensitive
1. _count 6. float
2. highScore 7. float_number_1
3. total_value_ 8. sum#
4. _number_ 9. number 1
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
➢ It can be reused
36
TYPES OF VARIABLES IN C
1. LOCAL VARIABLES
or block
37
TYPES OF VARIABLES IN C
2. GLOBAL VARIABLES
execution
38
TYPES OF VARIABLES IN C
3. STATIC VARIABLES
default
40
TYPES OF VARIABLES IN C
5. EXTERNAL VARIABLES
keyword
6. REGISTER VARIABLES
42
CONSTANTS IN C
43
SYMBOLIC CONSTANTS IN C
➢ Eg #define PI 3.14159 ;
44
OPERATORS IN C
➢ Symbols that tell the compiler to perform specific operations
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 )
48
RELATIONAL OPERATORS
These operators compare two operands (values) and return either
‘ true ’ ( 1 ) or ‘ false ‘ ( 0 )
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.
50
ASSIGNMENT OPERATORS
These operators are used to assign the value or result of an expression to a variable.
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++)
i. Pre-decrement (--a)
1. & ( Bitwise AND ) : Perform AND 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.
10. The / operator performs integer division when both operands are integers.
56
LIBRARY FUNCTIONS
➢ Pre-defined functions provided by C libraries
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.
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
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
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
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
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) {
85
EXAMPLE
86
#include <stdio.h>
int main() {
int i;
int number = 5;
SYNTAX
while (condition) {
// Code to be executed
// Update condition variable
}
88
EXAMPLE
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
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.
● 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.
➢ Execution Flow: The inner loop completes all its iterations for
97
FUNCTIONS
➢ A block of code designed to perform a specific task.
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
➢ SYNTAX
101
FUNCTION DEFINITION
➢ The function definition contains the actual code or logic of the function.
➢ SYNTAX
102
FUNCTION CALL
➢ SYNTAX
function_name(argument1, argument2,..);
103
EXAMPLE
104
#include <stdio.h>
// Function definition
int sum(int a, int b) {
return a + b; // Returns the sum of a and b
}
105
CATEGORIES OF FUNCTIONS
➢ 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.
if (n == 1) // Base case
{
return 1;
}
else
{
return n * factorial(n - 1); // Recursive case
}
}
108
#include <stdio.h>
int main() {
int num;
return 0;
}
109
ARRAYS
An array is a finite collection of homogeneous elements stored
in contiguous memory locations.
110
In C, you can declare and initialize an array as follows :
numbers
10 20 30 40 50
index 0 1 2 3 4
size = 5
111
TYPES OF ARRAYS
112
STRINGS
➢ In C, array of characters terminated by a null character (‘\0’) is known as a string.
➢ char name[20]; /* Declares a character array that can hold up to 19 characters plus the null terminator */
OR
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.
negative value if the first string is less than the second, and a positive value
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);
return 0;
} 115
STRUCTURES
➢ A structure is a user-defined data type in C that allows the grouping of variables
➢ Structures are declared using the struct keyword followed by the structure name
➢ 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.
116
SYNTAX
struct structure_name {
data_type member1;
data_type member2;
// ...
};
EXAMPLE
struct Person {
char name[50];
int age;
float height;
};
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 (&)
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
an array
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