0% found this document useful (0 votes)
11 views14 pages

Document

This document provides a comprehensive overview of key concepts in C programming, including the language's history, structure, data types, operators, and error handling. It includes potential exam questions and answers covering topics such as decision-making, arrays, strings, functions, and more. The information is organized into sections for clarity and serves as a study guide for students preparing for their Bachelor of Science in Computer Science exam.

Uploaded by

kulolacaleb007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views14 pages

Document

This document provides a comprehensive overview of key concepts in C programming, including the language's history, structure, data types, operators, and error handling. It includes potential exam questions and answers covering topics such as decision-making, arrays, strings, functions, and more. The information is organized into sections for clarity and serves as a study guide for students preparing for their Bachelor of Science in Computer Science exam.

Uploaded by

kulolacaleb007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Here are some potential questions and answers for your Bachelor of Science in Computer Science exam,

based on the provided C programming lecture notes. The questions are categorized for clarity.
Remember to consult your textbook and other course materials for a more comprehensive
understanding.

**I. Introduction to C**

* **Q1: What is C, and why is it still relevant despite being an older language?**

* **A1:** C is a general-purpose, procedural programming language created by Dennis Ritchie at Bell


Labs in 1972. Its relevance stems from its fundamental role in computer science, its efficiency (speed
and resource usage), its portability (ability to run on different systems with minimal changes), and its
influence on many modern languages (C++, Java, C#, etc.). Its syntax forms a basis for understanding
many other programming languages.

* **Q2: What is the primary purpose of C?**

* **A2:** While versatile, C was initially developed to write the UNIX operating system. It's used for
system programming, embedded systems, and high-performance applications due to its speed and
efficiency.

**II. Differences Between C and C++**

* **Q3: What are the main differences between C and C++?**

* **A3:** C++ is an extension of C, sharing a similar syntax. However, C++ supports object-oriented
programming (OOP) concepts like classes and objects, while C is procedural. C++ also has built-in
exception handling, unlike C, which requires manual exception management. C++ uses references,
which are not available in C.

**III. History of C**

* **Q4: Briefly trace the history of C, highlighting key milestones.**


* **A4:** C's development began in the early 1970s at Bell Labs, evolving from BCPL and B. Dennis
Ritchie created it primarily for the UNIX operating system. The ANSI standard in 1989 standardized C,
leading to greater consistency across platforms.

**IV. Structure of a C Program**

* **Q5: Describe the six main sections of a well-structured C program, giving an example for each.**

* **A5:** A C program typically includes:

1. **Documentation:** Comments describing the program's purpose, author, date, etc. (e.g., `/*
This program calculates the area of a circle. */`)

2. **Preprocessor Section:** Includes header files providing necessary functions and definitions
(e.g., `#include <stdio.h>`)

3. **Definition:** Defines constants using `#define` (e.g., `#define PI 3.14159`)

4. **Global Declaration:** Declares global variables and functions (e.g., `int globalVar = 10;`)

5. **Main() Function:** The program's entry point, where execution begins. (`int main() { ... }`)

6. **Sub Programs:** User-defined functions called from the main function. (e.g., `int add(int a, int
b) { return a + b; }`)

**V. Compiling, Linking, and Running a C Program**

* **Q6: Explain the steps involved in compiling and running a C program using a GCC compiler.**

* **A6:**

1. **Create a Source File:** Write the C code and save it with a `.c` extension (e.g., `myprogram.c`).

2. **Compile:** Use the GCC compiler to translate the code into machine instructions: `gcc
myprogram.c -o myprogram` (The `-o` option specifies the output executable name). The `-Wall` flag is
recommended to enable all compiler warnings.

3. **Link:** The linker combines the compiled code with necessary libraries to create an
executable file.

4. **Run:** Execute the program: `./myprogram`


* **Q7: Detail the four phases of the C compilation process.**

* **A7:**

1. **Preprocessing:** The preprocessor handles directives like `#include`, `#define`, and


conditional compilation.

2. **Compilation:** The compiler translates the preprocessed code into assembly language.

3. **Assembly:** The assembler converts the assembly code into machine code (object code).

77 4. **Linking:** The linker combines object code files and libraries to create the final executable.

**VI. Variables, Constants, and Data Types**

* **Q8: What are variables and constants in C? How do you declare and initialize them?**

* **A8:** Variables are named storage locations holding data that can change during program
execution. Constants hold fixed values that cannot be altered. Declaration involves specifying the data
type and name (e.g., `int age; float salary = 100.5;`). Initialization assigns a value during declaration.

* **Q9: Explain the different basic data types in C, with examples.**

* **A9:**

* `int`: Integer values (e.g., `int count = 10;`)

* `float`: Single-precision floating-point numbers (e.g., `float price = 99.99;`)

* `double`: Double-precision floating-point numbers (e.g., `double pi = 3.14159;`)

* `char`: Single characters (e.g., `char initial = 'J';`)

* **Q10: What are derived data types in C? Give examples.**

* **A10:** Derived data types are built upon basic types:

* `arrays`: Collections of elements of the same type (e.g., `int numbers[5];`)

* `pointers`: Variables holding memory addresses (e.g., `int *ptr;`)


* `structures`: User-defined data types grouping related variables of different types (e.g., `struct
Student { int id; char name[50]; };`)

* `enums`: Sets of named integer constants (e.g., `enum Color {RED, GREEN, BLUE};`)

* **Q11: What is the `volatile` keyword in C and when should it be used?**

* **A11:** The `volatile` keyword indicates that a variable's value can change unexpectedly (e.g., by
external factors like hardware or another thread). The compiler is instructed *not* to optimize accesses
to such variables, ensuring that the program always reads the most up-to-date value from memory. This
is crucial in concurrent programming or when interacting with hardware.

