Docsity

c language notes for btech, Slides of Programming Languages

Toggle sidebar
bg1
B E G I N N E R F R I E N D L Y | E X A M P L E D R I V E N | I N T E R V I E W R E A D Y
C Programming
The Complete Guide
Every topic explained in the simplest possible way, with step-by-step example programs, dry-run
tables, 45 interview questions with answers, output-prediction puzzles and a quick revision cheat
sheet.
18 Chapters | 90+ Solved Programs | 45 Interview Q&As
Basics - Operators - Decisions - Loops - Arrays - Strings - Functions - Pointers - Structures - Dynamic Memory - Files -
Preprocessor - Practice Set - Interview Prep
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d

Partial preview of the text

Download c language notes for btech and more Slides Programming Languages in PDF only on Docsity!

B E G I N N E R F R I E N D L Y | E X A M P L E D R I V E N | I N T E R V I E W R E A D Y

C Programming

The Complete Guide

Every topic explained in the simplest possible way, with step-by-step example programs, dry-run

tables, 45 interview questions with answers, output-prediction puzzles and a quick revision cheat

sheet.

18 Chapters | 90+ Solved Programs | 45 Interview Q&As

Basics - Operators - Decisions - Loops - Arrays - Strings - Functions - Pointers - Structures - Dynamic Memory - Files - Preprocessor - Practice Set - Interview Prep

W E L C O M E

About This Guide

This guide was written for one purpose: to make C feel easy. Every topic starts from zero, uses simple

everyday analogies (boxes, lockers, house addresses), shows a small program, and then shows the exact

output of that program, so you are never left guessing.

You do not need any programming background. Just read the chapters in order, type the programs on a

computer (or an online compiler), and try changing small things to see what happens. That is how

programming is truly learnt.

Box What it means

OUTPUT The exact output the program prints on the screen.

REMEMBER A short rule or warning that saves you from mistakes.

INTERVIEW FOCUS Questions from that topic that are asked again and again in job/campus interviews.

Dry-run tables Step-by-step trace of how the computer executes a loop or a program.

At the end you get three bonus chapters: Chapter 16 (a solved practice set of the most famous C

programs), Chapter 17 (45 interview questions with simple answers, output puzzles, and coding-round

favourites) and Chapter 18 (a one-look cheat sheet + a 7-day study plan).

REMEMBER

Do not try to memorise C. Understand each small program by dry-running it on paper - write the variable

names on paper and update their values line by line. After a few days of this, C logic becomes automatic.

C H A P T E R 01

1. Introduction to C

Before writing a single line of code, let us understand what C is, where it came from, and how your words

become something a computer can actually run.

1.1 What is C?

A computer is a machine. To give it instructions, we need a language it can work with. C is a

programming language - a way for humans to write instructions that a computer can execute, very fast.

C was created in 1972 by Dennis Ritchie at Bell Laboratories (USA). He built it mainly to write the UNIX

operating system. That one decision made C one of the most important languages in history.

Think of C as the mother language of programming. C++, Java, JavaScript, Python and C# all borrowed

their core ideas (variables, loops, functions, data types) from C. Learn C well once, and every other

language feels like C with extra features.

1.2 Why should you learn C?

  • It is very fast. C programs run almost as fast as the machine allows, because C sits close to the

hardware.

  • It runs the world. Operating systems (Linux kernel, parts of Windows), car systems, washing

machines, ATMs, robots, games and databases (like MySQL) are written in C or C++.

  • It builds your logic. C makes you think about memory and step-by-step logic - exactly the muscle you

need for coding tests and interviews.

  • It is asked in interviews. Pointers, arrays, strings and output questions from C are classics in campus

placements and job interviews.

1.3 Features of C

Feature Simple meaning

Simple Only 32 keywords (reserved words) in the original C - small language, easy to master.

Fast Compiled directly to machine code; almost no wasted time while running.

Portable The same program can be compiled and run on Windows, Linux, Mac with little or no change.

