Thursday, December 4, 2025

SLO 8.1.1 TILL SLO 10.1.11 WITH SOLUTION

 

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

SLO 8.4.5 TYPECASTING 

🟢 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 a float (decimal number).

  • Converting a char into an int, 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:

    int x = 10; float y = x; // int is automatically converted to float

    Here, 10 becomes 10.0 automatically.

Prog:

#include<stdio.h>
#include<conio.h>
main()
{
int x = 10;
float y = x;
printf("%f",y);
}

2. Explicit Typecasting

  • Done manually by the programmer.

  • You write the type in front of the value/variable you want to convert.

  • Example:

    float a = 10.5; int b = (int)a; // float is explicitly converted to int

    Here, 10.5 becomes 10 (decimal part is removed).

#include<stdio.h>
#include<conio.h>
main()
{
float a = 10.5;
/*int b = (int)a;*/   // float is explicitly converted to int
printf("%f",a);
}

🔵 C Program for Both Implicit & Explicit Typecasting

#include <stdio.h> int main() { // Implicit Typecasting Example int x = 10; float y; y = x; // int is automatically converted to float printf("Implicit Typecasting:\n"); printf("Integer value: %d\n", x); printf("Converted to float (automatically): %.2f\n\n", y); // Explicit Typecasting Example float a = 9.78; int b; b = (int)a; // float is explicitly converted to int printf("Explicit Typecasting:\n"); printf("Float value: %.2f\n", a); printf("Converted to int (manually): %d\n", b); return 0; }

🟣 Output of the Program

Implicit Typecasting: Integer value: 10 Converted to float (automatically): 10.00 Explicit Typecasting: Float value: 9.78 Converted to int (manually): 9

✅ 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:

#include <stdio.h> int main() { putchar('A'); // prints A putchar('\n'); // prints a newline (go to next line) putchar('B'); // prints B return 0; }

Output:

A B

📌 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:

#include <stdio.h> int main() { puts("Hello World"); puts("C Programming is fun!"); return 0; }

Output:

Hello World C Programming is fun!

📌 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:

#include <stdio.h> int main() { printf("Hello, World!\n"); // simple text printf("I am %d years old.\n", 20); // prints number (integer) printf("The price is %.2f dollars\n", 99.50); // prints decimal with 2 places printf("First letter is %c\n", 'A'); // prints a character return 0; }

Output:

Hello, World! I am 20 years old. The price is 99.50 dollars First letter is A

📌 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


#include <stdio.h>

int main() {
    // a. Decimal (using integer with %d)
    int decimalNumber = 25;
    printf("Decimal (integer value): %d\n", decimalNumber);

    // b. Integer (same as decimal in C, %d)
    int integerNumber = -42;
    printf("Integer: %d\n", integerNumber);

    // c. Float (decimal notation) -> %f
    float pi = 3.14159;
    printf("Float (decimal notation): %f\n", pi);

    // d. Float (exponential / scientific notation) -> %e or %E
    float bigNumber = 12345.6789;
    printf("Float (exponential notation): %e\n", bigNumber);

    // e. Character -> %c
    char letter = 'A';
    printf("Character: %c\n", letter);

    // f. Long integer -> %ld
    long int bigInteger = 1234567890;
    printf("Long integer: %ld\n", bigInteger);

    // g. String (sequence of characters) -> %s
    char name[] = "Hello, World!";
    printf("String: %s\n", name);

    return 0;
}



OUTPUT
Decimal number: 25
Integer number: -42
Float (decimal notation): 3.141590
Float (exponential notation): 1.234568e+04
Character: A
Long integer: 1234567890
String: Hello, World!

Step 2: Break down 25

  • The digits are: 2 and 5

  • Positions:

    • 2 is in the tens place → multiply by 101=1010^1 = 10

    • 5 is in the ones place → multiply by 100=110^0 = 1


Step 3: Calculate

