? Error Handling in C-1
? Error Handling in C-1
Types of Errors in C:
1. Syntax Errors
o Occur when rules of the language are violated.
o Detected at compile time.
o Example: Missing semicolon int a = 10
2. Runtime Errors
o Occur while the program is executing.
o Often caused by invalid operations (e.g., division by zero).
o Example: int a = 10 / 0;
3. Logical Errors
o Program compiles and runs but gives incorrect results.
o Caused by incorrect formula or logic.
o Example: area = 3.14 * r + r; // wrong formula
for circle area
Debugging Techniques:
BUILT-IN FUNCTIONS
Math Functions (from <math.h>)
Example:
#include <ctype.h>
printf("%c", toupper('a')); // Output: A
FUNCTIONS IN C
Calling a Function:
Parameter Passing:
1. Call by Value
o Copies the actual value
o Changes don’t affect original
o Default in C
2. Call by Reference (using pointers)
o Passes the address
o Changes affect original
Scope of Variables:
1. Local – declared inside function/block.
2. Global – declared outside all functions.
Example:
int square(int n) {
return n * n;
}
Recursion in C
Types of Recursion:
void tail(int n) {
if (n == 0) return;
printf("%d ", n);
tail(n - 1);
}
Non-Tail (Head) Recursion – Recursive call happens before other statements
void head(int n) {
if (n == 0) return;
head(n - 1);
printf("%d ", n);
}
void direct(int n) {
if (n <= 0) return;
printf("%d ", n);
direct(n - 1);
}
// Factorial
int fact(int n) {
if (n == 0) return 1;
return n * fact(n - 1);
}
// Fibonacci
int fib(int n) {
if (n == 0 || n == 1) return n;
return fib(n - 1) + fib(n - 2);
}
// Perfect number
int sumDiv(int n, int i) {
if (i == 1) return 1;
if (n % i == 0) return i + sumDiv(n, i - 1);
else return sumDiv(n, i - 1);
}
ARRAYS
One-Dimensional Arrays:
• Traverse:
for (int i = 0; i < 5; i++) printf("%d ", arr[i]);
• Linear Search:
• Bubble Sort:
Two-Dimensional Arrays:
• Matrix Addition:
• Matrix Multiplication:
for(i=0;i<2;i++)
for(j=0;j<2;j++)
for(k=0;k<2;k++)
C[i][j] += A[i][k] * B[k][j];
Multidimensional Arrays:
SCOPE OF VARIABLES
Storage Classes:
Example:
void func() {
static int count = 0;
count++;
printf("%d ", count);
}
typedef
Macros
#define PI 3.14
#define AREA(r) (PI * (r) * (r))
Advantages of Designators in C
1️⃣ Direct Index Initialize a specific index directly int a[] = {[5] =
Assignment without filling earlier values. 10};
2️⃣ Skipping Unused Unused elements are default- int a[] = {[3] =
Elements initialized to 0, so you can skip 7};
them easily.
3️⃣ Improved Code Makes code more readable, struct P p = {.y
Clarity especially for structs and large = 2, .x = 1};
arrays.
4️⃣ Order Doesn't You can initialize elements in any int a[] = {[2] =
Matter order, not just sequentially. 4, [0] = 1};
5️⃣ Perfect for Useful when only a few values are int data[1000] =
Sparse Arrays needed in a large array. {[999] = 1};