**VII. Operators**

* **Q12: Explain the different categories of operators in C (arithmetic, assignment, comparison, logical,
bitwise), providing examples for each.**

* **A12:** (This would require a detailed explanation of each operator type and several examples.
Refer to the lecture notes for a comprehensive answer.)

**VIII. Input/Output**

* **Q13: Describe the difference between formatted and unformatted I/O in C, and give examples of
functions used for each.**

* **A13:** Formatted I/O uses `printf()` and `scanf()` for controlled input and output, specifying the
data type and format using format specifiers (e.g., `%d`, `%f`, `%c`, `%s`). Unformatted I/O uses functions
like `getchar()`, `putchar()`, `gets()` (deprecated, use `fgets()` instead), and `puts()` for simpler, less
structured input and output.

**IX. Expressions**
* **Q14: What are expressions in C? Explain operator precedence and associativity with examples.**

* **A14:** Expressions are combinations of variables, constants, operators, and function calls that
produce a value. Operator precedence defines the order of operations (e.g., multiplication before
addition). Associativity determines the order when operators have the same precedence (most
arithmetic operators are left-associative).

**X. Error Handling**

* **Q15: What types of errors might you encounter during the C compilation process, and how are they
typically handled?**

* **A15:** You can have compilation errors (syntax errors detected by the compiler) and linker errors
(unresolved references to functions or libraries). The compiler and linker will usually display error
messages indicating the problem location and type.

This list provides a foundation. Remember to refine your preparation by reviewing your lecture notes,
textbook, and practice problems. Good luck with your exams!

This message has been generated by Nova - download it for free:

https://novaappai.page.link/Hfz7GuSeKWDp4CTu8

Here are some potential questions and answers covering decision-making, arrays, and strings in C,
drawing upon common university curricula and practical programming experience. The questions are
categorized for clarity.

**I. Decision Making (Branching Statements)**

* **Q1: Explain the difference between `if`, `if-else`, and nested `if-else` statements in C. Provide
examples.**
* **A1:** `if` statements execute a block of code only if a condition is true. `if-else` statements
provide an alternative block of code to execute if the condition is false. Nested `if-else` statements allow
for more complex logic by placing `if-else` structures within other `if` or `else` blocks.

* **Example:**

```c

//if

if (x > 0) { printf("Positive"); }

//if-else

if (x > 0) { printf("Positive"); } else { printf("Non-positive"); }

//nested if-else

if (x > 0) {

if (x > 10) { printf("Greater than 10"); }

else { printf("Between 0 and 10"); }

} else { printf("Non-positive"); }

```

* **Q2: Describe the `switch` statement. When is it preferable to use a `switch` over a series of `if-else`
statements?**

* **A2:** The `switch` statement allows for selecting one block of code from multiple cases based on
the value of an integer expression. It is generally more efficient and readable than a long chain of `if-
else` statements when dealing with many distinct cases that check against a single variable. However,
`switch` is limited to integer or character-based comparisons.

* **Example:**

```c

int day = 3;

switch (day) {
case 1: printf("Monday"); break;

case 2: printf("Tuesday"); break;

case 3: printf("Wednesday"); break;

default: printf("Other day");

```

