Class 11 Computer Science Programming Concepts and Logics Notes and Important Questions
Learn
Loading PDF viewer…
Notes for Class 11 Programming Concepts and Logics (Computer Science) are shown above.
Class 11 Programming Concepts and Logics Notes (Computer Science)
Key points
- 5.2 C Programming Language 5.2.1 Introduction and Features of C C language :- a general-purpose, structured, high-level programming language developed by Dennis Ritchie in 1972 at AT&T Bell Laboratories, USA. It came from the languages BCPL and B (by Ken Thompson). UNIX was rewritten in C. C is called a middle-level language because it has features of high-level languages and can also work close to hardware (memory, bits). Standards: ANSI C (C89), C99, C11, C17, C23. Features of C :- Uses :- operating systems (UNIX, Linux kernel, parts of Windows), compilers, device drivers, embedded systems, databases (MySQL), games. 5.2.2 Structure of a C Program /* Program to find area of a circle */ ← Documentation #include <stdio.h> ← Link section #define PI 3.14159 ← Definition section float area; ← Global declaration int main() ← main() function { float r; ← declaration part Structured — program is divided into functions (modules)
- Portable — a C program can run on different machines with little change
- Fast and efficient — compiled code runs very quickly
- Middle-level — supports pointers and bit operations for system programming
- Rich library — many built-in functions (printf, sqrt, strlen)
- Small set of keywords — only 32 keywords
- Case sensitive — sum and Sum are different
- Extensible — we can add our own functions; also the base of C++, Java, C# •
Unit 5 : Programming Concepts & Logics 5.1 Programming Concept 5.1.1 Introduction to Programming Languages Program :- a set of instructions given to the computer in a proper sequence to solve a problem. Programming language :- a formal language with its own words (keywords), symbols and grammar rules (syntax) used to write programs. eg. C, Python, Java. Programming is the process of writing, testing and maintaining programs. The person who writes programs is a programmer. 5.1.2 Low Level, High Level and 4GL Languages A. Low level language (LLL) :- close to the machine (hardware), hard for humans. B. High level language (HLL / 3GL) :- close to human language (English words and maths symbols); machine independent; easy to write, read and debug; needs a compiler or interpreter. eg. C, C++, Java, Python, BASIC, FORTRAN, COBOL, Pascal. C. Fourth generation language (4GL) :- very high level, non-procedural languages — we tell what to do, not how. Very few lines of code; used for databases, reports and queries. eg. SQL, MATLAB, report generators, FoxPro. SELECT name FROM student WHERE marks > 80; 5GL — languages for AI using constraints and logic, eg. Prolog, Mercury. Machine language (1GL) — written in binary 0s and 1s; directly understood by the CPU, no translator needed; very fast but very hard to write and machine dependent. • Assembly language (2GL) — uses short codes called mnemonics like ADD, SUB, MOV, LDA; needs an assembler; easier than machine language but still machine dependent. •
Low level language High level language Close to machine Close to human language Machine dependent Machine independent (portable) Hard to write and debug Easy to write and debug Fast execution, less memory Slower, needs more memory Needs assembler / none Needs compiler or interpreter eg. machine, assembly eg. C, Python, Java 5.1.3 Compiler, Interpreter and Assembler A computer understands only machine language, so programs in other languages must be converted by a language translator. 1. Assembler :- translates assembly language into machine code. 2. Compiler :- translates the whole high-level program at once into machine code (object code) and shows all errors together after compiling. Creates an executable (.exe) file. eg. C, C++ compilers (GCC, Turbo C). 3. Interpreter :- translates and executes the program line by line; stops at the first error. No separate object file. eg. Python, BASIC, JavaScript interpreters. Source code (prog.c) Compiler Object code (prog.obj) Linker Executable (prog.exe) + library files fig: compiling a C program Compiler Interpreter Translates whole program at once Translates line by line Shows all errors after compiling Stops at the first error Creates object / exe file No object file Execution is faster Execution is slower Needs more memory Needs less memory eg. C, C++ eg. Python, BASIC
5.1.4 Syntax, Semantic and Runtime Errors An error (bug) is a mistake in a program; finding and removing errors is called debugging. 1. Syntax error :- breaking the grammar rules of the language. Detected by the compiler; the program does not run. eg. missing semicolon, wrong spelling of a keyword, missing bracket. printf("Hello") /* error: ; missing */ Printf("Hi"); /* error: P capital */ 2. Semantic (logical) error :- the program runs but gives a wrong result because the logic or meaning is wrong. Not detected by the compiler — found by testing. eg. using + instead of *, wrong formula, = instead of ==. avg = a + b / 2; /* wrong: should be (a + b) / 2 */ 3. Runtime error :- error that occurs while the program is running, which may crash it. eg. division by zero, square root of a negative number, array index out of range, file not found, not enough memory. x = 10 / 0; /* runtime error: divide by zero */ 5.1.5 Control Structures Control structures decide the order (flow) in which statements are executed. There are three basic types: Statement 1 Statement 2 Statement 3 Condition? True part False part T F Condition? Loop body T F Sequence Selection Iteration fig: the three control structures 1. Sequence :- statements are executed one after another in the order they are written. eg. input → calculate → print.
2. Selection (decision / branching) :- a condition is checked and one of two or more paths is chosen. eg. if, if-else, switch. 3. Iteration (looping / repetition) :- a block of statements is repeated while a condition is true. eg. while, do-while, for. 5.1.6 Program Design Tools Before writing code we plan the solution using design tools: algorithm, flowchart and pseudocode. A. Algorithm :- a step-by-step finite set of instructions written in simple English to solve a problem. Features :- has input and output, each step is clear (definite), finite (ends after some steps), effective and language independent. Q. Write an algorithm to find the larger of two numbers. Step 1: Start Step 2: Read two numbers A and B Step 3: If A > B then print "A is larger" else print "B is larger" Step 4: Stop B. Flowchart :- a pictorial (diagram) representation of an algorithm using standard symbols connected by arrows. Start / Stop Read / Print Process Yes/No? A Terminal Input / Output Processing Decision Flow line Connector fig: flowchart symbols
Start Read A, B Is A > B ? Print A Print B Yes No Stop fig: flowchart to find the larger of two numbers C. Pseudocode :- a program-like description of the logic written in simple English mixed with programming words (IF, THEN, ELSE, WHILE, READ, PRINT). It is not real code and does not follow strict syntax. BEGIN READ A, B IF A > B THEN PRINT "A is larger" ELSE PRINT "B is larger" ENDIF END Algorithm Flowchart Pseudocode Steps in English Diagram with symbols English + code words Easy to write Easy to understand visually Close to real program Hard to see flow Hard to draw for big programs No standard rules 5.1.7 Absolute Binary, BCD, ASCII and Unicode These are ways (codes) to represent numbers and characters inside the computer.
1. Absolute binary :- the number is written in pure binary form. eg. (59)10 = 111011. Signed numbers use the leftmost bit as sign (0 = +, 1 = −) or 2's complement. 2. BCD (Binary Coded Decimal) :- each decimal digit is written separately as a 4-bit binary number (8421 code). eg. (59)10 = 0101 1001 (BCD). Used in calculators and digital clocks. 3. ASCII (American Standard Code for Information Interchange) :- a 7-bit code that gives 128 characters (English letters, digits, symbols, control codes). Extended ASCII uses 8 bits = 256 characters. Character ASCII (decimal) Binary A 65 1000001 Z 90 1011010 a 97 1100001 0 48 0110000 space 32 0100000 Trick: small letter = capital + 32 (a = 65 + 32 = 97). 4. Unicode :- a universal code that gives a unique number to every character of all languages of the world, including Nepali (Devanagari), Chinese, Arabic and emojis. Uses 8, 16 or 32 bits (UTF-8, UTF-16, UTF-32) and can represent over a million characters. eg. क = U+0915. The first 128 Unicode characters are the same as ASCII. ASCII Unicode 7 / 8 bits 8, 16 or 32 bits 128 / 256 characters Over a million characters English only All languages of the world Less memory More memory
- 5.2 C Programming Language 5.2.1 Introduction and Features of C C language :- a general-purpose, structured, high-level programming language developed by Dennis Ritchie in 1972 at AT&T Bell Laboratories, USA. It came from the languages BCPL and B (by Ken Thompson). UNIX was rewritten in C. C is called a middle-level language because it has features of high-level languages and can also work close to hardware (memory, bits). Standards: ANSI C (C89), C99, C11, C17, C23. Features of C :- Uses :- operating systems (UNIX, Linux kernel, parts of Windows), compilers, device drivers, embedded systems, databases (MySQL), games. 5.2.2 Structure of a C Program /* Program to find area of a circle */ ← Documentation #include <stdio.h> ← Link section #define PI 3.14159 ← Definition section float area; ← Global declaration int main() ← main() function { float r; ← declaration part Structured — program is divided into functions (modules)
- Portable — a C program can run on different machines with little change
- Fast and efficient — compiled code runs very quickly
- Middle-level — supports pointers and bit operations for system programming
- Rich library — many built-in functions (printf, sqrt, strlen)
- Small set of keywords — only 32 keywords
- Case sensitive — sum and Sum are different
- Extensible — we can add our own functions; also the base of C++, Java, C# •
printf("Enter radius: "); ← executable part scanf("%f", &r); area = PI * r * r; printf("Area = %.2f", area); return 0; } /* user-defined functions */ ← Sub-program section 1. Documentation section :- comments giving the program name, author, date and purpose. 2. Link section :- #include lines that link header files. 3. Definition section :- #define to make symbolic constants. 4. Global declaration :- variables / functions used in the whole program. 5. main() function :- every C program must have one main(); execution starts from here. Inside it: declaration part and executable part, written within { }. 6. Sub-program section :- user-defined functions. Rules :- every statement ends with a semicolon ( ; ), C is case sensitive (keywords in small letters), blocks are written inside { }. Q1. Write a program to display "Hello, World!". #include <stdio.h> int main() { printf("Hello, World!\n"); return 0; } Output :- Hello, World!
- 5.2.3 C Preprocessor and Header Files Preprocessor :- a program that processes the source code before compilation. Its commands are called preprocessor directives; they start with # and do not end with a semicolon. Header file :- a file with extension .h that contains declarations of built-in (library) functions. We include it to use those functions. Header file Functions stdio.h printf(), scanf(), getchar(), putchar(), gets(), puts() conio.h clrscr(), getch() — Turbo C only math.h sqrt(), pow(), sin(), abs(), floor() string.h strlen(), strcpy(), strcat(), strcmp() ctype.h toupper(), tolower(), isdigit(), isalpha() stdlib.h malloc(), exit(), rand(), atoi() 5.2.4 Character Set used in C The set of valid characters used to write a C program: Escape sequences :- special characters starting with a backslash used inside strings. Escape Meaning Escape Meaning \n new line \t horizontal tab \\ backslash \" double quote \' single quote \0 null character \a alert (beep) \b backspace #include — includes a header file: #include <stdio.h>
- #define — defines a symbolic constant or macro: #define PI 3.14
- #if, #ifdef, #else, #endif — conditional compilation
- Letters — A to Z, a to z
- Digits — 0 to 9
- Special characters — + − * / % = < > ( ) { } [ ] ; : , . # & | ! ? ' " _ ~ ^ \
- White spaces — blank space, tab, new line •
- 5.2.5 Use of Comments Comments are notes written in a program to explain the code. They are ignored by the compiler and make the program easy to understand and maintain. /* multi-line comment written between these marks */ int age; // single-line comment (C99 and later) 5.2.6 Identifiers, Keywords and Tokens Keywords :- reserved words with a fixed meaning in C. They cannot be used as variable names. All are in small letters. ANSI C has 32 keywords: auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while Identifiers :- names given by the programmer to variables, functions and arrays. eg. sum, total_marks, area1. Rules for identifiers :- Tokens :- the smallest individual units of a C program. Types: keywords (int), identifiers (sum), constants (10, 3.5), strings ("Nepal"), operators (+, =) and special symbols ({ } ; ,). Can contain letters, digits and underscore ( _ ) only
- Must start with a letter or underscore, not a digit
- No spaces or special symbols allowed
- Keywords cannot be used
- Case sensitive: Total ≠ total
- Valid: roll_no, _x, sum2 | Invalid: 2sum, roll no, int, a$b •
- int sum = a + 10; tokens: int | sum | = | a | + | 10 | ; → 7 tokens 5.2.7 Basic Data Types in C A data type tells the type of value a variable can store and how much memory it needs. Data type Stores Size Format Example int whole numbers 2 or 4 bytes* %d int age = 17; float decimal numbers (6 digits precision) 4 bytes %f float pi = 3.14; double big decimal numbers (15 digits) 8 bytes %lf double d = 2.5e10; char single character 1 byte %c char g = 'A'; void no value (used for functions) — — void main() * int is 2 bytes in Turbo C (−32768 to 32767) and 4 bytes in modern compilers like GCC (−2,147,483,648 to 2,147,483,647). Type modifiers :- short, long, signed, unsigned — change the size / range. eg. long int (%ld), unsigned int (%u), long double (%Lf). 5.2.8 Constants and Variables Constant :- a value that does not change during program execution. Variable :- a named memory location whose value can change during the program. It must be declared before use. int a, b; /* declaration */ float price = 99.5; /* declaration with initialisation */ a = 10; /* assignment */ Integer constant — 25, −7, 0
- Real (floating) constant — 3.14, −0.5, 2.5e3
- Character constant — single character in single quotes: 'A', '5'
- String constant — characters in double quotes: "Nepal"
- Symbolic constant — #define PI 3.14 or const float PI = 3.14; •
5.2.9 Type Specifier (Format Specifier) Format specifiers are used in printf() and scanf() to tell the type of data to be read or printed. They start with %. Specifier Data type Specifier Data type %d or %i int %f float %c char %lf double %s string %ld long int %u unsigned int %e exponent form %o octal %x hexadecimal %.2f prints 2 digits after the decimal point; %5d prints in a width of 5. 5.2.10 Simple and Compound Statements Simple statement :- a single instruction ending with a semicolon. eg. a = 5; printf("Hi"); Compound statement (block) :- a group of statements enclosed within { }, treated as one statement. Used in if, loops and functions. { sum = a + b; printf("%d", sum); } 5.2.11 Operators and Expressions Operator :- a symbol that performs an operation on data (operands). Expression :- a combination of operands and operators that gives a value. eg. a + b * 2 1. Arithmetic operators (let a = 17, b = 5): Operator Meaning Example Result + addition a + b 22 − subtraction a − b 12 * multiplication a * b 85
- Operator Meaning Example Result / division a / b 3 (integer division) % modulus (remainder) a % b 2 2. Relational operators :- compare two values and give 1 (true) or 0 (false): < > <= >= == !=. eg. (17 > 5) = 1, (17 == 5) = 0. 3. Logical operators :- combine conditions. Operator Meaning Example (a=17, b=5) Result && AND — true if both true a > 10 && b > 10 0 || OR — true if any true a > 10 || b > 10 1 ! NOT — reverses !(a > 10) 0 4. Assignment operators :- give a value to a variable: =. Shorthand: a += 5 (a = a + 5), a −= 5, a *= 5, a /= 5, a %= 5. 5. Unary operators :- work on one operand: ++ (increment), −− (decrement), − (minus), sizeof, !. 6. Conditional (ternary) operator ?: :- short form of if-else. Syntax: condition ? value1 : value2 max = (a > b) ? a : b; /* if a > b, max = a, else max = b */ Precedence (high → low) :- ( ) → unary (++ −− ! sizeof) → * / % → + − → < <= > >= → == != → && → || → ?: → = += −= eg. 10 + 6 / 2 * 3 = 10 + 3 * 3 = 10 + 9 = 19 5.2.12 Input / Output (I/O) Functions A. Formatted I/O :- use format specifiers. Pre-increment ++a — first increase, then use
- Post-increment a++ — first use, then increase
- eg. a = 5; b = ++a; → a = 6, b = 6 | a = 5; b = a++; → a = 6, b = 5
- sizeof(int) gives the size of int in bytes •
B. Unformatted I/O :- no format specifiers. Function Use getchar() reads one character (needs Enter) putchar() prints one character gets() reads a string with spaces (unsafe — use fgets() in new C) puts() prints a string and moves to a new line getch() / getche() reads a character without Enter (conio.h, Turbo C) Q2. Write a program to input two numbers and find their sum. #include <stdio.h> int main() { int a, b, sum; printf("Enter two numbers: "); scanf("%d %d", &a, &b); sum = a + b; printf("Sum = %d\n", sum); return 0; } Output :- Enter two numbers: 15 27 Sum = 42 Q3. Write a program to calculate simple interest. #include <stdio.h> int main() { printf() — displays output on the screen. eg. printf("Sum = %d", sum); • scanf() — reads input from the keyboard. eg. scanf("%d", &n); — the & (address of) operator is needed for variables (not for strings). •
float p, t, r, si; printf("Enter principal, time and rate: "); scanf("%f %f %f", &p, &t, &r); si = (p * t * r) / 100; printf("Simple interest = %.2f\n", si); return 0; } Output :- Enter principal, time and rate: 5000 2 10 Simple interest = 1000.00 Q4. Write a program to find the area of a circle using a symbolic constant. #include <stdio.h> #define PI 3.14159 int main() { float r, area; printf("Enter radius: "); scanf("%f", &r); area = PI * r * r; printf("Area of circle = %.2f\n", area); return 0; } Output :- Enter radius: 7 Area of circle = 153.94
Q5. Write a program to show the use of getchar(), putchar() and puts(). #include <stdio.h> int main() { char ch; printf("Enter a character: "); ch = getchar(); printf("You entered: "); putchar(ch); puts("\nThank you!"); return 0; } Output :- Enter a character: k You entered: k Thank you! 5.2.13 Selection Control Statements Selection (decision) statements choose which statements to execute based on a condition. 1. if statement :- executes the block only if the condition is true. if (condition) { statements; } 2. if-else statement :- executes one block if true, another if false.
if (condition) statement1; else statement2; Q6. Write a program to check whether a number is even or odd. #include <stdio.h> int main() { int n; printf("Enter a number: "); scanf("%d", &n); if (n % 2 == 0) printf("%d is even\n", n); else printf("%d is odd\n", n); return 0; } Output :- Enter a number: 17 17 is odd 3. if-else-if ladder :- checks many conditions one by one; the first true block runs. if (condition1) statement1; else if (condition2) statement2; else statement3;
Q7. Write a program to find the largest of three numbers. #include <stdio.h> int main() { int a, b, c; printf("Enter three numbers: "); scanf("%d %d %d", &a, &b, &c); if (a >= b && a >= c) printf("Largest = %d\n", a); else if (b >= a && b >= c) printf("Largest = %d\n", b); else printf("Largest = %d\n", c); return 0; } Output :- Enter three numbers: 12 45 30 Largest = 45 Q8. Write a program to input percentage and display the division. #include <stdio.h> int main() { float per; printf("Enter percentage: "); scanf("%f", &per); if (per >= 80) printf("Distinction\n"); else if (per >= 60) printf("First division\n");
else if (per >= 45) printf("Second division\n"); else if (per >= 35) printf("Third division\n"); else printf("Fail\n"); return 0; } Output :- Enter percentage: 72.5 First division 4. Nested if :- an if statement inside another if statement. Q9. Write a program to check whether a number is positive, negative or zero (nested if). #include <stdio.h> int main() { int n; printf("Enter a number: "); scanf("%d", &n); if (n != 0) { if (n > 0) printf("Positive\n"); else printf("Negative\n"); } else printf("Zero\n");
return 0; } Output :- Enter a number: -8 Negative 5. switch statement :- selects one case from many using the value of an expression (int or char). break ends each case; default runs when no case matches. switch (expression) { case value1: statements; break; case value2: statements; break; default: statements; } Q10. Write a program to make a simple calculator using switch. #include <stdio.h> int main() { float a, b; char op; printf("Enter expression (eg. 8 * 4): "); scanf("%f %c %f", &a, &op, &b); switch (op) { case '+': printf("Result = %.2f\n", a + b); break; case '-': printf("Result = %.2f\n", a - b); break; case '*': printf("Result = %.2f\n", a * b); break; case '/': if (b != 0) printf("Result = %.2f\n", a / b);
else printf("Cannot divide by zero\n"); break; default: printf("Invalid operator\n"); } return 0; } Output :- Enter expression (eg. 8 * 4): 8 * 4 Result = 32.00 if-else-if switch Checks any condition (>, <, &&) Checks only equality with constants Works with all data types Only int and char Hard to read with many conditions Neat for many choices (menus) 5.2.14 Iteration Control Statements (Loops) A loop repeats a block of statements while a condition is true. Every loop has: initialisation, condition and update (increment / decrement). 1. while loop :- entry-controlled loop; condition is checked first, so the body may run zero times. initialisation; while (condition) { statements; update; }
Q11. Write a program to find the reverse and sum of digits of a number. #include <stdio.h> int main() { int n, r, rev = 0, sum = 0; printf("Enter a number: "); scanf("%d", &n); while (n != 0) { r = n % 10; rev = rev * 10 + r; sum = sum + r; n = n / 10; } printf("Reverse = %d\n", rev); printf("Sum of digits = %d\n", sum); return 0; } Output :- Enter a number: 1234 Reverse = 4321 Sum of digits = 10 2. do-while loop :- exit-controlled loop; the body runs first and the condition is checked at the end, so it runs at least once. Note the semicolon after while( ). do { statements; } while (condition);
Q12. Write a program to add numbers until the user enters 0. #include <stdio.h> int main() { int n, total = 0; do { printf("Enter a number (0 to stop): "); scanf("%d", &n); total = total + n; } while (n != 0); printf("Total = %d\n", total); return 0; } Output :- Enter a number (0 to stop): 5 Enter a number (0 to stop): 8 Enter a number (0 to stop): 2 Enter a number (0 to stop): 0 Total = 15 while do-while Entry-controlled Exit-controlled Condition checked first Condition checked last May run 0 times Runs at least once No ; after while( ) ; after while( ) 3. for loop :- initialisation, condition and update are written in one line. Best when the number of repetitions is known.
for (initialisation; condition; update) { statements; } Q13. Write a program to display the multiplication table of a number. #include <stdio.h> int main() { int n, i; printf("Enter a number: "); scanf("%d", &n); for (i = 1; i <= 10; i++) printf("%d x %d = %d\n", n, i, n * i); return 0; } Output :- Enter a number: 7 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
Q14. Write a program to find the factorial of a number. #include <stdio.h> int main() { int n, i; long fact = 1; printf("Enter a number: "); scanf("%d", &n); for (i = 1; i <= n; i++) fact = fact * i; printf("Factorial of %d = %ld\n", n, fact); return 0; } Output :- Enter a number: 6 Factorial of 6 = 720 Q15. Write a program to print the first 10 terms of the Fibonacci series. #include <stdio.h> int main() { int a = 0, b = 1, c, i; printf("Fibonacci series: "); for (i = 1; i <= 10; i++) { printf("%d ", a); c = a + b; a = b; b = c; }
printf("\n"); return 0; } Output :- Fibonacci series: 0 1 1 2 3 5 8 13 21 34 break and continue :- break exits the loop (or switch) immediately; continue skips the rest of the current repetition and goes to the next one. Q16. Write a program to check whether a number is prime (using break). #include <stdio.h> int main() { int n, i, flag = 1; printf("Enter a number: "); scanf("%d", &n); if (n < 2) flag = 0; for (i = 2; i <= n / 2; i++) { if (n % i == 0) { flag = 0; break; } } if (flag == 1) printf("%d is a prime number\n", n); else printf("%d is not a prime number\n", n);
return 0; } Output :- Enter a number: 29 29 is a prime number Q17. Write a program to print 1 to 10 except 5 (using continue). #include <stdio.h> int main() { int i; for (i = 1; i <= 10; i++) { if (i == 5) continue; printf("%d ", i); } return 0; } Output :- 1 2 3 4 6 7 8 9 10 4. Nested loop :- a loop inside another loop. For each repetition of the outer loop, the inner loop runs completely. Used for patterns and matrices. Q18. Write a program to print the following patterns using nested loops. #include <stdio.h> int main() { int i, j;
for (i = 1; i <= 4; i++) { for (j = 1; j <= i; j++) printf("* "); printf("\n"); } for (i = 1; i <= 4; i++) { for (j = 1; j <= i; j++) printf("%d ", j); printf("\n"); } return 0; } Output :- * * * * * * * * * *
1 2 1 2 3 1 2 3 4
5.2.15 Array Array :- a collection of similar type of data stored in continuous memory locations under one common name. Each element is accessed using an index (subscript) starting from 0. 1-D array (one-dimensional) :- elements in a single row (list). int marks[5]; /* declaration: 5 integers */ int a[5] = {10, 20, 30, 40, 50}; /* initialisation */ Index a[0] a[1] a[2] a[3] a[4] Value 10 20 30 40 50 2-D array (two-dimensional) :- elements in rows and columns (table / matrix). Syntax: type name[rows][columns]; int m[2][3] = { {1, 2, 3}, {4, 5, 6} }; /* 2 rows, 3 columns */ m[0][2] = 3, m[1][0] = 4. Total elements = 2 × 3 = 6. Advantages :- stores many values with one name, easy to process with loops, saves code. Disadvantages :- fixed size, only same type of data. Q19. Write a program to input n numbers and find their sum, average and the largest. #include <stdio.h> int main() { int a[50], n, i, sum = 0, max; printf("How many numbers? "); scanf("%d", &n); printf("Enter %d numbers: ", n); for (i = 0; i < n; i++) scanf("%d", &a[i]); max = a[0]; for (i = 0; i < n; i++) {
sum = sum + a[i]; if (a[i] > max) max = a[i]; } printf("Sum = %d\n", sum); printf("Average = %.2f\n", (float)sum / n); printf("Largest = %d\n", max); return 0; } Output :- How many numbers? 5 Enter 5 numbers: 45 78 62 90 55 Sum = 330 Average = 66.00 Largest = 90 Q20. Write a program to sort five numbers in ascending order (bubble sort). #include <stdio.h> int main() { int a[5] = {34, 12, 89, 5, 47}; int i, j, temp; for (i = 0; i < 5 - 1; i++) { for (j = 0; j < 5 - 1 - i; j++) { if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1];
a[j + 1] = temp; } } } printf("Sorted: "); for (i = 0; i < 5; i++) printf("%d ", a[i]); return 0; } Output :- Sorted: 5 12 34 47 89 Q21. Write a program to add and subtract two 2×2 matrices. #include <stdio.h> int main() { int a[2][2], b[2][2], s[2][2], d[2][2], i, j; printf("Enter matrix A (2x2): "); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) scanf("%d", &a[i][j]); printf("Enter matrix B (2x2): "); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) scanf("%d", &b[i][j]); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) { s[i][j] = a[i][j] + b[i][j]; d[i][j] = a[i][j] - b[i][j];
} printf("A + B =\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) printf("%d\t", s[i][j]); printf("\n"); } printf("A - B =\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) printf("%d\t", d[i][j]); printf("\n"); } return 0; } Output :- Enter matrix A (2x2): 9 7 5 3 Enter matrix B (2x2): 1 2 3 4 A + B = 10 9 8 7 A - B = 8 5 2 -1
5.2.16 String and String Functions String :- a sequence (array) of characters ending with the null character '\0'. In C a string is stored in a char array. char name[20] = "Ram"; /* stored as R a m \0 */ char city[] = {'P','o','k','h','a','r','a','\0'}; We read a string with scanf("%s", name) (no &, stops at space) or gets(name) / fgets(), and print with printf("%s") or puts(). String functions are in string.h: Function Use Example strlen(s) gives the length (without \0) strlen("Nepal") → 5 strcpy(s1, s2) copies s2 into s1 s1 becomes s2 strcat(s1, s2) joins s2 at the end of s1 "Ram"+"Hari" → "RamHari" strcmp(s1, s2) compares: 0 if same, <0 or >0 if different strcmp("abc","abd") → negative strrev(s) reverses the string "Nepal" → "lapeN" strlwr(s) converts to lowercase "NEB" → "neb" strupr(s) converts to uppercase "neb" → "NEB" Note: strrev(), strlwr() and strupr() work in Turbo C / Windows compilers but are not part of standard C (not in GCC). Q22. Write a program to show the use of string functions. #include <stdio.h> #include <string.h> int main() { char s1[50] = "Nepal", s2[50] = "Kathmandu", s3[50]; printf("Length of s1 = %d\n", strlen(s1)); strcpy(s3, s1); printf("Copied s3 = %s\n", s3); strcat(s1, s2); printf("Joined s1 = %s\n", s1);
printf("strcmp(\"abc\",\"abd\") = %d\n", strcmp("abc", "abd")); printf("Upper = %s\n", strupr(s2)); printf("Lower = %s\n", strlwr(s2)); printf("Reverse = %s\n", strrev(s3)); return 0; } Output :- Length of s1 = 5 Copied s3 = Nepal Joined s1 = NepalKathmandu strcmp("abc","abd") = -1 Upper = KATHMANDU Lower = kathmandu Reverse = lapeN Q23. Write a program to check whether a word is a palindrome. #include <stdio.h> #include <string.h> int main() { char s[50], r[50]; printf("Enter a word: "); scanf("%s", s); strcpy(r, s); strrev(r); if (strcmp(s, r) == 0) printf("%s is a palindrome\n", s); else printf("%s is not a palindrome\n", s);
- return 0; } Output :- Enter a word: madam madam is a palindrome Important Questions — Unit 5 Theory Programs (practise all!) Differentiate between low-level and high-level languages. What is 4GL?
- Differentiate between compiler and interpreter.
- Explain syntax, semantic and runtime errors with examples.
- What is an algorithm? Write an algorithm and draw a flowchart to find the largest of three numbers.
- Differentiate between ASCII and Unicode. What is BCD?
- Explain the structure of a C program.
- What are identifiers? Write the rules for naming identifiers.
- Explain the basic data types of C with format specifiers.
- Explain arithmetic, relational, logical and conditional operators with examples.
- Differentiate between while and do-while loop.
- What is an array? Differentiate between 1-D and 2-D arrays.
- Explain any four string functions with examples.
- Check whether a year is a leap year.
- Find the sum of the first n natural numbers.
- Check whether a number is an Armstrong number (eg. 153).
- Print all even numbers from 1 to 100.
- Find the HCF and LCM of two numbers. •
- Exam tip :- always write #include, int main(), proper indentation, semicolons and a sample output. Marks are given for logic even if small syntax mistakes exist. Count vowels in a string.
- Find the transpose of a 3×3 matrix.
- Display the pattern: 5 4 3 2 1 / 5 4 3 2 / … / 5 •
Related chapters in Computer Science: Class 11 Application Package notes, Class 11 Web Technology I notes, Class 11 Computer System notes.
Practice
Important Questions
What is an algorithm? Write an algorithm and draw a flowchart to determine whether an input number is even or odd.
Write a program to input the elements of 4 × 3 matrix and print its elements properly using array.
Write a C program to calculate the factorial of a positive integer using a loop. Explain the program.
Which of the following is a valid identifier in C programming?
2number
total-marks
float
total_marks
Which language translator converts an assembly language program into machine code?
Compiler
Interpreter
Assembler
Browser
Which looping process checks the test condition at the end of the loop?
for
while
do-while
Nested loop
4 more questions locked
Upgrade to a paid plan to view all important questions
Exam
This unit introduces the fundamental concepts of programming and problem-solving. Students learn about programming languages, compilers, interpreters, algorithms, flowcharts, pseudocode, errors, and control structures. The unit also introduces C programming, including data types, variables, operators, input/output, decision-making, loops, arrays, and strings, providing a foundation for developing computer programs.
This page covers Programming Concepts and Logics, chapter 5 of 8 in the Class 11 Computer Science syllabus set by the National Examination Board (NEB). 8 important questions for this chapter are available, each with a model answer.
Read through the notes above, then try each important question for this chapter before checking its solution — comparing your working against past NEB and model questions is one of the most efficient ways to revise.