C-PROGRAMMING Q.b solns(musa)
C-PROGRAMMING Q.b solns(musa)
BANK
SOLUTIONS(MUSA) (BY.Umar)
THEORY Q. SOLNS
1. What are the tokens of c language explain with example
SOLN: Tokens are the fundamental building blocks of a C program.
They are the smallest individual units of code that have a distinct meaning to
the compiler.
During the first stage of compilation (called lexical analysis), the compiler
breaks down the program into these tokens, forming the basis for further
processing and translation.
Here's an explanation of tokens in C with examples:
Tokens are the fundamental building blocks of a C program. They are the
smallest individual units of code that have a distinct meaning to the
compiler. During the first stage of compilation (called lexical analysis), the
compiler breaks down the program into these tokens, forming the basis for
further processing and translation.
1. Keywords:
○ Predefined, reserved words with specific meanings in C.
○ Examples: int, float, char, if, else, while, for, return,
void, main, struct, union, typedef, sizeof, const,
2. Identifiers:
○ User-defined names for variables, functions, arrays,
structures, unions, etc.
○ Rules:
■ Must start with a letter (a-z, A-Z) or an underscore (_).
■ Can contain letters, digits, or underscores.
■ Case-sensitive (e.g., Age and age are different).
○ Examples: sum, count, average, myFunction, employeeName
3. Constants:
○ Fixed values that don't change during program execution.
○ Types:
■ Numeric constants:
■ Integer constants: Whole numbers (e.g., 10, -5, 0)
■ Floating-point constants: Numbers with decimal
parts (e.g., 3.14159, -2.5e2)
■ Character constants: Single characters enclosed in
single quotes (e.g., 'A', 'z', '!')
■ String literals: Sequences of characters enclosed in
double quotes (e.g., "Hello, world!")
4. Operators:
○ Symbols that perform operations on values.
○ Examples: Arithmetic operators (+, -, *, /, %), Relational
operators (==, !=, <, >, <=, >=), Logical operators (&&, ||, !),
Assignment operator (=), Increment/decrement operators (++,
--), etc.
5. Special Symbols:
○ Punctuation marks with specific functions in C syntax.
○ Examples: Parentheses (), braces {}, brackets [], semicolon
;, comma ,, period ., colon :
6. White Spaces:
○ Spaces, tabs, newlines, used for readability but ignored by the
compiler (except within strings).
Mathematical Functions:
(a) sqrt():
(b) fabs():
(c) pow():
(d) ceil():
String Functions:
(f) strcmp():
(g) strcat():
(h) strlen():
(j) strrev():
How it works:
1.The condition is evaluated first.
2.If the condition is true, expression1 is evaluated and its
value 3.becomes the result of the entire expression.
4.If the condition is false, expression2 is evaluated and its
value becomes the result.
EX.
int age = 25;
char *status = (age >= 18) ? "Adult" : "Minor"; // status will be
"Adult"
Breakdown:
age >= 18 is evaluated as true.
So, "Adult" is assigned to the status variable
Key Points:
1. It's a concise way to write simple conditional statements.
2. It's often used for variable assignments and returning values
from functions.
3. It can improve readability in some cases, but overuse can
make code less clear.
4. Use parentheses for clarity if expressions are complex.
5. It has lower precedence than most other operators, so use
parentheses for grouping as needed.
1. Call by Value:
- A copy of the actual parameter's value is passed to the function.
- Changes made to the parameter within the function do not affect the
original value.
Example:
C
void increment(int x) { // x is a copy of the original
value
x = x + 1;
int main() {
int num = 5;
2. Call by Reference:
- The address of the actual parameter is passed to the function.
- Changes made to the parameter within the function directly affect
the original value.
- It's often used for modifying large data structures or returning
multiple values.
Example:
C
void swap(int *a, int *b) { // a and b are pointers to
the original values
*a = *b;
*b = temp;
}
int main() {
3. Arrays as Parameters:
- Arrays are always passed by reference in C, even if you don't use
the & operator.
- Any changes made to the array within the function affect the original
array.
Example:
C
void modifyArray(int arr[], int size) { // arr is a
pointer to the original array
int main() {
int numbers[] = {1, 2, 3, 4};
}
Key Points:
- Choose the appropriate method based on whether you want to
modify the original values or not.
- Call by value is often used for simple data types and when you
want to preserve the original values.
- Call by reference is used for arrays, large structures, and when
you need to modify the original values or return multiple values.
Entry-controlled loops:
- The loop condition is checked before entering the loop body.
- If the condition is false at the beginning, the loop body won't
execute even once.
- Examples in C: for loop and while loop
C
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
C
int count = 10;
count--;
Exit-controlled loops:
- The loop condition is checked after executing the loop body.
C
int choice = 0;
do {
printf("Enter a positive number: ");
scanf("%d", &choice);
● The loop body (prompting for input) will execute at least once,
even if choice is initially negative.
● The condition choice <= 0 is checked after the first iteration,
and the loop continues if it's true.
Key Points:
SOLN:
Both structures and unions in C are used to group related data, but
they differ in how they store that data:
1. Memory allocation:
2. Accessing members:
4. Usage:
Soln.
Bitwise Operators:
Logical Operators:
Key Differences:
Examples:
Bitwise:
C
int a = 5, b = 3; // Binary: a = 0101, b = 0011
Logical:
C
int x = 10, y = 20;
Soln.
Strings in C:
1. strlen(str):
○ Calculates the length of a string (excluding the null
terminator).
○ Returns an unsigned integer value representing the number of
characters in the string.
○ Example: int length = strlen("Hello"); // length will be
5
2. strcpy(dest, src):
○ Copies one string to another.
○ Copies the characters of src to dest, including the null
terminator.
○ Caution: Be sure dest has enough space to accommodate the
copied string.
○ Example: char name1[20] = "Alice"; char name2[20];
strcpy(name2, name1);
3. strcat(dest, src):
4. strcmp(str1, str2):
○ Compares two strings lexicographically (character by
character).
○ Returns 0 if the strings are equal, a negative value if str1 is
less than str2, and a positive value if str1 is greater than str2.
○ Example: int result = strcmp("apple", "banana"); //
result will be negative
Remember:
Soln.
Nested Structures:
Example:
C
struct Address {
char street[50];
char city[30];
char state[20];
int zipcode;
};
struct Employee {
int id;
char name[50];
double salary;
};
Accessing Members:
C
struct Employee emp1;
emp1.salary = 50000.0;
Initialization:
struct Date {
int day;
int month;
int year;
};
struct Student {
int roll_no;
char name[50];
float marks;
};
Key Points:
Hardware:
Software:
Soln:
Structures:
struct struct_name {
member_type1 member_name1;
member_type2 member_name2;
// ... more members
};
Explanation:
Examples:
1. Employee Structure:
struct Employee {
int id;
char name[50];
float salary;
};
2. Address Structure:
struct Address {
char street[100];
char city[50];
char state[30];
int zipcode;
};
3. Student Structure:
struct Student {
int roll_no;
char name[30];
float marks;
};
Key Points:
emp1.id = 101;
emp1.salary = 50000.0;
Soln:
Here's an explanation of flowcharts and the common symbols used in
them:
Flowchart:
● A visual diagram that represents the flow of a process or
algorithm.
● Uses a set of standard symbols connected by arrows to depict
the sequence of steps and decisions involved.
● Helps in understanding, planning, analyzing, documenting, and
communicating processes.
1. Oval/Ellipse:
Additional Symbols:
Benefits of Flowcharts:
Soln.
Here are the different data type modifiers available in C, along with
their purposes and examples:
Examples:
C
signed int x = -5;
unsigned int y = 100;
Examples:
C
short int age = 25;
long int population = 785462135;
Example:
C
long long int huge_number = 9223372036854775807LL; // Maximum
value for long long
Key Points:
● Modifiers are applied to base data types like int, char, and
float.
Additional Notes:
C
switch (expression) {
case value1:
break;
case value2:
break;
default:
Explanation:
Example:
C
int day = 3; // Assume a value has been assigned to day
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
Key Points:
● The expression must evaluate to a compatible type for
comparison (integer or character).
● case values must be constant expressions.
● break statements are crucial to prevent fall-through (execution
continuing to the next case even if the expression doesn't
match).
● default is optional but often used to handle unexpected values.
● switch statements can be nested within each other for more
complex multi-way branching.
Soln:
Function Prototypes:
Syntax:
C
return_type function_name(parameter_list);
Explanation:
Example:
C
int calculate_area(int length, int width); // Function
prototype
int main() {
return 0;
return l * w;
}
Key Points:
Additional Notes:
Soln:
(i) Recursion:
(ii) Break:
(iii) Goto:
(iv) Continue:
SOLN:
#include <stdio.h>
int main() {
int rows, cols, i, j, sum = 0;
return 0;
}
int main() {
char str[100];
int len, i, flag = 1;
if (flag) {
printf("%s is a palindrome.\n", str);
} else {
printf("%s is not a palindrome.\n", str);
}
return 0;
}
Soln:
#include <stdio.h>
int main() {
int rows, cols, i, j;
printf("Enter the number of rows and columns: ");
scanf("%d %d", &rows, &cols);
return 0;
}
Soln:
#include <stdio.h>
int main() {
int x, n, result;
return 0;
}
int arr[n];
return 0;
}
int main() {
int num1, num2, result;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
return 0;
}
Soln.
#include <stdio.h>
#include <string.h>
struct Book {
char name[50];
float price;
int pages;
char author[50];
};
int main() {
struct Book books[100]; // Array to store details of 100 books
int num_books;
printf("Name: ");
fgets(books[i].name, 50, stdin); // Safer input for strings
books[i].name[strcspn(books[i].name, "\n")] = '\0'; // Remove
newline
printf("Price: ");
scanf("%f", &books[i].price);
printf("Pages: ");
scanf("%d", &books[i].pages);
printf("Author: ");
fgets(books[i].author, 50, stdin);
books[i].author[strcspn(books[i].author, "\n")] = '\0';
}
printf("\nBook Details:\n");
for (int i = 0; i < num_books; i++) {
printf("Book %d:\n", i + 1);
printf("Name: %s\n", books[i].name);
printf("Price: %.2f\n", books[i].price);
printf("Pages: %d\n", books[i].pages);
printf("Author: %s\n", books[i].author);
printf("--------------------\n");
}
return 0;
}
Soln:
#include <stdio.h>
int sum_recursive(int n) {
if (n == 0) {
return 0; // Base case: sum of 0 numbers is 0
} else {
return n + sum_recursive(n - 1); // Recursive call: add n to the sum
of (n-1) numbers
}
}
int main() {
int n;
return 0;
}
Soln:
#include <stdio.h>
reverseString(str);
return 0;
}
int main() {
int num, i, isPrime = 1;
if (isPrime) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
return 0;
}
Soln:
#include <stdio.h>
int main() {
int numbers[10];
int i;
printf("Enter 10 numbers:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &numbers[i]); // Store each number in the array
}
printf("\nEntered numbers:\n");
for (i = 0; i < 10; i++) {
printf("%d ", numbers[i]); // Print each number from the array
}
printf("\n");
return 0;
}
int main() {
int n, i, t1 = 0, t2 = 1, nextTerm;
return 0;
}
Soln:
#include <stdio.h>
int main() {
int num;
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
long long fact = factorial(num);
printf("Factorial of %d = %lld\n", num, fact);
}
return 0;
}
Soln:
#include <stdio.h>
int main() {
int num1, num2, result;
return 0;
}
Q.15) Write a program to find largest of three numbers
using nested if-else.
Soln:
#include <stdio.h>
int main() {
int num1, num2, num3;
return 0;
}
Soln:
#include <stdio.h>
int main() {
int rows;
// Print asterisks
for (int j = 1; j <= i; j++) {
printf("*");
}
return 0;
}
int main() {
int rows;
return 0;
}
Compiled by Umar