Structured Big programs are broken into small functions, like chapters in a book.

Low-level access C lets you directly work with memory addresses (pointers) when you need to.

Rich library Hundreds of ready-made functions (printing, maths, strings, files) come bundled with it.

1.4 What is a compiler? (in simple words)

A computer understands only machine language - long patterns of 0s and 1s. Humans cannot practically

write in 0s and 1s. So we need a translator:

A compiler is a program that translates your entire C program (called the source code ) into machine code

(0s and 1s) in one go. The translated file is called an executable (a.out on Linux, .exe on Windows).

Double-click that file and your program runs.

Popular C compilers: GCC (free, on Linux/Code::Blocks), Clang (on Mac), MSVC (Microsoft Visual Studio).

Old colleges still use Turbo C - the language is the same, only the tool is older.

1.5 Your first C program

#include /* 1. bring in the input/output tools */

int main() /* 2. the program starts running here / { printf("Hello, World!\n"); / 3. print a message on the screen */

return 0; /* 4. tell the OS: program finished OK */ }

OUTPUT

Hello, World!

Four lines, four ideas. Here is what each part means:

Part What it does

#include Copies the "standard input-output header" into your file. It contains printf and scanf. Without it, the compiler does not know what printf is.

int main() Every C program must have exactly one main function. Execution always begins here. int says main will return a whole number when it ends.

{ } The curly braces mark the beginning and end of main's body. All instructions live inside them.

printf("...") Prints whatever is inside the double quotes on the screen. \n means "go to a new line".

return 0; Returns 0 to the operating system, which is the code for "everything went fine". Any other number usually means some error happened.

REMEMBER

Read a C program like plain English: "Include standard input-output. Start main. Print hello. Return zero

(all OK)." Every C program you ever write is just a bigger version of this same shape.

1.6 What happens when you press "Run"?

One press of Run actually hides four steps. Knowing them is a common interview question:

Step Who does it What happens Output file

  1. Preprocessing Preprocessor Removes comments, expands #include and #define (Chapter 14).

file.i

  1. Compilation Compiler Checks your code for errors and translates it into assembly language.

file.s

  1. Assembly Assembler Converts assembly into machine code (object code).

file.o

  1. Linking Linker Joins your object code with library code (e.g. the real code of printf) into one executable.

a.out / prog.exe

You normally never see these steps - the compiler runs them all automatically. But now you know the

secret behind "Run".

C H A P T E R 02

2. Variables, Constants & Data Types

Programs are all about storing values, changing values and using values. This chapter teaches you where

and how C stores data.

2.1 What is a variable?

Imagine the computer's memory as a huge wall of numbered boxes. A variable is one box that you give a

name to, so you can put a value inside it and read it back later.

int age = 20; /* a box named "age" of type int, holding 20 / age = 21; / the box now holds 21 - that is why it is called a VARIABLE */

One line of declaration has three parts:

Part Example Meaning

Type int What kind of value the box can hold (whole number here) and how big the box is.

Name age The label on the box. You use this name in the rest of the program.

Value 20 What is inside the box right now.

Related words you must know: declaration (int age; - creates the box, value unknown), initialization

