C Programming: Important Theory

Table of Contents (C Programming: Important Theory)
- Define software. Explain different types of software.
- Compare application software with system software.
- What is a programming language? Explain different types of programming language.
- Compare assembly language with machine language.
- Write the difference between high-level and low-level language.
- Explain, briefly, about the generations of programming language.
- What are the characteristics of a well-written program?
- Explain about recent trends of software.
- Explain different phases or steps of developing software.
- List the advantages and disadvantages of using a flowchart.
- List different symbols used for drawing a flowchart.
- Explain the compilation process with a relevant diagram.
- Write the difference between a compiler and an interpreter.
- Define the term source code, object code, compiler, and linker.
- What is an algorithm? Write its characteristics.
- Define the flowchart. Write its advantages and disadvantages.
- Write a flowchart to find the largest among three numbers.
- Define variable, constant, and keyword.
- Define data type. Write the types of data types in C.
- Write the rules of variable declaration in C.
- What is a constant? Write its types.
- Write the differences between printf() and scanf().
- Define operator. Write the types of operators in C.
- Define formatted and unformatted I/O functions with examples.
- Write the differences between entry-controlled loop and exit-controlled loop.
- Define loop. Write the types of loops in C.
- Write a program to find the factorial of a number using a loop.
- Define nested loop. Write a program to display a multiplication table using a nested loop.
- Define control structure. Write the types of control structures in C.
- Write a program to check whether a number is prime or not.
- Define array. Write its types.
- Write a program to find the sum of array elements.
- Define string. Write the differences between string and character array.
- Write a program to reverse a string.
- Define function. Write its advantages.
- Write a program to find the sum of two numbers using a function.
- “The number and types of arguments must be the same as the number and types of format specifiers used.” Clarify the statement with an example.
- Why are precision and field width required? What happens if the field width given is less than the length of the variable?
- Explain flags with a few examples.
- What are unformatted I/O functions? Write the syntax of putchar(), getchar(), getch(), getche().
- What do you mean by selective structures? When are they used?
- Write the syntax and working flow for various selection structures.
- In which cases should `simple if` and `if-else` be used?
- When is an `else-if` ladder needed?
- What sort of conditions necessitates the use of a `nested-if`?
- Demonstrate converting a nested-if structure to an else-if ladder with logical operators.
- Write the general form of a `switch` case.
- What kind of condition determines whether a `switch` or `if-else` is to be used?
- What kind of variables or expressions can be used within the expression of a `switch`?
- What can be the values of the `case` label/constant in a `switch` case?
- Explain the role of the `break` statement in a `switch` case. What happens if it is not used?
- Write the general form and working flow of the conditional operator.
- Explain why repetitive structures are required.
- What are the basic requirements for operating a loop? What is a running variable?
- Write the syntax for `for`, `while`, and `do-while` loops.
- When should we use a `for` loop? How does it differ from a `while` loop?
- When is a `while` loop used? What happens if initialization or update is done incorrectly?
- Distinguish between `while` and `do-while` loops.
- Explain `break` and `continue` statements with an example.
- Compare `break` and `continue` statements.
- What are nested loops? When are they used?
- Demonstrate how to change a `for` loop to a `while` loop.
- Explain the working flow of a nested `for` loop with an example.
- What happens if a nested loop contains the same running variable?
- Which conditions will cause a loop to run indefinitely?
- Define `function` and mention its advantages.
- Explain the `main` function. How does it differ from other functions?
- Describe function declaration (prototype), function call, and function definition.
- Differentiate formal arguments from actual arguments.
- Explain the use of return statement. Is it mandatory to use return statement?
- What happens to the statements written after the return statement?
- What does the return type symbolize in function definition and declaration? How is it related to the return statement?
- What does function declaration suggest? How are functions called?
- “The number and type of arguments must be the same in function definition”, clarify the statement.
- Is it mandatory to have a function declaration? “Any entity must be declared first before it is used”, explain the statement.
- Describe different types of functions based on return type and arguments.
- What are library functions? How do they differ from user-defined functions?
- What do you mean by passing by reference? When is it used?
- Differentiate between pass by value and pass by reference.
- What changes can be seen in the function declaration, function call, and function definition while using pass by reference?
- What sort of variables require the address operator in a function call while using pass by reference?
- Explain different ways of returning multiple values from a function.
- Define recursion. Explain how it differs from iteration.
- What are the requirements to solve a problem recursively?
- List the merits and demerits of using a recursive function.
- Define storage class. Compare automatic, extern, and static variables.
- Demonstrate the use of global variables and static variables.
- What do you mean by a derived data type?
- Define array. When and why are arrays required?
- Explain array declaration and initialization for different data types.
- What does the name of an array represent? Explain with an example how to access elements of an array.
- Demonstrate the difference that can be seen in the function declaration, function call, and function definition, when a single array element is passed and when the complete array is passed.
- “Passing a single element of an array indicates passing by value whereas passing the complete array (array name) represents pass by reference”, explain the statement with an example.
- Define string and null character. Explain, with an example, about string constants and string variables.
- How are strings declared? Demonstrate the different ways of initializing strings.
- What is the drawback of using `%s` in `scanf` to read a string? Illustrate different ways of reading a string.
- Explain why the address operator (ampersand) is not used while reading a string.
- Describe the general form, purpose, and return value (if any) of the following string functions: `strlen()`, `strcpy()`, `strcat()`, `strcmp()`.
- Explain briefly about an array of strings.
- What is a pointer? Differentiate a pointer with an array.
- List the advantages of using a pointer.
- Explain the role of `*` and `&` operators in C programming.
- Compare array and pointer. Describe how array and pointer can be used interchangeably.
- Explain about null pointer and void pointer.
- What is a user-defined data type?
- Define structure and explain briefly why it is required.
- Write the general syntax of a structure. What will be the size of a structure?
- What is the significance of the dot operator in C programming?
- Write the difference between a structure and an array.
- When is an array of structures used? Illustrate the difference in passing a single structure and an array of structures to a function with an example.
- What are the ways of returning an array of structures from a called function to the calling function?
- Explain briefly about the nested structure along with its syntax.
- Illustrate the difference between structure and union.
- What is a file? Why are files required?
- Explain briefly about the file structure `FILE` and `FILE` pointer.
- Describe different modes of opening a file.
- Where will be the position of the `FILE` pointer for different file opening modes?
- How can we access a file randomly? Write a one-line code for the following access.
- What is error handling? Why is it done?
- What are the different errors during I/O operations? How are errors handled during different file operations?
- Explain about different types of functions that are generally used.
- Write the difference between Writing mode and Appending Mode.
1. Define software. Explain different types of software.
Software is a collection of machine-readable instructions that directs a computer to perform some specific tasks. It is an ordered sequence of instructions given for changing the state of the computer hardware in a certain predefined sequence. Generally, software can be categorized as system software and application software. The detailed descriptions of system software and application software, along with their sub-categories, are given below:
System software: It is a type of computer software designed to operate the computer hardware, to provide basic functionality, and to provide a platform for running application software. System software includes device drivers, operating systems, etc. It is responsible for controlling, integrating, and managing the individual hardware components of a computer system so that they can work together harmoniously. Its purpose is to hide the complex details of the hardware.
- Operating system is the main system software that controls all parts of the computer system. The major functions of an OS are to handle all the hardware connected to the system, coordinate and manage the use of other resources, and provide common services for computer programs. Application programs usually require an operating system to function.
- Device driver is a computer program that operates or controls a particular type of device that is attached to a computer. A device driver simplifies programming by acting as a translator between a hardware device and the applications that use it.
Application software: It is a type of computer software that causes a computer to perform useful tasks that a user wishes to perform. It utilizes the capacities of a computer directly for a dedicated task. Application software includes word processing software, database software, multimedia software, graphics software, etc. It can be categorized as:
- Tailored (custom) software is software that is specially designed for some specific organizations or other users. It is developed for a single user that accommodates the particular preferences and expectations of the user.
- Packaged (off-the-shelf) software is software which performs some specific function or calculation that is useful for more than one computer user and is sufficiently well documented to be used without modifications on a defined configuration of some computer system.
2. Compare application software with system software.
The comparisons of application and system software are:
- Application software utilizes the capacities of a computer to perform a dedicated task to benefit the user, whereas system software manages and integrates a computer’s capabilities but doesn’t utilize those capacities in the performance to benefit the user.
- System software provides the platform for the application software to run on the system, whereas application software provides the platform for the end-users to use the capacities of the system to solve various problems.
- System software deals with the hardware (architecture of the system), whereas the application software interacts with the end-user.
- System software consists of low-level programs that interact with the computer at a very basic level.
3. What is a programming language? Explain different types of programming language.
A Programming Language is a standardized communication technique for describing instructions to a computer. Each programming language has a set of syntactic and semantic rules used to define computer programs. The different types of programming languages are described below.
Low-Level Languages are those languages which are closer to the hardware. They are specific to the hardware, so they cannot run on different hardware. Knowledge of hardware is required to develop such programs using low-level languages. It can be divided into Machine language and Assembly language.
-
Machine Language is the closest language to the hardware in which the instructions are given in the form of 0’s and 1’s.
Advantages:
- It makes fast and efficient use of computers.
- A translator is not required.
Disadvantages:
- The programmer should have hardware knowledge.
- All memory addresses and operation codes need to be remembered.
- Testing and Debugging are difficult to carry out.
- They are machine-dependent.
-
Assembly Languages are those languages which use mnemonics in place of 0’s and 1’s. Each instruction is represented by symbols instead of just using bits. The program written in assembly languages must be converted to machine language.
Advantages:
- Easier to understand and use as compared to machine language.
- Programs are normally very fast and very compact.
- Timings can be calculated very precisely and program flow is easily controlled.
Disadvantages:
- A good understanding of the hardware is required.
- Machine dependent.
High-Level language is a language with strong abstraction from the details of the computer and uses natural language elements, making the process of developing a program simpler and more understandable relative to a lower-level language. These languages are English-like and are very close to human languages. They are machine-independent. High-level languages are required to be converted into machine-level languages with the help of translators. Rather than dealing with registers, memory addresses, and stacks, they deal with variables, arrays, objects, functions, loops, threads, etc. It can be categorized as:
- Procedural-oriented languages (Imperative languages): In these languages, one or more related blocks of statements that perform some complete function are grouped together into a procedure. If the same sequence of operations is needed elsewhere in the program, a simple statement can be used to refer back to that procedure. A procedure may be a list of instructions directing a computer, step by step, what to do, usually having a linear order of execution from the first statement to the second and so forth with occasional loops and branches. Procedural programming languages include C, C++, FORTRAN, Pascal, and BASIC.
- Problem-Oriented Languages (Declarative languages): These languages were developed to solve specific problems or develop specific applications. These languages focus on what work is to be performed rather than how to perform the work. These languages are usually limited to a very specific application and might use syntax that is never used in other programming languages. These languages are specially focused on database management systems. SQL, CSS, and FUSION are some of the examples of problem-oriented languages.
- Natural Languages: These languages are supposed to have the form of human cognition and human intelligence. With these languages, humans can easily communicate or interact with computers without the requirement of knowledge of any special programming languages. These are generally used in Artificial Intelligence and Expert Systems. LISP and PROLOG are a few natural languages commonly in practice.
Advantages of High-level Languages
- Support a high level of abstraction.
- Easier to learn and use since the languages are very close to human languages.
- Easier to test and debug.
- They are machine-independent. Software written in a high-level language can be used on any computer system with a different architecture.
Disadvantages of High-Level Languages
- Requires more memory space and time.
4. Compare assembly language with machine language.
Assembly language and machine language are both low-level languages. Their comparison is as follows:
- Assembly languages use mnemonics while machine language uses 0’s and 1’s to represent operational codes and operands.
- Assembly languages need a translator to convert into machine language.
- Comparatively, assembly languages are easier to understand and use than machine language. But machine languages are a bit faster and more efficient.
- Both are machine-dependent, and a programmer must have knowledge about the hardware before using each language.
5. Write the difference between high-level and low-level language.
The differences between high-level and low-level languages are:
- Low-level languages are machine-oriented, whereas high-level languages are problem-oriented.
- Programs developed using low-level languages run faster and take less storage space.
- Low-level languages are used to develop system software, whereas high-level languages are used to design application software.
6. Explain, briefly, about the generations of programming language.
The various generations of programming languages are explained below.
- First Generation: The first generation of programming languages is all about machine code. The code of the first-generation programming language was entered through physical switches on the computer and involved commands to move data bits to and from registers, compute on these, and more. Machine language can be taken as a first-generation programming language.
- Second Generation: To minimize the difficulty, the operational codes were represented by mnemonics which in some way describe the action of the machine code (such as save, mov, add, load). The source codes needed to be assembled into machine code before they could be executed by a processor with the help of an assembler. Such languages are sometimes still used for kernels and device drivers, i.e., the core of the operating system and for specific machine parts. Assembly language was used as a second-generation language.
- Third Generation: Languages of the third generation were closer to human languages. The flaws of the first and second generations were dealt with by making the language machine-independent and including programmer-friendly features. These languages require a compiler to make machine code for the processor. Third-generation languages, which are high-level languages, are sometimes referred to as imperative languages. Imperative means that the code is executed line by line in sequence. A few examples are FORTRAN, C, C++, Java, C#, etc.
- Fourth Generation Languages are designed to reduce programming effort and the time it takes to develop software, resulting in a reduction in the cost of software development. Languages have been designed with a specific purpose, which includes query languages, report generators, etc. These languages are referred to as declarative languages since they describe what computation should be performed but not how to perform it. Characteristics of fourth-generation languages can be summarized as portable, closer to human language, database supportive, simple, and requires less effort, non-procedural. SQL, NOMAD, and FOCUS are some of the examples of fourth-generation languages.
- Fifth Generation Language, also known as natural language, provides a visual or graphical interface to develop software. It allows users to interact with computers without needing any specialized knowledge. These languages are generally used for writing programs for artificial intelligence, neural networks, plasma computing, etc. LISP, PROLOG, and Mercury are some of the examples of fifth-generation languages.
7. What are the characteristics of a well-written program?
A feature of software defines the distinguishing characteristics of software based on performance, portability, or functionality. Some of the important characteristics of well-written computer programs can be:
- Integrity refers to the accuracy of the calculations.
- Clarity refers to the overall readability of the program.
- Simplicity: The structure and logic of the program must be as simple as possible to enhance the clarity and accuracy of the program.
- Efficiency is concerned with execution speed and efficient memory utilization.
- Modularity means dividing the program into small modules which are independent of each other. It enhances accuracy and clarity and facilitates future program alterations.
- Interoperability is the ability of the software to exchange information with other applications and make use of information transparently.
- Portability is the ability of the software to function in different platforms and environments. Some other desirable characteristics may be security, flexibility, scalability, reliability, etc.
8. Explain about recent trends of software.
In the early days of software development, software was difficult to develop as they used machine languages, which made them efficient and faster but on the other hand, became non-portable and lacked a lot of user-friendly features. But as the programming language developed, the software has become very user-friendly and provides a visual interface or a graphical user interface which has made it much easier for users to interact.
Development of software has taken a huge stride in the modern era. In recent years, DevOps and agile development methodology have been heavily used for software development. Nowadays the focus is on cloud computing which in general means a virtual hard drive that is accessible to the network of computers.
Cloud computing is a computing paradigm in which tasks are assigned to a combination of connections, software, and services accessed over a network. This network of servers and connections is collectively known as the cloud. Using different media as an access point, users can reach into the cloud for resources whenever required.
9. Explain different phases or steps of developing software.
The following phases are included in software development.
- Problem Analysis: This is the first step of software development in which we define our objectives, analyze our input, processing, and output requirements. Depending on the size and complexity of the problem, a clear statement of the problem is made. And the types and number of inputs and outputs are evaluated. Finally, a mechanism to convert available resources into final productive results must be determined.
- Algorithm Development and Flow Diagram: In this phase, a general outline of the problem is sketched using an algorithm and a flowchart. Algorithms are used to define a set of steps or procedures to be followed to solve a given problem, while flowcharts are the diagrammatic representation of the steps to solve a particular problem.
- Coding: It is the process of writing a program using a particular programming language. Though high-level languages are more preferred, low-level languages can be used as well to write a program. Depending upon ease and accessibility, the programmer may use any platform to write a program.
- Compilation and Execution: When the programs are written in a high-level language, then they need to be converted into a low-level language. This conversion is done by a compiler, and the process is called compilation. After the compilation process, an executable program will be generated which, when opened, is set to execution. Different inputs are provided to check if the defined objectives are fulfilled or not.
- Debugging and Testing: Testing is the process of finding errors in the program, while debugging is the mechanism to remove the different errors that are present in the program. General syntax errors will be pointed out by the compiler, but the run-time errors must be checked by providing different sets of inputs to the program and tracing the output.
- Program Documentation: It is done for future reference which can be analyzed for better software development in later days. Documentation includes all the information about the program.
10. List the advantages and disadvantages of using a flowchart.
The various advantages and disadvantages of using a flowchart are listed as:
Advantages:- Communication: As diagrams are a better way to provide information, a flowchart will communicate the logic of the whole system concisely and efficiently.
- Effective Analysis: The problem can be analyzed more effectively, resulting in a reduction in cost and time.
- Proper Documentation: As a flowchart contains information about the working of the system, it helps to make documentation better.
- Efficient Coding: The flowchart acts as a guide for the programmer to write code in a more efficient manner since the steps and requirements are clearly defined in the diagram.
- Proper Debugging: The flowchart, sometimes, can be helpful in the debugging process.
- Efficient Program Maintenance: The maintenance of an operating program becomes easy with the help of a flowchart. It helps the programmer to put efforts more efficiently on that section.
- Complex and clumsy: When the program gets quite complicated, the flowchart can be more complex than it is imagined to be.
- Difficulty in modifications: When some alterations are to be done, the flowchart may require re-drawing.
11. List different symbols used for drawing a flowchart.
The basically used symbols in a flowchart are tabulated as:
SN | Symbol | Name of shape | Purpose |
---|---|---|---|
1. | Oval Shape (◯) | Start/Stop | Used to indicate the start and stop of the program |
2. | Parallelogram (▱) | Input/Output | Used to represent the input and output of the program |
3. | Rectangle (▭) | Processing | Used for data manipulation |
4. | Diamond (◇) | Decision | Used when there are more than one options for the user to select |
5. | Circle (○) | Connector | Used to connect two different distant sections of a flowchart |
6. | Arrow head (→) | Flow line | Used to connect two symbols |
12. Explain the compilation process with a relevant diagram.
The process of translation of a high-level language to a low-level language is called the compilation process. In this process, the source code is converted into an executable file. It basically consists of two phases.
- Compilation: First, the compiler converts the source code, which is written using a high-level language, to object code.
- Linking: Secondly, the linker combines the object code with library modules that are used in the program and also replaces the symbolic addresses with real addresses. And finally, it generates machine code in the form of an executable file.
Figure 1: Compilation Process
[Source Code .c]
↓
[Compiler]
↓
[Object Code .obj]
↓
[Linker] ← [Library Files]
↓
[Executable File .exe]
13. Write the difference between a compiler and an interpreter.
The differences between a compiler and an interpreter are:
SN | Compiler | Interpreter |
---|---|---|
1. | Scans the entire program and translates it as a whole into machine code. | Translates the program one statement at a time. |
2. | Generates intermediate object code which further requires linking, hence requires more memory. | No intermediate object code is generated, hence they are memory efficient. |
3. | It takes a large amount of time to analyze the source code but the overall execution time is fast. | It takes less amount of time to analyze the source code but the overall execution time is slow. |
4. | It generates the error message only after scanning the whole program. Hence debugging is comparatively hard. | When an error is detected while translating, it stops at that point. Hence debugging is easy. |
5. | Examples: C, C++ use compilers. | Examples: BASIC uses interpreters. |
14. Define the term source code, object code, compiler, and linker.
Source code is the program written in a high-level programming language. Example: file with .c
extension.
Object code is the intermediate machine code generated by the compiler, usually stored with .obj
extension.
Compiler translates high-level language into machine language (object code).
Linker combines object modules and libraries into a final executable program.
15. What is an algorithm? Write its characteristics.
Algorithm is a step-by-step procedure to solve a given problem in a finite number of steps.
Characteristics:
- Definiteness – Each step must be clear and unambiguous.
- Finiteness – Must terminate after a finite number of steps.
- Input – Takes zero or more inputs.
- Output – Produces at least one output.
- Effectiveness – Steps must be basic and executable.
16. Define the flowchart. Write its advantages and disadvantages.
A flowchart is a graphical representation of an algorithm using symbols to represent steps.
Advantages:
- Easy to understand and communicate.
- Helps in debugging and program design.
- Useful documentation tool.
Disadvantages:
- Complex for large programs.
- Difficult to modify.
- Time-consuming to draw.
17. Write a flowchart to find the largest among three numbers.
The flowchart compares three numbers a
, b
, and c
step by step and displays the largest.
(Here you can insert a diagram of the flowchart.)
18. Define variable, constant, and keyword.
Variable: Named memory location whose value can change during program execution.
Constant: Fixed value that does not change during execution (e.g., 3.14).
Keyword: Reserved word in C with special meaning (e.g., int
, return
).
19. Define data type. Write the types of data types in C.
Data type defines the type of data a variable can store and how much memory it needs.
Types:
- Primary data types (int, char, float, double)
- Derived data types (arrays, pointers, structures)
- User-defined data types (typedef, enum, struct, union)
20. Write the rules of variable declaration in C.
- Variable name must begin with a letter or underscore.
- Can contain letters, digits, and underscore.
- No special characters allowed.
- Cannot be a keyword.
- Must be declared before use.
21. What is a constant? Write its types.
Constant is a fixed value in a program.
Types:
- Integer constants (e.g., 10, -25)
- Real/Float constants (e.g., 3.14)
- Character constants (e.g., ‘a’)
- String constants (e.g., “Hello”)
- Symbolic constants (using
#define
)
22. Write the differences between printf() and scanf().
printf()
is used for output,scanf()
is used for input.printf()
writes data to the screen,scanf()
reads data from the keyboard.printf()
does not need address operator&
,scanf()
needs it for variables.
23. Define operator. Write the types of operators in C.
Operator is a symbol used to perform operations on data.
Types:
- Arithmetic operators (+, -, *, /, %)
- Relational operators (==, !=, <, >)
- Logical operators (&&, ||, !)
- Assignment operators (=, +=, -=)
- Increment/Decrement operators (++ , –)
- Bitwise operators (&, |, ^, ~, <<, >>)
- Conditional (?:)
24. Define formatted and unformatted I/O functions with examples.
Formatted I/O: Functions that allow formatted input/output, e.g., printf()
, scanf()
.
Unformatted I/O: Functions that handle characters/strings without format specifiers, e.g., getchar()
, putchar()
, gets()
, puts()
.
25. Write the differences between entry-controlled loop and exit-controlled loop.
- Entry-controlled: Condition is checked before execution (e.g.,
for
,while
). - Exit-controlled: Condition is checked after execution (e.g.,
do-while
). - Entry-controlled may not execute even once, exit-controlled executes at least once.
26. Define loop. Write the types of loops in C.
Loop is used to execute a set of statements repeatedly until a condition is false.
Types:
for
loopwhile
loopdo-while
loop
27. Write a program to find the factorial of a number using a loop.
#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 *= i;
}
printf("Factorial = %ld", fact);
return 0;
}
28. Define nested loop. Write a program to display a multiplication table using a nested loop.
Nested loop means a loop inside another loop.
#include <stdio.h>
int main() {
int i, j;
for(i=1; i<=10; i++) {
for(j=1; j<=10; j++) {
printf("%d\t", i*j);
}
printf("\n");
}
return 0;
}
29. Define control structure. Write the types of control structures in C.
Control structure directs the flow of execution of program statements.
Types:
- Sequence structure
- Selection structure (if, if-else, switch)
- Looping structure (for, while, do-while)
30. Write a program to check whether a number is prime or not.
#include <stdio.h>
int main() {
int n, i, flag=0;
printf("Enter a number: ");
scanf("%d", &n);
for(i=2; i<=n/2; i++) {
if(n % i == 0) {
flag = 1;
break;
}
}
if(flag==0 && n>1)
printf("Prime number");
else
printf("Not prime");
return 0;
}
31. Define array. Write its types.
Array is a collection of similar data elements stored in contiguous memory locations.
Types:
- One-dimensional array
- Multi-dimensional array (2D, 3D, etc.)
32. Write a program to find the sum of array elements.
#include <stdio.h>
int main() {
int a[100], n, i, sum=0;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i<n; i++) {
scanf("%d", &a[i]);
sum += a[i];
}
printf("Sum = %d", sum);
return 0;
}
33. Define string. Write the differences between string and character array.
String is a sequence of characters ending with null character '\0'
.
Differences:
- String is a sequence of characters, character array may or may not represent a string.
- String is always null-terminated, character array may not be.
- String functions can be applied only to strings.
34. Write a program to reverse a string.
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
strrev(str);
printf("Reversed string: %s", str);
return 0;
}
35. Define function. Write its advantages.
Function is a block of code that performs a specific task and can be reused.
Advantages:
- Reusability of code
- Easy debugging and testing
- Improves readability and modularity
- Saves development time
36. Write a program to find the sum of two numbers using a function.
#include <stdio.h>
int sum(int a, int b) {
return a + b;
}
int main() {
int x, y;
printf("Enter two numbers: ");
scanf("%d%d", &x, &y);
printf("Sum = %d", sum(x, y));
return 0;
}
37. “The number and types of arguments must be the same as the number and types of format specifiers used.” Clarify the statement with an example.
This statement means that in formatted I/O functions like printf()
, there must be a one-to-one correspondence between the format specifiers in the control string (e.g., %d
, %f
) and the variables (arguments) that follow. This correspondence must hold for both the total count and the data type of each item.
Valid Example:
int num1 = 2, num2 = 5, sum;
sum = num1 + num2;
printf("%d + %d = %d", num1, num2, sum);
Here, there are three %d
format specifiers and three integer arguments (num1
, num2
, sum
). This is correct.
Invalid Examples:
printf("%d * %d = %d", num1);
– Invalid because there are 3 specifiers but only 1 argument.printf("%d %f", num1, num2);
– Invalid because the second specifier%f
(for a float) does not match the type of the second argumentnum2
(an integer).
38. Why are precision and field width required? What happens if the field width given is less than the length of the variable?
Precision is used with floating-point numbers to specify the number of digits to display after the decimal point. Field width specifies the minimum number of characters to be used for displaying a value, which is useful for aligning output neatly.
If the specified field width is less than the actual length of the data:
- For
scanf()
: The function will only read up to the number of characters specified by the width. For example, inscanf("%3d", &num);
, if the user inputs14324
, only the first 3 digits (143
) will be read intonum
. - For
printf()
: The function will ignore the specified width and print the entire value. C does this to avoid truncating data and showing an incorrect value. Forprintf("Num = %3d", 12492);
, the output will beNum = 12492
.
39. Explain flags with a few examples.
Flags are special characters used within format specifiers to add formatting to the output, such as alignment and signs.
Flag | Description |
---|---|
- | Left-justifies the output within the specified field width. By default, it’s right-justified. |
+ | Forces the output to display a sign (+ or -) for signed numerical types. |
0 | Pads the output with leading zeros instead of spaces if a field width is specified. |
# | Used with octal (%o ) and hexadecimal (%x ) to prefix them with 0 and 0x respectively. |
Example: printf("%-8.2f", 82.4432);
will print “82.44
“. The number is formatted to two decimal places and left-justified within an 8-character space.
40. What are unformatted I/O functions? Write the syntax of putchar(), getchar(), getch(), getche().
Unformatted I/O functions read and write data as a raw stream of characters without applying any specific formatting options like width or precision. Examples include functions for reading/writing single characters or strings.
Function | Purpose | Syntax |
---|---|---|
getchar() | Reads a single character from standard input (waits for Enter key). | char_variable = getchar(); |
putchar() | Displays a single character to standard output. | putchar(char_variable); |
gets() | Reads a string from standard input. | gets(string_variable); |
puts() | Displays a string to standard output. | puts(string_variable); |
getch() | Reads a single character from the keyboard without echoing it to the screen. | char_variable = getch(); |
getche() | Reads a single character from the keyboard and echoes it to the screen. | char_variable = getche(); |
41. What do you mean by selective structures? When are they used?
Selective structures (also known as conditional or decision-making structures) are statements that allow a program to execute different blocks of code based on whether a certain condition is true or false. They are used whenever a program needs to make a choice, such as in validating input, controlling program flow, or implementing logic.
42. Write the syntax and working flow for various selection structures.
a. Simple if
Statement
Syntax:
if (condition) {
// True statements;
}
Working Flow: The condition is evaluated. If it’s true, the statements inside the block are executed. If it’s false, the block is skipped, and execution continues with the next statement after the `if` block.
b. if-else
Statement
Syntax:
if (condition) {
// Statements_T (executed if true);
} else {
// Statements_F (executed if false);
}
Working Flow: If the condition is true, `Statements_T` are executed. If the condition is false, `Statements_F` are executed.
c. else-if
Ladder
Syntax:
if (condition1) {
// Statement_1;
} else if (condition2) {
// Statement_2;
} else {
// Default_Statements;
}
Working Flow: The conditions are checked sequentially from top to bottom. As soon as a true condition is found, its corresponding block is executed, and the rest of the ladder is skipped. If none of the conditions are true, the final `else` block is executed.
d. Nested if
Statement
Syntax:
if (condition1) {
if (condition2) {
// Statement 1;
}
} else {
// ...
}
Working Flow: A nested `if` is an `if` statement inside another `if` or `else` block. The inner condition is only checked if the outer condition is met.
43. In which cases should `simple if` and `if-else` be used?
A simple if is used when you only need to perform an action for a single condition. If the condition is false, no special action is needed.
An if-else statement is used when there are two mutually exclusive outcomes. You need to perform one action if the condition is true and a different action if it is false.
- Case for
if-else
: Checking if a number is even or odd. A number must be one or the other, so an `if-else` is perfect. - Case for `simple if`: Finding the sum of only the even numbers from a list. You only care about the “is even” condition and can ignore the odd numbers.
44. When is an `else-if` ladder needed?
An else-if ladder is needed when there are more than two mutually exclusive conditions to check. It provides a way to choose one action from a list of several possibilities.
Example: To check if a number is positive, negative, or zero. A number can only be one of these three, making it a perfect case for an `else-if` ladder.
45. What sort of conditions necessitates the use of a `nested-if`?
A nested-if is necessary when you have conditions that are dependent on each other, or are not mutually exclusive. It allows you to test for a secondary condition only after a primary condition has been confirmed to be true.
Example: To check if a number is both even AND greater than 30. A number being even doesn’t exclude it from being greater than 30. You would first check if it’s even, and *then*, inside that `if` block, you would check if it’s also greater than 30.
46. Demonstrate converting a nested-if structure to an else-if ladder with logical operators.
You can often simplify a complex nested-if structure by combining conditions with logical operators (like `&&` for AND) in an else-if ladder.
Using Nested-if to find the largest of three numbers (a, b, c):
if (a > b) {
if (a > c) {
largest = a;
} else {
largest = c;
}
} else {
if (b > c) {
largest = b;
} else {
largest = c;
}
}
Equivalent logic using an else-if Ladder with `&&`:
if (a > b && a > c) {
largest = a;
} else if (b > a && b > c) {
largest = b;
} else {
largest = c;
}
47. Write the general form of a `switch` case.
The general form of a switch statement is:
switch (expression) {
case constant-1:
// statement-1;
break;
case constant-2:
// statement-2;
break;
...
default:
// default statement;
break;
}
48. What kind of condition determines whether a `switch` or `if-else` is to be used?
Use an if-else statement for conditions involving ranges (e.g., `x > 0`), floating-point numbers, or complex logical expressions. Use a switch statement for conditions where a single variable is being compared against multiple discrete integer or character constants.
49. What kind of variables or expressions can be used within the expression of a `switch`?
The expression in a `switch` statement must evaluate to a value of an integral type, which includes `int`, `char`, `short`, `long`, etc.
50. What can be the values of the `case` label/constant in a `switch` case?
The value for each `case` label must be an integer or character constant (a literal value like `1`, `’A’`, etc.). It cannot be a variable or an expression.
51. Explain the role of the `break` statement in a `switch` case. What happens if it is not used?
The break statement is used to exit the `switch` block immediately after a matching `case` is executed. If `break` is omitted, the program will “fall through” and execute the code in all subsequent `case` blocks until a `break` is encountered or the `switch` statement ends.
52. Write the general form and working flow of the conditional operator.
The conditional (or ternary) operator provides a concise way to write a simple if-else statement.
General Form: variable = condition ? value_if_true : value_if_false;
Working Flow: The `condition` is evaluated. If it is true, `value_if_true` is assigned to the `variable`. If it is false, `value_if_false` is assigned.
Example: x = (a > 4) ? (a + 3) : (a - 2);
If `a` is 5, the condition `5 > 4` is true, so `a + 3` (which is 8) is assigned to `x`.
53. Explain why repetitive structures are required.
Repetitive structures (loops) are required when a block of code needs to be executed multiple times. They provide a mechanism to repeat operations without having to write the same lines of code over and over again, making programs more efficient and concise.
54. What are the basic requirements for operating a loop? What is a running variable?
There are three basic requirements for a loop to operate correctly:
- Initialization: Setting the starting value of the loop control variable.
- Condition: The test that determines if the loop should continue executing.
- Update: Modifying the loop control variable in each iteration (e.g., incrementing or decrementing it) to eventually make the condition false.
A running variable (or loop control variable) is the variable used in these three parts to control the loop’s execution.
55. Write the syntax for `for`, `while`, and `do-while` loops.
a. For Loop
for (initialization; condition; update) {
// statements;
}
b. While Loop
initialization;
while (condition) {
// Statements;
update;
}
c. Do-While Loop
initialization;
do {
// Statements;
update;
} while (condition);
56. When should we use a `for` loop? How does it differ from a `while` loop?
A for loop is typically used when the number of iterations is known before the loop starts. For example, if you need to process 10 numbers, a `for` loop is a natural choice.
A while loop is used when the number of iterations is not known in advance and depends on a condition that is met during execution. For example, reading from a file until you reach the end.
57. When is a `while` loop used? What happens if initialization or update is done incorrectly?
A `while` loop is used when the number of iterations is not fixed and depends on a condition determined at runtime. For example, summing the digits of a user-inputted number; the loop runs once for each digit, which is unknown beforehand.
If the initialization of the running variable is done inside the body of the loop, or if the update of the running variable is not done at all, the loop’s condition may never become false, resulting in an infinite loop.
58. Distinguish between `while` and `do-while` loops.
`while` loop | `do-while` loop |
---|---|
Entry-Controlled Loop: Condition is checked before executing the body. | Exit-Controlled Loop: Condition is checked after executing the body. |
The body of the loop may execute zero times if the condition is initially false. | The body of the loop is guaranteed to execute at least once. |
The `while` statement is not terminated by a semicolon. | The `while(condition)` part must be terminated by a semicolon. |
59. Explain `break` and `continue` statements with an example.
Break Statement: Immediately terminates the innermost loop or `switch` statement in which it appears. Execution resumes at the statement following the loop.
Continue Statement: Skips the rest of the current iteration of a loop and immediately proceeds to the next iteration.
60. Compare `break` and `continue` statements.
Break Statement | Continue Statement |
---|---|
Used in loops and `switch` cases. | Used only in loops. |
Terminates the entire loop or `switch` structure. | Skips the current iteration but continues the loop. |
61. What are nested loops? When are they used?
Nested loops are loops placed inside the body of another loop. They are used when you need to perform repetitive tasks that themselves contain another set of repetitive tasks. Common use cases include:
- Working with two-dimensional structures like matrices or printing patterns.
- Repeating a problem that requires a loop for a range of values (e.g., finding all prime numbers within a certain range).
62. Demonstrate how to change a `for` loop to a `while` loop.
Any `for` loop can be converted to an equivalent `while` loop by moving the initialization before the loop and the update statement inside the loop.
For Loop:
for (initialization; condition; update) {
// statements;
}
Equivalent While Loop:
initialization;
while (condition) {
// statements;
update;
}
63. Explain the working flow of a nested `for` loop with an example.
In a nested loop, the inner loop completes all its iterations for each single iteration of the outer loop.
Example: To print a pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
This is achieved with a nested loop where the outer loop controls the rows and the inner loop controls the columns in each row.
64. What happens if a nested loop contains the same running variable?
Using the same running variable for both the inner and outer loops will cause logical errors. The inner loop will modify the variable that the outer loop depends on, leading to unexpected behavior, often resulting in an infinite loop or premature termination of the outer loop.
65. Which conditions will cause a loop to run indefinitely?
A loop becomes an infinite loop when its terminating condition is never met. This can happen if:
- The update statement for the running variable is missing.
- The initialization is incorrect or reset inside the loop.
- The condition is always true (e.g., `while(1)`).
- The update logic moves the running variable away from the terminating condition instead of towards it.
66. Define `function` and mention its advantages.
A function is a self-contained module of code that performs a specific task. Advantages include:
- Code Reusability: A function can be called multiple times, avoiding code duplication.
- Reduced Program Length: Reusing code makes the overall program shorter.
- Modularity: Complex problems can be broken down into smaller, simpler tasks.
- Easy Debugging: It’s easier to find and fix errors in small, isolated functions.
- Division of Tasks: In a team, different programmers can work on different functions simultaneously.
67. Explain the `main` function. How does it differ from other functions?
The main function is the mandatory entry point for every C program. Execution of the program starts from the `main` function.
It differs from other functions because it is called automatically by the operating system when the program is run, whereas other functions must be explicitly called from within the program.
68. Describe function declaration (prototype), function call, and function definition.
Every user-defined function has three key parts:
- Function Declaration (Prototype): This tells the compiler about the function’s name, return type, and the types of its parameters before it is used. It ends with a semicolon. (e.g.,
float sum(float, float);
) - Function Call: This is where the function is invoked to perform its task. The program’s control transfers to the function’s definition. (e.g.,
result = sum(a, b);
) - Function Definition: This contains the actual block of code that is executed when the function is called. It consists of the function header and the function body. (e.g.,
float sum(float num1, float num2) { ... }
)
69. Differentiate formal arguments from actual arguments.
An argument is a value passed to a function.
Actual Arguments | Formal Arguments | |
---|---|---|
Where are they used? | In the function call. They are the actual values or variables being passed. | In the function definition and declaration. They are the placeholders that receive the values. |
Scope | They are defined in the calling function. | They are local variables that exist only within the called function. |
Example | In result = sum(a, b); , `a` and `b` are actual arguments. | In float sum(float num1, float num2) {...} , `num1` and `num2` are formal arguments. |
70. Explain the use of return statement. Is it mandatory to use return statement?
Whenever a function needs to return a value, then a return statement can be used. The return statement, however, can return only a single value.
If the function is built to return a certain value to the calling function, then it is mandatory to use a return statement. But if the function has void as a return type, then the return statement can be avoided.
71. What happens to the statements written after the return statement?
The statements after the return statement will not execute. Since the return statement sends the control back to the calling function, the control never reaches the statements written after the return statement.
72. What does the return type symbolize in function definition and declaration? How is it related to the return statement?
The return type in function declaration and definition symbolizes whether the function returns a value to the calling function or not. If the return type is void, it represents that the function doesn’t return a value, while other data types such as int, float, char in the return type represent that the function returns a value.
The return statement can be avoided if the return type is void. But if the return type is not void, then the return statement is mandatory.
74. What does function declaration suggest? How are functions called?
Function declaration provides the following information:
- Name of the function: Generally, this defines what the function does.
- Return type: Symbolizes whether the function returns a value after processing.
- List of arguments or parameters: Represents what type and how many values are required by the function to operate.
Functions are called with their name followed by the list of parameters or arguments. A function call must be used or assigned if the returned value should be taken into consideration. But if the function does not return any value or it returns a value which is not of much use, then the function call need not be assigned to or used.
75. “The number and type of arguments must be the same in function definition”, clarify the statement.
The number and type of arguments must be the same in the function declaration, function call, and function definition.
76. Is it mandatory to have a function declaration? “Any entity must be declared first before it is used”, explain the statement.
Function declaration can be omitted if the function definition is written before its call. So, function declaration is not mandatory.
Every entity in C programming must be declared before it is used. Declaration gives information not only to the user but also to the compiler about the type and name of the entity we are using. With such information, the compiler will interpret statements correctly. Also, the compiler can decide how much storage space to allocate. Hence, every entity such as variables and functions must be declared first prior to its use.
77. Describe different types of functions based on return type and arguments.
Based on return type and argument, the function can be categorized into four types. The description is based on where the input, processing, and output will take place.
- Function with no arguments and no return type: This kind of function can have no information exchange with other functions unless global variables are used. Generally, all the operations such as input, processing, and output are done within the function.
- Function with arguments and no return type: Such functions take input values in the calling function, but the processing and output part of the problem will be within the function itself.
- Function with arguments and return type: This function, usually, contains only the processing part. The input and output of the problem will be in the calling function. The inputs will be passed as arguments while the result will be returned through the return statement of the function.
78. What are library functions? How do they differ from user-defined functions?
Library functions are inbuilt functions which consist of lines of code to carry out a particular operation. Library functions are declared in header files, so the inclusion of the corresponding header file is a must whenever the library functions are used.
The differences between library functions and user-defined functions are listed below.
SN | Library Function | User-Defined Function |
---|---|---|
1. | Inbuilt functions for a specific purpose. | Defined by the user based on the problem specified. |
2. | Requires a header file to be included. | A header file is not required. |
3. | The definition is already written. | The definition should be written by the user. |
4. | It cannot be modified. | It can be modified as required. |
79. What do you mean by passing by reference? When is it used?
Passing by reference in a function means to pass the address of the variable rather than its value. When a function needs to return more than one value, which it cannot do through the return statement, then in such situations passing by reference is used.
80. Differentiate between pass by value and pass by reference.
The differences between pass by value and pass by reference can be summarized as:
SN | Pass by value | Pass by reference |
---|---|---|
1. | The value of the variable is passed. | The address of the variable is passed. |
2. | Changes to formal arguments in the called function do not affect the value of actual arguments in the calling function. | Any changes made to the formal arguments in the called function change the value of the actual arguments in the calling function. |
3. | A return statement should be used to return a value. | A return statement is not required in this case but can be used. |
4. | Only one value can be returned to the calling function. | More than one value can be returned to the calling function. |
81. What changes can be seen in the function declaration, function call, and function definition while using pass by reference?
When using pass by reference, the following changes can be seen:
- Function declaration: use of pointer notation to hold the address.
void function_name(datatype *, datatype *);
- Function call: use of the address operator to pass the address.
function_name(&var_name1, &var_name2);
- Function definition: use of pointer notation to hold the address.
void function_name(datatype *var_name1, datatype *var_name2) {}
82. What sort of variables require the address operator in a function call while using pass by reference?
The address operator is required by those variables whose value needs to be changed in the called function, but its changed value is required in the calling function. For example: To find the sum and difference of two numbers, there are two inputs, which don’t require change, and two outputs, which require change. So the function call would be like:
calc(num1, num2, &sum, &diff);
83. Explain different ways of returning multiple values from a function.
The different ways of returning multiple values from a function are:
- Using pass by reference: It works directly on the location of actual arguments, so a change can be seen in the calling function when changes are made in the called function. So, it can return multiple values.
- Using an array: Since an array name, in itself, is an address of the first element, it is also a kind of pass by reference.
- Using a structure: Since a structure can contain multiple members, returning a single structure results in returning multiple values.
84. Define recursion. Explain how it differs from iteration.
Recursion is a process where a function calls itself repeatedly. The difference between recursion and iteration is listed in the table below.
SN | Recursion | Iteration |
---|---|---|
1. | It is a function that calls itself unless the base condition is reached. | Iterative instructions are loop-based repetitions of a process. |
2. | Infinite recursion occurs if the recursive solution does not reduce the problem in a manner that converges on the base condition. | An infinite loop occurs with iteration if the loop-condition is always true. |
3. | It terminates when a base case is recognized. | It stops when the loop-condition is false. |
4. | It is usually slower than iteration due to the overhead of maintaining the stack. | It does not use a stack so it is faster than recursion. |
85. What are the requirements to solve a problem recursively?
The requirements to solve a problem recursively are:
- Base condition: It is the known value to the programmer that terminates the recursion. For example, to calculate factorial, we know that 0! = 1 or 1! = 1, so either case can be taken as a base condition.
- Recursive solution: It is the solution that converges towards the base condition after each execution. For example, to calculate the factorial of number n, we know that n! = n x (n-1)! In programming,
fact(n) = n * fact(n-1)
. Here,n * fact(n-1)
is the recursive solution to calculate the factorial of a given number.
86. List the merits and demerits of using a recursive function.
The advantages and disadvantages of recursion can be listed as:
Advantages:- Complex problems can be solved in an easier way.
- Less coding needs to be done.
- Difficult to find the converging solution.
- It uses more memory.
- It is usually a slower process; push and pop operations in the stack cause it to be a bit slower.
87. Define storage class. Compare automatic, extern, and static variables.
A storage class in C programming represents the scope along with the lifetime of a variable. It also represents where the value is stored and what its initial value is when first declared. All variables except the register type are stored in main memory. auto variables are equivalent to local variables; all local variables are auto by default. extern variables are equivalent to global variables.
The different storage classes and their descriptions are listed in the table below.
SN | Storage Class | Initial Value | Scope | Life |
---|---|---|---|---|
1. | auto | Garbage value | Local | Within the function only |
2. | extern | Zero | Global | Till the end of the program |
3. | static | Zero | Local | Till the end of the program |
88. Demonstrate the use of global variables and static variables.
The following program demonstrates the use of global variables and static variables.
#include#include void globalCheck(); void staticCheck(); int x = 5; void main() { clrscr(); globalCheck(); staticCheck(); staticCheck(); getch(); } void globalCheck() { printf("\n\nThe value of x in another function is %d\n", x); } void staticCheck() { static int i = 0; i++; printf("\nThe value of i is %d", i); }
In this program, the variable x is a global variable which is accessed in the main function as well as in the globalCheck() function. Also, the variable i is declared as static, which retains its value between different function calls.
89. What do you mean by a derived data type?
Data types that are derived from fundamental data types are called derived data types. They simply add some functionality to the basic data types. Arrays and pointers are the basic examples of derived data types.
90. Define array. When and why are arrays required?
An array is simply a list or collection of variables of the same type which share a common name but are accessed through a different index within a square bracket. The variables are assigned contiguous memory locations.
When the problem is related to not one or two variables but a collection of numbers, then arrays are used. The use of an array ensures efficient programming. For example, if we need to add 100 numbers, then the declaration of 100 variables individually would be tedious and impractical, but the use of an array makes it easier and more efficient by making the declaration and access of numbers short and easy.
91. Explain array declaration and initialization for different data types.
The array declaration and initialization for different data types are listed below:
One-dimensional Array:- Declaration:
data_type array_name[size];
Examples:int num[5];
,char list[10];
,float marks[20];
- Initialization at declaration:
int num[5] = {1, 2, 3, 4, 5};
char list[] = {'a', 'b', 'c', 'd'};
- Declaration:
data_type array_name[row_size][col_size];
Examples:int num[5][5];
,char list[10][10];
- Initialization at declaration:
int num[2][2] = {{1, 2}, {3, 4}};
char list[][] = {{'a', 'b'}, {'c', 'd'}};
92. What does the name of an array represent? Explain with an example how to access elements of an array.
The name of an array holds the address of the first element of an array. So, it represents the base address of that array.
For a one-dimensional array, the elements are accessed by using the array name followed by an index within a square bracket. For example, if an array is declared as: int num[5];
, then num[0]
and num[1]
are used to access the first and second elements respectively.
For a two-dimensional array, the elements are accessed using the array name followed by two square brackets within which the row index and column index should be given. For example, if an array is declared as: int list[3][3];
, then to access the value we use list[0][1]
to access the value of the first row and second column.
93. Demonstrate the difference that can be seen in the function declaration, function call, and function definition, when a single array element is passed and when the complete array is passed.
Let us consider a simple example to demonstrate the difference.
Assuming, Array declaration and initialization: int num[5] = {1, 2, 3, 4, 5};
and a function check()
to do some operation.
SN | Section | Passing Single Element | Passing Complete Array |
---|---|---|---|
1. | Function declaration | void check(int); |
void check(int[]); |
2. | Function call | check(num[1]); |
check(num); |
3. | Function definition | void check(int x) {} |
void check(int x[]) {} |
94. “Passing a single element of an array indicates passing by value whereas passing the complete array (array name) represents pass by reference”, explain the statement with an example.
When we pass a single element, we use the array name with an index. For instance, let num
be an array defined as: int num[10];
; then num[2]
represents the third element of an array. Since it stores a value, passing it in such a way symbolizes passing by value. But when an array name is passed, it passes the starting address of an array, as we know that the name of an array represents the address of the first element. For example, passing the array name num
to the function represents passing the address of num[0]
, as num
is equivalent to &num[0]
. Using that base address, all other elements can be accessed. Hence, passing the array name or the complete array represents pass by reference.
95. Define string and null character. Explain, with an example, about string constants and string variables.
A string is an array of characters terminated with a null character. The null character represents the end of a string. The null character is written as \0
in C programming.
Let us take an example to demonstrate string constants and variables.
char name[20] = "Johnson";
Here, the variable name
is declared as an array of characters, which can be used as a string variable. But to use it as a string variable, it must be assigned a string constant or a set of characters with a null character at the end. The set of characters defined within double quotation marks is a string constant. There will be a default null character in a string constant. While a string formed from a set of characters must be terminated with a null character manually.
96. How are strings declared? Demonstrate the different ways of initializing strings.
Strings are declared using an array, with char
as the data type.
char str[10];
Here, str
is a string variable.
Strings are initialized as:
char str[] = "Johnson";
char str[] = {'N', 'E', 'P', 'A', 'L', '\0'};
The size of the array is optional when strings are initialized in the declaration. The size of the string will be equal to the number of characters. If the size needs to be declared, then it must be equal to or greater than the number of characters initialized.
97. What is the drawback of using `%s` in `scanf` to read a string? Illustrate different ways of reading a string.
When %s
is used as a format specifier in scanf
, it does not read a string with a space. All characters before the space character will be read, but other characters will be ignored.
Different ways of reading a string are as follows:
- Using unformatted input function:
gets(string_variable);
- Using formatted input function:
scanf("%s", string_variable);
- Character search sets can be used:
scanf("%[^\n]", string_variable);
reads characters unless a new line is detected. - Reading character-wise:
i = 0; while((string_variable[i] = getchar()) != '\n') { i++; } string_variable[i] = '\0';
98. Explain why the address operator (ampersand) is not used while reading a string.
The string is the name of an array of characters. Since the name of an array represents the address of the first element, the string also symbolizes the address of the first character. Hence, the address operator is not used while reading a string using scanf()
.
99. Describe the general form, purpose, and return value (if any) of the following string functions: `strlen()`, `strcpy()`, `strcat()`, `strcmp()`.
The descriptions of different string functions are listed in the table below:
SN | Function | General Form | Purpose | Returning value |
---|---|---|---|---|
1. | strlen() | len = strlen(str1); |
Gives the length of a string (str1 ). |
Length as an integer. |
2. | strcpy() | strcpy(str1, str2); |
Copies the value of one string (str2 ) to another string (str1 ). |
None |
3. | strcat() | strcat(str1, str2); |
Combines two strings (str1 and str2 ) into one (str1 ). |
None |
4. | strcmp() | c = strcmp(str1, str2); |
Compares two strings (str1 , str2 ). |
Difference of ASCII value of characters. |
100. Explain briefly about an array of strings.
As a one-dimensional array of characters represents a string, a two-dimensional array of characters represents an array of strings.
- General Form:
char string_name[number_of_strings][Number of characters in each string];
char namelist[10][20];
it represents an array of strings with 10 strings with each 20 characters long. - Initialization:
char namelist[10][10] = {"Johnson", "Sarah", "Holmes"};
In two-dimensional declarations of arrays of characters, if the variable is followed with two pairs of square brackets then it represents a single character. For instance, namelist[1][1]
represents the character ‘a’. In simple, it selects the second row and then the second column, pointing to the character ‘a’. But if the variable is followed with a single pair of square brackets then it represents a string. For example, namelist[2]
symbolizes the string “Holmes”.
101. What is a pointer? Differentiate a pointer with an array.
A pointer is a variable which holds the address of another variable. Like other variables, it must be declared before using it. Its general form is:
data_type *var_name;
int *p;
it represents a pointer declaration with the variable name p
and integer as its type.
The differences between a pointer and an array are as follows:
SN | Array | Pointer |
---|---|---|
1. | Collection of similar types of variables which hold a certain value. | A variable which holds the address of another variable. |
2. | It is static in nature; size is fixed at declaration and cannot be modified. | It is dynamic in nature; size can be allocated based on requirement. |
3. | Size is defined simply using an integer within the square bracket in the declaration. | Size is defined using library functions, such as malloc() , calloc() . |
102. List the advantages of using a pointer.
The various advantages of a pointer are:
- It provides direct access to memory.
- It provides a way to return more than one value from a function.
- It reduces storage space and complexity of the program.
- It reduces the execution time of the program.
- It provides an alternative way to access array elements.
- It helps to build complex data structures like linked lists, stacks, queues, trees, etc.
103. Explain the role of `*` and `&` operators in C programming.
The reference operator (&
) is used to provide the address of a variable, whereas the dereference operator (*
), when used with a variable, provides the value stored in the corresponding address.
For example, let us consider:
int a = 4;
int *p;
p = &a;
Here, &p
gives the address of the pointer variable p
, &a
gives the address of the variable a
. But *p
gives the value 4, since p
gives the address of a
.
104. Compare array and pointer. Describe how array and pointer can be used interchangeably.
An array and a pointer are not the same thing, but their notations can be used interchangeably. The name of an array represents the address of the first element, so it can be taken as a pointer.
int num[5];
here num
is equivalent to &num[0]
, so num
is a pointer.
The following table shows the details about how array and pointer can be used interchangeably.
SN | Access | Array Notation | Pointer Notation |
---|---|---|---|
1. | Address of i-th element | &num[i] |
(num + i) |
2. | Value of i-th element | num[i] |
*(num + i) |
105. Explain about null pointer and void pointer.
A null pointer is one which is not pointing to anything. Whereas a void pointer is one which does not have any data type associated with it, but can be assigned an address of any type. A null pointer cannot be dereferenced, while to dereference a void pointer, it needs type casting.
A null pointer is declared as:
int *p = NULL;
A void pointer is declared as:
void *p;
A null pointer is a value that any type of pointer may take to indicate that it is pointing nowhere, while a void pointer is a special type of pointer that can point to somewhere without a specific type.
106. What is a user-defined data type?
A user-defined data type is a kind of data type which uses the built-in data types and other user-defined data types that model the structure and behavior of data in applications.
107. Define structure and explain briefly why it is required.
A structure is a heterogeneous user-defined data type which contains members of different data types grouped under a single name. Many real-time problems, such as Player’s Record, Library management, require information to be saved. The information will be of different types, and such information can be grouped together for easier handling. Since many problems require combining data items of different kinds, a structure is required.
108. Write the general syntax of a structure. What will be the size of a structure?
The general syntax of a structure is:
struct tag_name { data_type member 1; data_type member 2; ... data_type member n; };
Example:
struct profile { char name[30]; int age; };
The size of a structure will be the sum of the sizes of all members of the structure. In the above example, the size of the structure profile will be 32.
109. What is the significance of the dot operator in C programming?
The dot operator is used to access the members of a structure.
110. Write the difference between a structure and an array.
The differences between a structure and an array are listed below.
SN | Arrays | Structures |
---|---|---|
1. | It is a collection of related data elements of the same type. | It can have elements of different types. |
2. | It is a derived data type. | It is a user-defined data type. |
3. | The name of an array represents the address of the first element. | The name of the structure represents the user-defined data type. |
111. When is an array of structures used? Illustrate the difference in passing a single structure and an array of structures to a function with an example.
When it is required to work with a list of records containing various information, an array of structures is used. The following table shows the difference that can be seen while passing a single structure and passing an array of structures. Let us consider a function named record()
and a structure named profile
, then:
SN | Section | Passing single structure | Passing array of structure |
---|---|---|---|
1. | Variable Declaration | struct profile p; |
struct profile p[20]; |
2. | Function Declaration | void record(struct profile); |
void record(struct profile[]); |
3. | Function call | record(p); |
record(p); |
112. What are the ways of returning an array of structures from a called function to the calling function?
The following methods can be used to return an array of structures to the calling function.
- Pass the array of structures, which needs to be returned, as an argument in the function call.
- Return the reference of the array of structures from the called function to the calling function through the return statement.
113. Explain briefly about the nested structure along with its syntax.
Whenever there is a presence of a structure as a member of another structure, then it forms a nested structure. Also when one structure is declared inside of another structure then a nested structure is formed. The following example illustrates the concept of a nested structure.
Nested Structure 1struct date { int mm, dd, yy; }; struct profile { char name[20]; int age; struct date dob; };Nested Structure 2
struct profile { char name[20]; int age; struct date { int mm, dd, yy; } dob; };
Variable declaration: struct profile p;
Accessing members: p.age
, p.dob.mm
, p.dob.yy
. The members of a structure date
should be accessed through its own variable.
114. Illustrate the difference between structure and union.
The differences between a structure and a union are:
SN | Structure | Union |
---|---|---|
1. | The keyword struct is used. |
The keyword union is used. |
2. | Each member is allocated a memory space. The size of the structure equals the sum of the sizes of its members. | Memory is allocated based on the size of the highest space requirement. Its size is equal to the size of the largest member. |
3. | Each member within a structure is assigned a unique memory location. | Memory allocated is shared by individual members of the union. |
115. What is a file? Why are files required?
Sometimes information can be stored in auxiliary memory devices, which is in the form known as data files. Files are required:
- To store data permanently.
- To access and alter the information whenever necessary.
116. Explain briefly about the file structure `FILE` and `FILE` pointer.
The FILE
structure provides the necessary information about a file or stream which performs input and output operations. The FILE
structure is defined in the stdio.h
header file. A pointer of type FILE
is a file pointer, which is used to represent the file to be worked with.
117. Describe different modes of opening a file.
The different modes of opening a file are listed as:
SN | Mode | Description |
---|---|---|
1. | "r" |
Opens a file for reading, but the file must exist. |
2. | "w" |
Creates an empty file for writing. If the file already exists, then the content will be overwritten. |
3. | "a" |
Adds data at the end of the file. Also creates a file, if it does not exist. |
118. Where will be the position of the `FILE` pointer for different file opening modes?
The position of the FILE
pointer will be at the beginning for reading and writing modes whereas the FILE
pointer will be positioned at the end of the file for append mode.
119. How can we access a file randomly? Write a one-line code for the following access.
The function fseek()
is used to access the file randomly. It is used to position the file pointer at the specified location as required.
- To access the 23rd byte from the beginning of the file:
fseek(fp, 23, SEEK_SET);
- To access the 5th block of a file from the start of a file:
fseek(fp, 5 * size_of_block, SEEK_SET);
120. What is error handling? Why is it done?
Error handling refers to the anticipation, detection, and resolution of programming errors. Error handling is done to prevent the unexpected termination of the program.
121. What are the different errors during I/O operations? How are errors handled during different file operations?
Only a few, out of many, errors during file I/O operations are listed below:
- No such file or directory
- Permission denied
- Bad file number
The following methods can be used to handle different types of errors during file operations.
- Check for
NULL
pointer: the functionfopen
returns aNULL
pointer if it cannot open the file.fptr = fopen("demo.txt", "r"); if(fptr == NULL) { printf("Error Occurred"); exit(-1); }
- Using the
ferror()
macro: it tests the given file for a read or write error.if(ferror(file_pointer) != 0) { printf("Error Detected"); }
122. Explain about different types of functions that are generally used.
The various functions along with their descriptions are listed below.
- fopen(“String1”, “String2”): Opens a file.
String1
is the filename,String2
is the mode. - fclose(file_pointer): Closes a file.
- putc(arg1, arg2): Writes a character to a file.
- getc(arg1): Reads a character from a file.
- fprintf(file_pointer, “control string”, …): Writes formatted output to a file.
- fscanf(file_pointer, “control string”, …): Reads formatted input from a file.
123. Write the difference between Writing mode and Appending Mode.
The differences between Writing mode and Appending Mode are:
SN | Writing Mode | Appending Mode |
---|---|---|
1. | File Pointer points at the beginning. | File Pointer points at the end of the file. |
2. | Content of the file is overwritten. | Content is added at the end. |