25(10)=(2×101)+(5×100)25_{(10)} = (2 \times 10^1) + (5 \times 10^0) =(2×10)+(5×1)= (2 \times 10) + (5 \times 1) =20+5= 20 + 5 =25= 25


Q 9.1.3: Input with scanf, getch, getche, getchar, gets

🧠 Concept Before Code:

FunctionDescription
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:

#include <stdio.h> #include <conio.h> // for getch() and getche() int main() { int age; char grade; char name[50]; char ch; // Using scanf() printf("Enter your age: "); scanf("%d", &age); // Clear input buffer before using gets() fflush(stdin); // Using gets() printf("Enter your full name: "); gets(name); // Using getchar() printf("Enter your grade (A, B, C...): "); grade = getchar(); // Using getch() printf("\nPress any key (it will NOT be shown): "); ch = getch(); printf("\nYou pressed: %c\n", ch); // Using getche() printf("Press any key again (it WILL be shown): "); ch = getche(); printf("\nYou pressed: %c\n", ch); // Output summary printf("\n\n--- Your Details ---\n"); printf("Name: %s\n", name); printf("Age: %d\n", age); printf("Grade: %c\n", grade); return 0; }

🧾 Sample Output:

Enter your age: 16 Enter your full name: Ali Khan Enter your grade (A, B, C...): A Press any key (it will NOT be shown): You pressed: X Press any key again (it WILL be shown): Y You pressed: Y --- Your Details --- Name: Ali Khan Age: 16 Grade: A

🧠 Simple Explanation (For Class or Notes)

🟢 1. scanf()

Use: To take formatted input from the user — like numbers, characters, or words.
Example:

int age; scanf("%d", &age);

➡️ 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:

char ch; ch = getch();

➡️ 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:

char ch; ch = getche();

➡️ If you type A, it will appear on the screen and be stored in ch.

Explain Like This:

"getche() is like getch() but it displays the key you press."


🟢 4. getchar()

Use: Reads one character from the keyboard (and shows it).
Example:

char grade; grade = getchar();

➡️ 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:

char name[50]; gets(name);

➡️ 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).
Unlike scanf("%s", ...), it can read spaces too."


🧾 Summary Table for Notes

FunctionInput TypeShows Input?Example UseRemarks
scanf()Words, numbers✅ YesTaking age, marks, etc.Stops at space or Enter
getch()Single character❌ NoHidden key inputUsed in “Press any key”
getche()Single character✅ YesCharacter inputShows what you press
getchar()Single character✅ YesInput like gradeWaits for Enter
gets()String (text line)✅ YesFull name or sentenceReads 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 xymarks, etc.).

The assignment operator (=) is like putting something inside the box.


Example 1: Simple Assignment

x = 10;

💡 Meaning: Put the number 10 inside the box named x.


Example 2: Updating the Value

x = x + 5;

💡 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; → means x = x + 5;

  • x -= 3; → means x = x - 3;

  • x *= 2; → means x = x * 2;

  • x /= 4; → means x = 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 +=

#include <stdio.h> int main() { int x; printf("Enter a number: "); scanf("%d", &x); x += 5; // same as x = x + 5 printf("After adding 5, value of x = %d\n", x); return 0; }

✅ Program 2: Subtraction using -=

#include <stdio.h> int main() { int x; printf("Enter a number: "); scanf("%d", &x); x -= 3; // same as x = x - 3 printf("After subtracting 3, value of x = %d\n", x); return 0; }

✅ Program 3: Multiplication using *=

#include <stdio.h> int main() { int x; printf("Enter a number: "); scanf("%d", &x); x *= 2; // same as x = x * 2 printf("After multiplying by 2, value of x = %d\n", x); return 0; }

✅ Program 4: Division using /=

#include <stdio.h> int main() { int x; printf("Enter a number: "); scanf("%d", &x); x /= 4; // same as x = x / 4 printf("After dividing by 4, value of x = %d\n", x); return 0; }

✅ Program 5: Combo Example (+=, -=, *=, /=)