(age = 20; - puts the first value in), and definition (declaration + initialization together: int age =

2.2 Rules for naming variables (identifiers)

Rule Valid example Invalid example

Can contain letters, digits and underscore _ only. total_1 total-1, total 1

Must start with a letter or underscore. _sum, sum2 2sum

Cannot be a C keyword (a reserved word). roll_no int, float, return

No spaces allowed. my_age my age

Case-sensitive: Total and total are two different variables.

Total, total (both valid, but confusing!)

REMEMBER

Give meaningful names: marks is better than m. In interviews and real projects, readable names matter a

lot.

2.3 Data types - choosing the right box

A data type tells the compiler two things: how much space the box takes in memory and what kind of

values it can hold.

Type Typical size What it stores Example Format specifier

char 1 byte One character (letter, digit, symbol) 'A' %c

Type Typical size What it stores Example Format specifier

int 4 bytes Whole numbers: -2,147,483,648 to +2,147,483,

100 %d

float 4 bytes Decimal numbers with about 6- digits of precision

3.14f %f

double 8 bytes Decimal numbers with about 15 digits of precision

3.141592653 %lf

void no size "Nothing" - used for functions that return no value

void menu() -

Sizes can differ slightly between machines. Do not memorise blindly - ask the compiler with the sizeof

operator:

#include

int main() { printf("char : %zu byte\n", sizeof(char)); printf("int : %zu bytes\n", sizeof(int)); printf("float : %zu bytes\n", sizeof(float)); printf("double : %zu bytes\n", sizeof(double)); return 0; }

OUTPUT

char : 1 byte int : 4 bytes float : 4 bytes double : 8 bytes

2.4 Type modifiers

Modifiers resize the basic boxes: short (smaller), long (bigger), signed (allows negative, default),

unsigned (only zero and positive - doubles the positive range).

Type Typical size Range (typical) Format

short int 2 bytes -32,768 to 32,767 %hd

long int 4 or 8 bytes about +2 billion (or much more) %ld

long long 8 bytes about +9.2 quintillion %lld

unsigned int 4 bytes 0 to 4,294,967,295 %u

2.5 Constants - boxes that cannot change

A constant is a value that never changes while the program runs. Two ways to make one:

#define PI 3.14159 /* way 1: preprocessor constant (Chapter 14) */

const float MAX = 100.0f; /* way 2: const keyword - compiler protected */

MAX = 200.0f; /* ERROR! cannot change a const */

REMEMBER

Want an exact decimal answer from division? Make sure at least one side is a float - either cast it

(float)a / b, or write one value as 7.0 / 2.

2.8 Overflow - when a box is too small

A signed char can hold only up to 127. If you add 1 to 127, the value "overflows" and (on most

machines) wraps around to -128. Every type has a maximum; crossing it gives wrong results silently. That

is why long long exists for big numbers.

INTERVIEW FOCUS

From this chapter: sizes of data types (char=1, int=4, float=4, double=8 typically) - difference

between declaration and definition (declaration announces a name; definition allocates memory and/or

assigns value) - what is ASCII? (a numbering scheme for characters; 'A'=65) - what is typecasting?

(converting one data type into another, implicitly by C or explicitly by you) - what happens on 7/2 and

7.0/2? (3 and 3.5).

C H A P T E R 03

3. Operators

Operators are the "action words" of C - symbols that do work on values. Master these and you can express

any calculation in one line.

An operator is a symbol that performs an operation. The values it works on are called operands. In a +

b, + is the operator and a, b are the operands.

3.1 Arithmetic operators

Operator Name Example (a=17, b=5) Result

  • Addition a + b 22
  • Subtraction a - b 12
  • Multiplication a * b 85

/ Division a / b 3 (decimal part cut!)

/ Division (float) 17.0 / 5 3.

% Modulus (remainder) a % b 2

#include

int main() { int a = 17, b = 5; printf("Sum = %d\n", a + b); printf("Product = %d\n", a * b); printf("Quotient = %d\n", a / b); /* 3 - int division / printf("Remainder = %d\n", a % b); / 2 */ return 0; }

OUTPUT

Sum = 22 Product = 85 Quotient = 3 Remainder = 2

REMEMBER

% gives the remainder and works only with integers (fmod() in is for floats). It is the king of

number puzzles: last digit = n % 10 , even/odd test = n % 2 , and divisibility checks all use it.

3.2 Increment (++) and decrement (--)

i++ and ++i both add 1 to i. The difference is when the increase happens:

#include

int main() { int a = 5; printf("%d\n", a++); /* prints 5 FIRST, then a becomes 6 (post) / printf("%d\n", a); / prints 6 */

A B A && B A || B

0 (false) 1 (true) 0 1

1 (true) 0 (false) 0 1

1 (true) 1 (true) 1 1

A shortcut worth knowing: in A && B, if A is false, C does not even check B (the answer must be false

anyway). This is called short-circuit evaluation.

3.5 Assignment operators

x = x + 5 is so common that C gives it a shortcut x += 5. This works for every arithmetic operator: -=,

*=, /=, %=, and even for bitwise &=, |=, <<=.

int x = 10; x += 5; /* x = 15 / x -= 3; / x = 12 */ x = 2; / x = 24 / x /= 4; / x = 6 / x %= 4; / x = 2 */

3.6 Bitwise operators (working with 0s and 1s)

Every value in memory is actually a pattern of bits. Bitwise operators work on those bits directly. Example

values: 12 is 1100 in binary and 10 is 1010.

Operator Name Example Result Rule

& AND 12 & 10 8 bit is 1 only if both bits are 1

| OR 12 | 10 14 bit is 1 if any bit is 1

^ XOR 12 ^ 10 6 bit is 1 if bits are different

~ NOT ~12 -13 flips every bit (0 to 1, 1 to 0)

<< left shift 12 << 2 48 shift bits left = multiply by 2 (per shift)

>> right shift 12 >> 2 3 shift bits right = divide by 2 (per shift)

#include

int main() { int n = 14; if (n & 1) /* check the LAST bit: 1 = odd, 0 = even */ printf("Odd\n"); else printf("Even\n");

printf("%d\n", 5 << 1); /* 10 - shifting left once doubles it */ return 0; }

OUTPUT

Even 10

REMEMBER

Interview favourites: n & 1 tests even/odd, n << 1 doubles, n >> 1 halves, x ^ y ^ y gives back x

(this is the base of the XOR swap trick in Chapter 16).

3.7 Other important operators

  • Ternary? : - a one-line if/else: max = (a > b)? a : b; reads as "if a > b then a else b".
  • sizeof - tells the size of a type or variable in bytes: sizeof(int) is 4 on most machines.
  • & (address-of) - gives the memory address of a variable (star of Chapter 10).
  • Comma , - evaluates left to right, keeps the rightmost value: x = (1, 2, 3); puts 3 in x. Rarely

useful, sometimes asked.

3.8 Operator precedence (who runs first?)

Just like maths (multiplication before addition), C has a fixed order. Highest first:

Priority Operators Note

1 (highest) ( ) [ ]. -> ++ -- (postfix) brackets and postfix first

2! ~ ++ -- (prefix) - (unary) * (deref) & (address) sizeof (type) cast

all unary operators

3 * / % multiplication family

4 + - addition family

5 << >> shifts

6 < <= > >= comparison

7 == != equality

8 & bitwise AND

9 ^ bitwise XOR

10 | bitwise OR

11 && logical AND

12 || logical OR

13? : ternary

14 = += -= *= ... assignment (lowest!)

REMEMBER

When in doubt, use brackets. (a + b) * c is always clearer than remembering rules, and brackets

never hurt performance.

INTERVIEW FOCUS

From this chapter: ++i vs i++ (pre: increase then use; post: use then increase) - = vs == (assign vs

compare) - what does % return? (remainder of integer division) - & vs && (bitwise AND vs logical AND) -

why does 7/2 give 3? (integer division cuts the decimal) - what does n & 1 do? (tests the last bit:

odd/even check).

4.2 Making output look neat

Format Meaning Example output

%5d right-align in width 5 ' 12'

%-5d left-align in width 5 '12 '

%05d pad with zeros up to width 5 '00012'

%8.2f width 8 total, 2 decimals ' 12.50'

%.1f exactly 1 decimal 3.14159 gives 3.

4.3 Escape sequences - special characters inside quotes

Escape Meaning

\n new line (Enter key)

\t tab space (about 8 columns)

\ a real backslash \

" a double quote inside a string

' a single quote, useful in 'It's'

\0 the NULL character - secret end marker of every string

4.4 scanf - reading from the user

scanf reads what the user types and stores it into a variable. It has one golden rule: give it the ADDRESS

of the variable, using & - because it needs to know where to put the value (which box to fill).

#include

int main() { int a, b, sum;

printf("Enter two numbers: "); scanf("%d %d", &a, &b); /* &a = "address of a" */

sum = a + b; printf("Sum = %d\n", sum); return 0; }

OUTPUT

Enter two numbers: 12 30 Sum = 42

REMEMBER

Forgetting & in scanf is the #1 cause of sudden crashes for beginners. The program then writes the value

to a garbage address. Compiler warnings catch it - never ignore warnings.

4.5 Reading a character - the newline trap

When you press Enter, that Enter itself stays in the keyboard buffer as a \n character! If you read a %d first

and then a %c, the %c happily eats that leftover \n and your program seems to "skip" the character input.

The fix is beautiful: put a space before %c - scanf(" %c", &ch) - the space tells scanf to skip any

leftover whitespace first.

#include

int main() { int age; char grade;

printf("Enter age: "); scanf("%d", &age);

printf("Enter grade: "); scanf(" %c", &grade); /* note the SPACE before %c */

printf("age=%d grade=%c\n", age, grade); return 0; }

OUTPUT

Enter age: 20 Enter grade: A age=20 grade=A

4.6 Reading text (strings)

scanf("%s", ...) reads only one word - it stops at the first space. To read a full line with spaces, use

fgets (safe) - gets() also reads lines but is so dangerous it has been removed from the C standard.

#include

int main() { char name[30];

printf("Enter full name: "); fgets(name, sizeof(name), stdin); /* reads the whole line */

printf("Hello, %s", name); /* fgets keeps the \n, so no \n needed */ return 0; }

OUTPUT

Enter full name: Asha Raman Hello, Asha Raman

Two smaller tools: getchar() reads exactly one character, putchar(ch) prints exactly one character:

char ch = getchar(); /* waits for one keypress + Enter / putchar(ch); / prints that character */

C H A P T E R 05

5. Decision Making (if, if-else, switch)

Real programs constantly make decisions: pass or fail, debit or credit, menu choice. C decides with if-else

and switch.

5.1 The simple if

if runs a block of code only when a condition is true. In C, any non-zero value is true and zero is false.

if (marks >= 40) { printf("Pass\n"); }

If the condition is false, the block is simply skipped and the program continues below.

5.2 if-else and the else-if ladder

#include

int main() { int marks = 78;

if (marks >= 90) printf("Grade A\n"); else if (marks >= 75) printf("Grade B\n"); else if (marks >= 60) printf("Grade C\n"); else if (marks >= 40) printf("Grade D\n"); else printf("Fail\n");

return 0; }

OUTPUT

Grade B

The ladder is checked from top to bottom , and the moment one condition is true, that block runs and the

whole ladder is exited - even if later conditions would also be true. Here 78 fails >= 90 , passes >= 75 ,

prints "Grade B" and stops.

REMEMBER

Order matters! If you wrote if (marks >= 40) first, a 78 student would wrongly get "Grade D". In

ladders, put the strictest condition on top.

5.3 Nested if - an if inside an if

#include

int main() { int a = 12, b = 45, c = 23, big;

if (a >= b) { if (a >= c) big = a; /* a >= b and a >= c / else big = c; / c > a >= b / } else { if (b >= c) big = b; / b > a and b >= c / else big = c; / c > b > a */ }

printf("Largest = %d\n", big); return 0; }

OUTPUT

Largest = 45

5.4 switch - the menu expert

When you compare one variable against many fixed values , switch is cleaner than a long if-else

ladder. It works with int and char only (not float, not strings in C).

#include

int main() { int day = 3;

switch (day) { 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; default: printf("Weekend!\n"); } return 0; }

OUTPUT

Wednesday

  • switch (x) - the variable being checked. Must be an integer or character type.
  • case value: - "if x equals this value, start here".
  • break; - leaves the switch immediately. Forget it and execution falls into the next case (see below).