Programming in C Language
8.1 Introduction to Programming Languages
Q 8.1.1: What is a computer
program?
- Answer:
A program is a set of instructions that tells the computer what to do
step-by-step to solve a problem.
Q 8.1.2: Program syntax vs semantics?
- Syntax:
Rules of writing code (spelling, brackets, semicolons).
- Semantics:
Meaning of the code (what the code actually does).
Q 8.1.3: Levels of programming languages
- Low
level:
- Machine
language: 0s and 1s; hardware understands it directly.
- Assembly
language: Short codes like MOV, ADD; needs an assembler.
- High
level:
- Procedural:
Step-by-step procedures (C, Pascal).
- Structured:
Uses blocks, selection, loops (C).
- Object-oriented:
Uses objects/classes (C++, Java).
Q 8.1.4: Features of high-level languages
- Easy
to read/write, portable (runs on many machines with a compiler), faster
development, fewer hardware details.
Q 8.1.5: Assembler vs Compiler vs Interpreter
- Assembler:
Converts assembly → machine code.
- Compiler:
Converts whole source code → machine code at once (e.g., C).
- Interpreter:
Runs code line-by-line (e.g., Python). Slower but easier to test.
8.2 Programming Environment Q 8.2.1: What is an IDE?
- Answer:
An IDE (Integrated Development Environment) is software that gives editor,
compiler, debugger, and tools in one place.
Q 8.2.2: Common IDE menus (what they do)
- File:
New, Open, Save, Exit.
- Edit:
Cut, Copy, Paste, Undo/Redo.
- Search:
Find/Replace text.
- Compile/Build:
Turn code into an executable.
- Debug:
Run with breakpoints, watch variables.
- Project:
Manage multiple files.
- Options/Settings:
Change fonts, compiler settings.
- Window:
Arrange open files.
- Help:
Docs and shortcuts.
8.3 Programming Basics
Q 8.3.1: What are header files?
- Answer:
Files that contain declarations for functions you use. Example: stdio.h
for printf/scanf.
Q 8.3.2: Structure of a C program
- Preprocessor
directives: #include, #define
- main()
function: starting point
- Body:
statements inside { }
- Variables:
global (outside functions) and local (inside a function/block)
Example:
#include <stdio.h> //
preprocessor
#define PI 3.14 // macro
int main() { // main
function
int r = 2; // local variable
float area = PI * r * r;
printf("Area =
%.2f\n", area);
return 0;
}
Q 8.3.3: Purpose of comments
- Explain
code for humans; compiler ignores them.
- Single-line:
// this is a comment
- Multi-line:
/* comment */
8.4 Constants and Variables Q 8.4.1: Constant vs Variable
- Variable:
value can change (int age = 15;).
- Constant:
value cannot change (const float PI = 3.14;).
Q 8.4.2: Rules for variable names
- Only
letters, digits, underscore; cannot start with a digit; no spaces; no
keywords; case-sensitive.
Q 8.4.3: Basic C data types (typical sizes on 32-bit/64-bit compilers;
may vary)
- int:
4 bytes
- float:
4 bytes
- char:
1 byte
- long
int: 4 or 8 bytes (often 8 on 64-bit) Note: Use sizeof(type) in your
compiler to confirm.
Q 8.4.4: Declare and initialize variables and constants
#include <stdio.h>
int main() {
int count = 10; // variable
float price = 99.50;
char grade = 'A';
long int big = 100000L;
const float PI = 3.14159; //
constant
printf("%d %.2f %c %ld
%.2f\n", count, price, grade, big, PI);
return 0;
}
Q 8.4.5: Implicit vs explicit type casting
🟢 What is Typecasting in C?
Typecasting means changing the data type of a variable from one type to another.
For example:
Converting an
int(integer) into afloat(decimal number).Converting a
charinto anint, etc.
🟡 Types of Typecasting
1. Implicit Typecasting (Type Conversion / Type Promotion)
Done automatically by the compiler.
Smaller data types are automatically converted into larger data types to avoid data loss.
Example:
Here,
10becomes10.0automatically.
2. Explicit Typecasting
Done manually by the programmer.
You write the type in front of the value/variable you want to convert.
Example:
Here,
10.5becomes10(decimal part is removed).
🔵 C Program for Both Implicit & Explicit Typecasting
🟣 Output of the Program
✅ So the difference is:
Implicit → compiler does it automatically.
Explicit → programmer does it manually by writing
(type)before the variable.
Section 9: Fundamentals of Input and Output
9.1 Input and Output Functions in C
Q 9.1.1: Output with putchar, puts, printf
In C programming, there are many ways to display text (output) on the screen. Three common ones are:
putchar()→ prints one character at a time.puts()→ prints an entire string (sentence or word), and automatically goes to a new line.printf()→ the most powerful, can print characters, words, numbers, variables, and formatted output.
1. putchar()
👉 Think of putchar() as writing one letter at a time.
It can only display a single character.
Example:
Output:
📌 Notice: 'A' and 'B' are in single quotes because they are characters.
2. puts()
👉 Think of puts() as writing a whole word or sentence.
It prints the string and automatically moves to the next line.
Example:
Output:
📌 puts() always ends with a newline — you don’t need to write \n.
3. printf()
👉 printf() is the most flexible.
It can print:
Characters
Strings (sentences)
Numbers (integers, decimals)
Even mix them together with formatting
Example:
Output:
📌 Here %d, %f, %c are format specifiers (placeholders) for numbers, decimals, and characters.
✅ Summary for Layman:
putchar()→ like pressing one key on the keyboard.puts()→ like typing a whole sentence and then pressing Enter.printf()→ like typing anything you want (letters, numbers, mix) with full control.
Q 9.1.2: Format specifiers examples
Step 2: Break down 25
The digits are: 2 and 5
Positions:
2is in the tens place → multiply by5is in the ones place → multiply by
Step 3: Calculate
Q 9.1.3: Input with scanf, getch, getche, getchar, gets
🧠 Concept Before Code:
| Function | Description |
|---|---|
scanf() | Takes formatted input (like numbers or words). |
getch() | Takes a single character input without showing it on the screen. |
getche() | Takes a single character input and shows it on the screen. |
getchar() | Reads a single character (shows it like getche). |
gets() | Takes a line of text as input (stops at Enter). (unsafe, but good for basic learning) |
💻 C Program:
🧾 Sample Output:
🧠 Simple Explanation (For Class or Notes)
🟢 1. scanf()
Use: To take formatted input from the user — like numbers, characters, or words.
Example:
➡️ It reads an integer value and stores it in the variable age.
Explain Like This:
"
scanf()is used when we want to take input in a specific format, for example an integer or a float.
It stops reading when you press SPACE or ENTER."
🟢 2. getch()
Use: To take one character input without showing it on the screen.
Example:
➡️ If you type A, nothing will appear — but the program will store 'A' in ch.
Explain Like This:
"
getch()is used when we want to take a single key input secretly — for example, in password fields or “Press any key to continue” screens."
🟢 3. getche()
Use: To take one character input and show it on the screen.
Example:
➡️ If you type A, it will appear on the screen and be stored in ch.
Explain Like This:
"
getche()is likegetch()but it displays the key you press."
🟢 4. getchar()
Use: Reads one character from the keyboard (and shows it).
Example:
➡️ If you type A and press Enter, it will store 'A' in grade.
Explain Like This:
"
getchar()takes only one character as input — for example, your grade A, B, or C."
🟢 5. gets()
Use: Reads a whole line of text including spaces.
Example:
➡️ If you type Ali Khan, the full name is stored in the name variable.
Explain Like This:
"
gets()is used to take string input (like your name or sentence).
Unlikescanf("%s", ...), it can read spaces too."
🧾 Summary Table for Notes
| Function | Input Type | Shows Input? | Example Use | Remarks |
|---|---|---|---|---|
scanf() | Words, numbers | ✅ Yes | Taking age, marks, etc. | Stops at space or Enter |
getch() | Single character | ❌ No | Hidden key input | Used in “Press any key” |
getche() | Single character | ✅ Yes | Character input | Shows what you press |
getchar() | Single character | ✅ Yes | Input like grade | Waits for Enter |
gets() | String (text line) | ✅ Yes | Full name or sentence | Reads spaces too |
Q 9.1.4: What is an escape sequence?
- A
special backslash code that represents a non-printing character.
Q 9.1.5: Common escape sequences
- \a
alert (beep), \b backspace, \n newline, \r carriage return, \t tab, \
backslash, ' single quote, " double quote, ? question mark.
#include <stdio.h>
int main() {
printf("Hello\tWorld\nLine2\rCR
test\n");
printf("Quotes: \'
\" Backslash: \\\n");
return 0;
}
9.2 Operators in C Q 9.2.1: Arithmetic operators
#include <stdio.h>
int main(){
int a=9,b=4;
printf("+ %d\n",
a+b);
printf("- %d\n",
a-b);
printf("* %d\n",
a*b);
printf("/ %d\n",
a/b); // integer division → 2
printf("%% %d\n",
a%b); // remainder → 1
return 0;
}
Q 9.2.2: Convert arithmetic expression to C
- Example:
Expression 3x^2 + 2x + 1 with x=2
int x=2; int y = 3*x*x + 2*x + 1;
Q 9.2.3: Solve an arithmetic problem
float price=99.5, qty=3;
float bill = price*qty;
Q 9.2.4: Assignment and compound assignment
int x=10;
x = x + 5; // same as:
x += 5; // other: -=, *=,
/=, %=
📝 Assignment Operator (Layman Explanation)
👉 Imagine you have a box with a name written on it.
That box is called a variable (like x, y, marks, etc.).
The assignment operator (=) is like putting something inside the box.
Example 1: Simple Assignment
💡 Meaning: Put the number 10 inside the box named x.
Example 2: Updating the Value
💡 Meaning: Look inside the box x, take what is there, add 5 to it, and put the new value back in the same box.
If x was 10 before → now it becomes 15.
Shortcuts (Compound Assignment Operators)
These are just short ways to update the value in the box:
x += 5;→ meansx = x + 5;x -= 3;→ meansx = x - 3;x *= 2;→ meansx = x * 2;x /= 4;→ meansx = x / 4;
Real Life Example 🎒
Think of your pocket money:
Start:
money = 100;→ you have 100 rupees.money += 50;→ you got 50 more → now 150.money -= 30;→ you spent 30 → now 120.money *= 2;→ your money doubled → now 240.
The = operator is simply saying: “Put this new value in the box again.”
✅ Program 1: Addition using +=
✅ Program 2: Subtraction using -=
✅ Program 3: Multiplication using *=
✅ Program 4: Division using /=
✅ Program 5: Combo Example (+=, -=, *=, /=)
Q 9.2.5: Increment and decrement
📘 C Program: Using Increment and Decrement Operators
🧠 Explanation
a++→ Post-increment → use the value ofafirst, then increase it by 1++b→ Pre-increment → increase the value ofbfirst, then use ita--→ Post-decrement → use the value ofafirst, then decrease it by 1--b→ Pre-decrement → decrease the value ofbfirst, then use it
🧾 Example Output
Q 9.2.6: Relational operators
- <,
>, <=, >=, == (equal), != (not equal). They return 1 (true) or 0
(false).
int a=5, b=7;
printf("%d\n", a < b);
// 1
Q 9.2.7: Logical operators
- &&
AND, || OR, ! NOT
int age=20; int hasID=1;
if (age>=18 && hasID) printf("Allowed\n");
SLO NO.9.2.7
Use the following logical operators in a C program
AND(&&)
OR(||)
NOT(!)
Q 9.2.8: Difference between = and ==
- =
assigns a value: x = 5;
- ==
compares values: if (x == 5) …
Q 9.2.9: Unary vs Binary operators
- Unary:
works on one value (++, --, !, unary -).
- Binary:
works on two values (+, -, *, /, %, <, >, &&, ||).
Q 9.2.10: Conditional (ternary) operator
int a=10, b=20;
int max = (a>b) ? a : b; //
if a>b then a else b
Q 9.2.11: Operator precedence (simple idea)
- Highest:
(), unary +/-, ++/--, !
- Then:
*, /, %
- Then:
+, -
- Then:
<, <=, >, >=
- Then:
==, !=
- Then:
&&
- Then:
||
- Lowest:
=, +=, -= … Tip: Use parentheses to make your intention clear.
Section 10: Control Structures
Q 10.1.1: What is a control statement?
- Answer:
A statement that controls the flow of a program (decision-making or
selection and repetition). Examples: if, if-else, switch.
Q 10.1.2: What is a conditional statement?
- Answer:
A statement that runs code only if a condition is true. Examples: if,
if-else, if-else-if, switch.
Q 10.1.3: Structure of if
if (condition) {
// statements when
condition is true
}
Q 10.1.4: Program using if
c
Copy code
int marks=75;
if (marks >= 50) printf("Pass\n");
Q 10.1.5: Structure of if-else
c
Copy code
if (condition) {
// true part
} else {
// false part
}
Q 10.1.6: Program using if-else
int num=7;
if (num%2==0) printf("Even\n");
else printf("Odd\n");
Q 10.1.7: Structure of if-else-if
if (cond1) { ... }
else if (cond2) { ... }
else { ... }
Q 10.1.8: Program using if-else-if (grading)
int m=83;
if (m>=85) printf("A");
else if (m>=70) printf("B");
else if (m>=50) printf("C");
else printf("Fail");
Q 10.1.9: Structure of switch
switch (expression) {
case value1: /* statements
*/ break;
case value2: /* statements
*/ break;
default: /* statements */
}
Q 10.1.10: Advantages and disadvantages of switch
- Advantages:
Clean and readable for many fixed choices, faster than many if-else in
some cases.
- Disadvantages:
Works only with integral types (int/char, not ranges), no relational conditions
like > or <, must remember break to avoid fall-through.
Q 10.1.11: Program using switch
‘Schar
op = '+';
int a=7,b=3;
switch(op){
case '+':
printf("%d\n", a+b); break;
case '-':
printf("%d\n", a-b); break;
case '*':
printf("%d\n", a*b); break;
case '/':
printf("%d\n", b!=0 ? a/b : 0); break;
default: printf("Unknown\n");
}
___________________________________________________________________________________________________
SWITCH NESTED
IF AND ELSE
























No comments:
Post a Comment