#include <stdio.h> int main() { int x; printf("Enter a number: "); scanf("%d", &x); x += 10; // add 10 printf("After adding 10: %d\n", x); x -= 5; // subtract 5 printf("After subtracting 5: %d\n", x); x *= 2; // multiply by 2 printf("After multiplying by 2: %d\n", x); x /= 3; // divide by 3 printf("After dividing by 3: %d\n", x); return 0; }

🖥️ int main() and return 0; in C – Simple Explanation

1. int main()

  • Every C program starts running from a function called main().

  • The word int means that this function will return an integer (a number) back to the computer when it finishes.

  • Think of it like a promise:
    👉 “Hey computer, when I finish running the program, I’ll give you a number as a report card.”


2. return 0;

  • At the end of the program we usually write:

    return 0;
  • Here, 0 means ‘everything went fine’.

  • If the program gives some other number, it usually means there was a problem.

👉 In real life:
Imagine you submit your homework.

  • If the teacher writes 0 mistakes → everything is correct ✅.

  • If the teacher writes 5 mistakes → something went wrong ❌.

Same way, return 0; tells the computer:
👉 “I finished my work successfully without errors.”


3. Why do we need it in school programs?

  • In simple programs, even if you don’t write return 0;, many compilers still work fine.

  • But good practice is to always write it, because it makes the program complete and professional.


✅ So, in layman terms:

  • int main() → starting point of the program that promises to return a number when finished.

  • return 0; → that number, usually 0, which means “Program ran successfully.”


Q 9.2.5: Increment and decrement

📘 C Program: Using Increment and Decrement Operators

#include <stdio.h> int main() { int a = 5, b = 10; // Display initial values printf("Initial values:\n"); printf("a = %d, b = %d\n\n", a, b); // Using increment operator printf("Using increment operator:\n"); printf("a++ = %d\n", a++); // Post-increment: use value first, then increment printf("Now a = %d\n", a); printf("++b = %d\n", ++b); // Pre-increment: increment first, then use value printf("Now b = %d\n\n", b); // Using decrement operator printf("Using decrement operator:\n"); printf("a-- = %d\n", a--); // Post-decrement: use value first, then decrement printf("Now a = %d\n", a); printf("--b = %d\n", --b); // Pre-decrement: decrement first, then use value printf("Now b = %d\n", b); return 0; }

🧠 Explanation

  • a++ → Post-increment → use the value of a first, then increase it by 1

  • ++b → Pre-increment → increase the value of b first, then use it

  • a-- → Post-decrement → use the value of a first, then decrease it by 1

  • --b → Pre-decrement → decrease the value of b first, then use it


🧾 Example Output

Initial values: a = 5, b = 10 Using increment operator: a++ = 5 Now a = 6 ++b = 11 Now b = 11 Using decrement operator: a-- = 6 Now a = 5 --b = 10 Now b = 10

RELATIONAL OPERATOR

🔹 List of Relational Operators in C

OperatorMeaningExampleResult
==Equal to5 == 5True (1)
!=Not equal to5 != 3True (1)
>Greater than7 > 4True (1)
<Less than3 < 8True (1)
>=Greater than or equal to6 >= 6True (1)
<=Less than or equal to2 <= 5True (1)

🔹 Example Program

#include <stdio.h> int main() { int a = 10, b = 20; printf("a == b: %d\n", a == b); printf("a != b: %d\n", a != b); printf("a > b : %d\n", a > b); printf("a < b : %d\n", a < b); printf("a >= b: %d\n", a >= b); printf("a <= b: %d\n", a <= b); return 0; }

🔹 Output:

a == b: 0 a != b: 1 a > b : 0 a < b : 1 a >= b: 0 a <= b: 1

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. Write a Program to check if number is divisible by 2 or not.
Solution:





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


TERNARY



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


ELSE IF




SWITCH






___________________________________________________________________________________





No comments:

Post a Comment