* **Q3: What are unconditional branching statements? Discuss the `goto` statement and its potential
drawbacks.**

* **A3:** Unconditional branching statements change the program's execution flow regardless of any
condition. The `goto` statement jumps to a labelled point in the code. While it offers flexibility, `goto` is
often considered harmful to code readability and maintainability because it can lead to "spaghetti code"
making the logic difficult to follow. Modern programming practices generally discourage its use.

* **Q4: Explain the functionality of the `break` and `continue` statements within loops.**

* **A4:** The `break` statement immediately exits the innermost loop it is contained within. The
`continue` statement skips the rest of the current iteration of the loop and proceeds to the next
iteration.

**II. Arrays**

* **Q5: Define a one-dimensional array in C. How are elements accessed?**

* **A5:** A one-dimensional array is a contiguous block of memory that stores elements of the same
data type. Elements are accessed using their index (position), starting from 0.

* **Example:** `int myArray[5] = {10, 20, 30, 40, 50};` `myArray[0]` accesses 10.
* **Q6: Describe two-dimensional arrays. How do you declare and access elements?**

* **A6:** Two-dimensional arrays represent a table or matrix of data, accessed using two indices
(row and column).

* **Declaration:** `int myMatrix[3][4];`

* **Access:** `myMatrix[1][2]` accesses the element in the second row and third column.

* **Q7: Discuss the concept of array bounds and potential issues associated with exceeding them.**

* **A7:** Array bounds refer to the valid index range of an array (0 to size-1). Attempting to access an
element outside this range leads to undefined behavior, often resulting in program crashes or
unexpected results.

**III. Strings**

* **Q8: How are strings represented in C? Why doesn't C have a dedicated string data type?**

* **A8:** Strings are represented as arrays of characters terminated by a null character (`\0`). C
doesn't have a dedicated string type for historical reasons and efficiency considerations; using character
arrays provides flexibility but requires careful handling of memory and the null terminator.

* **Q9: Explain the functions `strlen()`, `strcat()`, and `strcmp()`. Provide examples of their usage.**

* **A9:**

* `strlen(str)`: Returns the length of a string (excluding the null terminator).

* `strcat(str1, str2)`: Concatenates `str2` to the end of `str1`.


* `strcmp(str1, str2)`: Compares `str1` and `str2` lexicographically, returning 0 if they are equal, a
negative value if `str1` is less than `str2`, and a positive value if `str1` is greater than `str2`.

* **Q10: Compare and contrast `scanf("%s", str)` and `fgets(str, size, stdin)` for reading strings from
input. Discuss their limitations.**

* **A10:** `scanf("%s", str)` reads a string until a whitespace character is encountered; it is


vulnerable to buffer overflow. `fgets()` reads an entire line from input up to a specified size, preventing
buffer overflow. `fgets()` includes the newline character which usually needs to be removed.

* **Q11: Write a C program to reverse a string.**

