C Programming Notes for CAT-1
(CSE1022)
1. Key Learnings & Mistakes
- In C, `String` is not a data type (unlike Java). Strings are just `char` arrays, e.g., `char
name[50];`.
- To read a string: `scanf("%s", name);`
- To print a string: `printf("%s", name);`
- For copying strings, use `strcpy(dest, src)` from <string.h>, assignment (`=`) does not work
for strings.
- Passing 2D arrays: you must specify column size in the function declaration, e.g., `void
fun(int arr[][10], int row, int col)`.
- Mistake fixed: In loops, always read input with `scanf("%d", &arr[i][j]);` not `arr[row]
[col]`.
- For factorial-based series: returning `int` is fine if n is small, but large n can cause
overflow.
- Always increment counters (like `c++`) in both if/else blocks when alternating terms in
series.
- When using `sqrt` and other math functions: they return `double`.
Use `%lf` for printing double/float results. Example:
```c
double x = sqrt(16);
printf("%lf", x);
```
- `%d` → int, `%ld` → long int, `%f` → float, `%lf` → double.
2. Bitwise Operators
Common uses of bitwise operators in C:
- `&` (AND): Check if a number is odd/even. Example: `if (n & 1)` → odd.
- `|` (OR): Set a particular bit to 1.
- `^` (XOR): Toggle bits or check if two numbers differ.
- `~` (NOT): Flip all bits.
- `<<` (Left shift): Multiply by 2^k.
- `>>` (Right shift): Divide by 2^k (floor division for positive numbers).
3. Ternary Operator
Syntax: `condition ? expr1 : expr2;`
- If condition is true → expr1 is executed.
- Else → expr2 is executed.
Example:
```c
int n = 5;
printf("%s", (n % 2 == 0) ? "Even" : "Odd");
```
4. Switch Statement
Syntax:
```c
switch (expression) {
case 1:
// code
break;
case 2:
// code
break;
default:
// code
}
```
- `switch` is like multiple if-else.
- `break` is required to exit a case; otherwise, execution continues to the next case (fall-
through).
- Only works with integer and character constants (not float or strings).
5. Operator Precedence in C
Order of precedence (highest to lowest):
1. `()` `[]` `->` `.`
2. Postfix `++` `--`
3. Prefix `++` `--`, unary `+` `-`, `!`, `~`, typecast `(type)`, `sizeof`, `*` (dereference), `&`
(address-of)
4. `*` `/` `%`
5. `+` `-`
6. `<<` `>>`
7. `<` `<=` `>` `>=`
8. `==` `!=`
9. `&`
10. `^`
11. `|`
12. `&&`
13. `||`
14. `?:` (ternary)
15. Assignment operators `=`, `+=`, `-=`, etc.
16. `,` (lowest)
6. Important Questions to Practice
✅ Q3: Sort N student names alphabetically ignoring case.
✅ Q6: Series for cos(x).
✅ Q9: Complete the function to print all elements except diagonal.
✅ Q12: Rotate a square matrix 90° clockwise in place.
✅ Q15: Compute secondary diagonal sum and border sum.
Other good practice: Q1 (Perfect Number), Q7 (switch with bitwise/ternary), Q8
(recursion), Q18 (Armstrong), Q19 (sin series), Q24 (reverse array with swap).