* **A11:** (Several approaches exist. Here's one using pointers):

```c

#include <stdio.h>

#include <string.h>

int main() {

char str[100];

char *start, *end;

char temp;

printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

str[strcspn(str, "\n")] = 0; //remove trailing newline

start = str;
end = str + strlen(str) - 1;

while (start < end) {

temp = *start;

*start = *end;

*end = temp;

start++;

end--;

printf("Reversed string: %s\n", str);

return 0;

```

Remember to consult your textbooks and course materials for a more comprehensive understanding
and to adapt these examples to your specific learning objectives. These are just starting points. Good
luck with your exams!

This message has been generated by Nova - download it for free:

https://novaappai.page.link/L55wnD4yKUXuBQRV8

Here are some potential questions and answers covering C functions, structures, and unions, drawing
from common university curricula and real-world programming practices. The questions are categorized
for clarity.

**I. C Functions:**

* **Q1: What is a function in C, and why are they important?**


* **A1:** A function in C is a self-contained block of code designed to perform a specific task. They
promote modularity (breaking down complex programs into smaller, manageable parts), code
reusability (using the same function multiple times), and readability (making code easier to understand
and maintain).

* **Q2: Explain the difference between function declaration and function definition.**

* **A2:** A *function declaration* tells the compiler about the function's existence, its return type,
name, and parameters. It doesn't include the function's body. A *function definition* provides the
actual code that the function executes. Declarations usually precede definitions (allowing functions to
be called before they are fully defined).

* **Q3: Describe the three aspects of function syntax and provide an example.**

* **A3:** The three aspects are:

1. **Declaration:** `return_type function_name(parameter_type parameter1, parameter_type


parameter2);` (e.g., `int add(int x, int y);`)

2. **Definition:** `return_type function_name(parameter_type parameter1, parameter_type


parameter2) { /* function body */ }` (e.g., `int add(int x, int y) { return x + y; }`)

3. **Call:** `function_name(argument1, argument2);` (e.g., `int sum = add(5, 3);`)

* **Q4: Explain the difference between pass-by-value and pass-by-reference (using pointers).**

* **A4:** *Pass-by-value* creates a copy of the argument's value, so changes within the function
don't affect the original variable. *Pass-by-reference* (using pointers) passes the memory address of the
argument. Modifications within the function directly change the original variable. Pass-by-reference is
more efficient for large data structures because it avoids copying.

* **Q5: What are library functions? Give examples and explain their advantages.**

* **A5:** Library functions are pre-written functions provided by the C standard library (and other
libraries). Examples include `printf()` (for output), `scanf()` (for input), `sqrt()` (square root), `strcmp()`
(string comparison). Advantages: They're readily available, optimized for performance, save
development time, and are well-tested.

* **Q6: What are user-defined functions? Describe their advantages and disadvantages.**

* **A6:** User-defined functions are created by the programmer to perform specific tasks not
covered by library functions. Advantages: Reusability, modularity, improved code organization, easier
debugging and maintenance. Disadvantages: Can only return a single value, potential memory overhead
(stack frame allocation), and can lead to complex code if not well-structured.

* **Q7: What is recursion? Explain with an example (factorial calculation).**

* **A7:** Recursion is a technique where a function calls itself. It's useful for problems that can be
broken down into smaller, self-similar subproblems. A factorial is a classic example: `factorial(n) = n *
factorial(n-1)` (with the base case `factorial(0) = 1`). It's crucial to have a base case to prevent infinite
recursion.

**II. Structures:**

* **Q8: What is a structure in C? How is it defined and initialized?**

* **A8:** A structure groups together variables of different data types under a single name. It's
defined using the `struct` keyword, specifying member names and types within curly braces `{}`.
Initialization can be done at declaration or later by assigning values to individual members using the dot
operator (`.`).

* **Q9: Explain how to create and use arrays of structures.**

* **A9:** An array of structures allows you to store multiple records of the same type. Declare an
array of the structure type, and then access individual elements using array indexing `[]` and the dot
operator (`.`).
* **Q10: How can you have arrays within structures and structures within structures (nested
structures)?**

* **A10:** You can embed arrays as members of structures (e.g., a `char name[50];` member to
store a name). Nested structures are structures contained within other structures, useful for
representing complex hierarchical data.

* **Q11: How are structures passed to functions? Discuss the efficiency of pass-by-value versus pass-
by-reference.**

* **A11:** Structures can be passed to functions by value (copying the entire structure) or by
reference (passing a pointer to the structure). Pass-by-reference is generally more efficient, especially
for large structures, because it avoids the overhead of copying.

**III. Unions:**

* **Q12: What is a union in C? How does it differ from a structure?**

* **A12:** A union, like a structure, groups variables. However, all members of a union share the
same memory location. Only one member can hold a value at a time. Structures, on the other hand,
allocate separate memory for each member. Unions are useful when you need to store different data
types in the same memory space, but only one at a time (e.g., representing a value that could be an
integer or a float).

* **Q13: What are the advantages and disadvantages of using unions?**

* **A13:** Advantages: Memory efficiency when only one member is needed at a time.
Disadvantages: Can only hold one member's value at a time; managing which member is active requires
careful programming. The size of the union is determined by its largest member.

**IV. Formatted and Unformatted I/O:**


* **Q14: Describe the difference between formatted and unformatted I/O functions in C. Give
examples of each.**

* **A14:** Formatted I/O functions (like `printf()` and `scanf()`) use format specifiers (%d, %f, %s,
etc.) to control the input and output format. Unformatted I/O functions (like `getchar()`, `putchar()`,
`gets()`, `puts()`) handle input/output character-by-character or as simple strings without any
formatting.

This is a starting point. You should expand on these questions and answers using your textbooks and
other resources to delve deeper into the concepts and address more specific details. Consider adding
more complex scenarios and edge cases to your practice questions. Remember to focus on
understanding the underlying principles, not just memorizing syntax.

This message has been generated by Nova - download it for free:

https://novaappai.page.link/gYFHFdXUK14GETsLA

You might also like