Unit - 1
Planning the Computer Program
Q1) Define problem solving?
A1) A computer is a tremendously powerful and adaptable equipment that can execute a wide range of activities, yet it lacks intelligence and thinking ability.
Many jobs are carried out by the computer exactly how it is instructed. This sets the onus on the user to provide accurate and specific instructions to the computer so that it can complete the essential task correctly. A faulty or confusing command can be dangerous at times.
The computer cannot solve the problem on its own; instead, the computer requires step-by-step instructions. In truth, it is not the computer's job to solve problems.
The programmer is responsible for expressing the answer to the problem in terms of simple procedures that the computer can comprehend and perform.
Problem-solving is a step-by-step process of examining information about a situation and coming up with effective responses.
To solve a problem using a computer, one must go through a series of stages or phases.
Q2) What are the steps of problem solving?
A2) Problem Solving Steps
Problem solving is a creative process that involves systematization and automation. There are a variety of steps that can be performed to improve one's problem-solving abilities.
In order to solve an issue, a problem-solving technique follows a set of procedures. Let's have a look at each stage one by one:
- Problem Definition Phase:
Only after a thorough understanding of the problem is it possible to achieve success in solving it. That is, we can't expect to fix an issue we don't comprehend. As a result, comprehending the problem is the first step toward its resolution.
We must highlight what must be done rather than how it must be done throughout the problem definition phase. That is, we aim to extract the issue statement's precisely defined set of tasks.
Inexperienced problem solvers frequently rush through the issue-solving process, only to discover that they are either tackling the wrong problem, solving the wrong problem, or solving only one problem.
2. Getting Started on a Problem:
A issue can be solved in a variety of ways, and there may be multiple solutions. As a result, determining which option would be more fruitful is challenging. C programming is used to solve problems.
Even though the problem has been defined, you may not know where to begin tackling it. Such a barrier can develop when you become preoccupied with the details of the implementation before you have fully comprehended or worked out a solution.
The best advise is to avoid getting caught up in the details. These can be added later once the problem's complexities are known.
3. Use of Specific Examples:
We can employ heuristics, or the rule of thumb, to get started on a problem. This technique allows us to begin by identifying a specific problem that we want to address and attempting to figure out the mechanism that will allow us to tackle that problem.
Because the relationship between the mechanism and the problem is more clearly defined, it is usually much easier to work out the details of a solution to a specific problem.
This method of focusing on a specific problem can provide us with the necessary groundwork to begin solving the larger problem.
4. Similarities Among Problems:
Consider a specific example as one approach to get started. Another option is to apply previous experience to current issues. As a result, it's critical to look for parallels between the current challenge and previous problems that we've handled.
The more experience one has, the more tools and strategies one can apply to the problem at hand. However, it might occasionally prevent us from finding a desirable or superior solution to the situation.
The capacity to view a situation from various perspectives is an important talent to strive to cultivate in problem-solving.
One must be able to turn a problem inside out, sideways, backwards, forwards, and so on in metaphorical terms. It should be possible to get started on any problem once this skill has been mastered.
5. Working Backwards from the Solution:
In some circumstances, we can assume we already know the answer to the problem and then proceed backwards to the beginning. Even a wild guess at the solution to the problem might be enough to get us started on it.
By writing down the many steps and explorations done, we can standardize the studies and avoid duplication of work.
Another activity that aids in the development of problem-solving skills is to intentionally look back on how we went about identifying the solution after we have solved an issue.
Q3) What is an Algorithm?
A3) Algorithm
An algorithm is the finite set of English statements which are designed to accomplish the specific task. Study of any algorithm is based on the following four criteria :
1. Design of algorithm: This is the first step in the creation of an algorithm. Design of algorithm includes the problem statement which tell user about the area for which algorithm is required. After problem statement next important thing required is the information about available and required resources. The last thing required in design of algorithm phase is information about the expected output.
2. Validation of algorithm: Once an algorithm is designed, it is necessary to validate it for several possible input and make sure that algorithm is providing correct output for every input. This process is known as algorithm validation. The purpose of the validation is to assure us that this algorithm will work correctly independently of the issues concerning the programming language it will eventually be written in.
3. Analysis of algorithm: Analysis of algorithms is also called as performance analysis. This phase refers to the task of determining how much computing time and storage an algorithm requires. The efficiency is measured in best case, worst case and average case analysis.
4. Testing of algorithm: This phase is about to testing of a program which coded as per the algorithm. Testing of such program consists of two phases:
● Debugging: It is the process of executing programs on sample data sets to determine whether faulty results occur or not and if occur, to correct them.
● Profiling: Profiling or performance measurement is the process of executing a correct program on data sets and measuring the time and space it takes to compute the result
Characteristics of an algorithm
● Input: Algorithm must accept zero or more inputs.
● Output: Algorithm must provide at least one quantity.
● Definiteness: Algorithm must consist of clear and unambiguous instruction.
● Finiteness: Algorithm must contain finite set of instruction and algorithm will terminates after a finite number of steps.
● Effectiveness: Every instruction in algorithm must be very basic and effective.
Q4) Write about flowchart?
A4) Flow chart
Flowchart is a diagrammatic representation of the sequence of logical steps of a program. Flowcharts use simple geometric shapes to depict processes and arrows to show relationships and process/data flow.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
Symbol | Symbol Name | Purpose |
Start/Stop | Used at the beginning and end of the algorithm to show start and end of the program. | |
Process | Indicates processes like mathematical operations. | |
Input/ Output | Used for denoting program inputs and outputs. | |
Decision | Stands for decision statements in a program, where answer is usually Yes or No. | |
Arrow | Shows relationships between different shapes. | |
On-page Connector | Connects two or more parts of a flowchart, which are on the same page. | |
Off-page Connector | Connects two parts of a flowchart which are spread over different pages. |
Guidelines for Developing Flowcharts
These are some points to keep in mind while developing a flowchart −
● Flowchart can have only one start and one stop symbol
● On-page connectors are referenced using numbers
● Off-page connectors are referenced using alphabets
● General flow of processes is top to bottom or left to right
● Arrows should not cross each other
Q5) Describe debugging?
A5) Debugging
Debugging is the process by which a developer (who may or may not be the author of the code he is trying to debug) attempts to update a portion of previously written code using various tools accessible to him in order to eliminate an error that was not discovered during compile (or syntax checking) time (in other words that has surfaced at the run time subject to certain conditions).
Different types of debugging
Debugging can be accomplished in a variety of methods. But, before we go over them, it's important to recognise that any debugging process is made up of two core tasks. First, look at the values of various variables at various phases of the programme execution, and then look at how the control flows (Are we approaching the "if" block?). Is it ever reached the "break" statement inside the "while" loop?
● Print statements
While running the code, you use "print" (or "printf" or "echo" or whatever the equivalent is) to output certain values. This is probably the simplest approach to begin debugging. It is also the most inconvenient and time-consuming method. It's inconvenient since we can simply leave all (or portion of) those print statements in the code once we're done, resulting in messy code (and in some very rare occasions, breaking it in production.). It takes time since we have to write all of the print statements before monitoring them while the programme is running.
● Using logging
This method is text-based, similar to printing, but with a lot more features. We may actually transmit structured messages from our software to log management platforms and then utilise those tools to run various searches across the corpus of text to get the necessary information, rather than using "stdout" as the output mechanism (as with printing). It is an extremely efficient method. And for any genuine production software, logging is a must. However, it has its own limitations. We still have to write all of our log statements by hand (and remove them later if they aren't needed), and we can't peer behind the hood of programme execution in most circumstances.
● Interactive (Symbolic) debugger
If you've ever used a programme like "gdb," (or “ipdb” or “pydb” or “lldb” or anything like that) you'll understand what I'm talking about. For the rest, there are tools on your development machines that give you full interactive access to the programme at runtime and allow you to investigate extremely low level (and high level) issues on a running piece of code. The benefit of this method of debugging is that it requires no additional work on your behalf to begin debugging the code. You simply start the debugger and point it to the executable, and there you have it! You're in the middle of a running programme, but you have complete control over its investigation (and, if necessary, change) in real time.
Q6) What are the steps for debugging?
A6) Steps for Debugging in C
- Make a file named fib.c.
#include <stdio.h>
Int main()
{
int i;
int numTerms = 10;
int t1 = 0, t2 = 1;
int nextTerm;
printf("Fibonacci Series: ");
for (i = 1; i <= numTerms; ++i)
{
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
2. Use the gcc compiler and the -g flag to enable debug symbols when compiling the fib.c file.
3. Debug the fib application with TotalView.
4. By clicking on the line number, you can set a breakpoint at line 12.
5. Press the Green GO button to begin debugging. TotalView executes the programme until it reaches the line 12 breakpoint, at which point it quits.
6. Step through the loop with the Next button, watching the values of the variables in the Local Variables box change.
7. TotalView is a unique function that allows you to record the execution of your programme so that you may look back in time.
By pressing the Red Record button on the Replay Engine toolbar, you can enable reverse debugging and then go backward and forward through the code.
Q7) Explain the types of error?
A7) Type of errors
- Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax are known as syntax errors. This compiler error indicates something that must be fixed before the code can be compiled. All these errors are detected by compiler and thus are known as compile-time errors.
Most frequent syntax errors are:
- Missing Parenthesis (})
- Printing the value of variable without declaring it
- Missing semicolon like this:
// C program to illustrate
// syntax error
#include<stdio.h>
Void main()
{
Int x = 10;
Int y = 15;
Printf("%d", (x, y)) // semicolon missed
}
Error:
Error: expected ';' before '}' token
Syntax of a basic construct is written wrong. For example: while loop
// C program to illustrate
// syntax error
#include<stdio.h>
Int main(void)
{
// while() cannot contain "." as an argument.
While(.)
{
Printf("hello");
}
Return 0;
}
Error:
Error: expected expression before '.' token
While(.)
In the given example, the syntax of while loop is incorrect. This causes a syntax error.
2. Run-time Errors: Errors which occur during program execution(run-time) after successful compilation are called run-time errors. One of the most common run-time error is division by zero also known as Division error. These types of error are hard to find as the compiler doesn’t point to the line at which the error occurs.
For more understanding run the example given below.
// C program to illustrate
// run-time error
#include<stdio.h>
Void main()
{
Int n = 9, div = 0;
// wrong logic
// number is divided by 0,
// so this program abnormally terminates
Div = n/0;
Printf("resut = %d", div);
}
Error:
Warning: division by zero [-Wdiv-by-zero]
Div = n/0;
In the given example, there is Division by zero error. This is an example of run-time error i.e errors occurring while running the program.
3. Linker Errors: These error occurs when after compilation we link the different object files with main’s object using Ctrl+F9 key(RUN). These are errors generated when the executable of the program cannot be generated. This may be due to wrong function prototyping, incorrect header files. One of the most common linker error is writing Main() instead of main().
// C program to illustrate
// linker error
#include<stdio.h>
Void Main() // Here Main() should be main()
{
Int a = 10;
Printf("%d", a);
}
Error:
(.text+0x20): undefined reference to main'
4. Logical Errors: On compilation and execution of a program, desired output is not obtained when certain input values are given. These types of errors which provide incorrect output but appears to be error free are called logical errors. These are one of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect if we follow the line of execution and determine why the program takes that path of execution.
// C program to illustrate
// logical error
Int main()
{
Int i = 0;
// logical error : a semicolon after loop
For(i = 0; i < 3; i++);
{
Printf("loop ");
Continue;
}
Getchar();
Return 0;
}
No output
5. Semantic errors: This error occurs when the statements written in the program are not meaningful to the compiler.
// C program to illustrate
// semantic error
Void main()
{
Int a, b, c;
a + b = c; //semantic error
}
Error
Error: lvalue required as left operand of assignment
a + b = c; //semantic error
Q8) Write short notes on documentation?
A8) Documentation
A programme or software document is any written text, graphics, or video that describes a software or programme to its users. A user can be anyone, from a programmer to a system analyst to an end user. Multiple documents for different users may be developed at various phases of development. Software documentation is, in reality, an important part of the overall software development process.
Because multiple teams produce separate modules of the product in modular programming, documentation becomes even more critical. Good and detailed documentation will make it easier for anyone other than the development team to comprehend a module.
These are some guidelines for document creation.
● Documentation should be written from the reader's perspective.
● The document should be clear.
● There should not be any repeats.
● Industry norms must be followed.
● Always keep your documents up to date.
● Any outdated document should be phased out after it has been properly documented.
Advantages of Documentation
Providing software documentation has a number of advantages.
● Keeps track of all components of a programme or software.
● Maintenance is less difficult.
● Other than the developer, all parts of software can be understood by programmers.
● Enhances the software's overall quality.
● Assists with user education.
● If people leave the system abruptly, it ensures knowledge decentralization, reducing costs and effort.
Q9) Define ubuntu.
A9) Ubuntu
Ubuntu is an operating system based on Linux. Computers, cellphones, and network servers are all supported. Canonical Ltd, based in the United Kingdom, created the system. All of the principles utilised to create the Ubuntu software are based on Open Source software development principles.
Features of Ubuntu
The following are some of Ubuntu's most notable features.
● Ubuntu's desktop edition works with all of the standard Windows programmes, such as Firefox, Chrome, and VLC.
● It works with the LibreOffice office suite.
● Thunderbird, an email client included into Ubuntu, allows users to access email services such as Exchange, Gmail, and Hotmail.
● Users may browse and edit images using a variety of free programmes.
● There are other video management applications that allow users to exchange videos.
● With Ubuntu's clever searching feature, finding content is simple.
● The finest aspect is that it is a free operating system with a large open source community behind it.
Features
Ubuntu has a number of features:
● Ubuntu Desktop
● Ubuntu Server
● Kubuntu
● Linux Mint
● Ubuntu Desktop
Ubuntu is a desktop operating system designed for everyday use. The Ubuntu operating system includes pre-installed software that assists users with a variety of common tasks. The Ubuntu desktop operating system has a number of features, including multimedia, email, and browsing.
● Ubuntu Server
The Ubuntu server operating system is mostly used to host database and web server applications. This operating system also supports Azure and AWS, among other cloud services.
● Kubuntu
The Unity programme powers the Ubuntu operating system's user interface. The Kubuntu interface, on the other hand, is based on the KDE Plasma desktop. The KDE Plasma desktop gives Ubuntu a look and feel. The Kubuntu operating system has the same software availability and features as the Ubuntu operating system.
● Linux Mint
The Ubuntu-based Linux Mint operating system is likewise based on Ubuntu. The Linux Mint operating system comes with a number of pre-installed multimedia and photo applications. The Linux Mint operating system is based entirely on open-source software.
Advantages of the Ubuntu Operating System
The Ubuntu operating system has a number of advantages:
● Ubuntu is Free
● Ubuntu can be Easily Customized
● Virtual Desktops
● Better Option for Development
● Ubuntu is more Secure
● Free Apps
Q10) What is C programming?
A10) C is a general-purpose programming language that is extremely popular, simple and flexible. It is a machine-independent, structured programming language which is used extensively in various applications.
C was the basic language to write everything from operating systems (Windows and many others) to complex programs like the Oracle database, Git, Python interpreter and more.
It is said that 'C' is a god's programming language. One can say, C is a base for programming. If you know 'C,' you can easily grasp the knowledge of the other programming languages that uses the concept of 'C'
It is essential to have a background in computer memory mechanisms because it is an important aspect when dealing with the C programming language.
Advantages of C language
● Reliability: C language allows low level access to data and commands and maintains the syntax of a high level language. These qualities make it a useful language for both systems programming and general purpose programs.
● Flexibility: C is a powerful and flexible language which provides fast program execution.
● Modularity: C language provides features like Functions, Structures, Unions and Built-in Library functions which support code reusability.
● Efficiency and Effectiveness: The programs of C language are less complex and do not require any special programming language platform other than compiler. C language plays vital role in hardware programming
Q11) What is the history of C?
A11) History of C language
The base or father of programming languages is 'ALGOL.' It was first introduced in 1960. 'ALGOL' was used on a large basis in European countries. 'ALGOL' introduced the concept of structured programming to the developer community. In 1967, a new computer programming language was announced called as 'BCPL' which stands for Basic Combined Programming Language. BCPL was designed and developed by Martin Richards, especially for writing system software.
This was the era of programming languages. Just after three years, in 1970 a new programming language called 'B' was introduced by Ken Thompson that contained multiple features of 'BCPL.' This programming language was created using UNIX operating system at AT & T and Bell Laboratories. Both the 'BCPL' and 'B' were system programming languages.
In 1972, a great computer scientist Dennis Ritchie created a new programming language called 'C' at the Bell Laboratories. It was created from 'ALGOL', 'BCPL' and 'B' programming languages. 'C' programming language contains all the features of these languages and many more additional concepts that make it unique from other languages.
'C' is a powerful programming language which is strongly associated with the UNIX operating system. Even most of the UNIX operating system is coded in 'C'. Initially 'C' programming was limited to the UNIX operating system, but as it started spreading around the world, it became commercial, and many compilers were released for cross-platform systems. Today 'C' runs under a variety of operating systems and hardware platforms. As it started evolving many different versions of the language were released.
At times it became difficult for the developers to keep up with the latest version as the systems were running under the older versions. To assure that 'C' language will remain standard, American National Standards Institute (ANSI) defined a commercial standard for 'C' language in 1989. Later, it was approved by the International Standards Organization (ISO) in 1990. 'C' programming language is also called as 'ANSI C'.
Q12) Explain GCC?
A12) GNU Compiler Collection (GCC) is a GNU Project optimizing compiler that supports a wide range of programming languages, hardware architectures, and operating systems. GCC is distributed as free software by the Free Software Foundation (FSF) under the GNU General Public License (GNU GPL). GCC is an important part of the GNU toolchain and the standard compiler for most GNU and Linux kernel projects. GCC is one of the largest free programmes in existence, with around 15 million lines of code in 2019. It has served as both a tool and an example in the development of free software.
History of GCC
Richard Stallman, the founder of the GNU Project, is the original author of the GNU C Compiler (GCC).
The GNU Project began in 1984 with the goal of creating a free Unix-like operating system to encourage freedom and collaboration among computer users and programmers. Every Unix-like operating system requires a C compiler, and the GNU Project had to create one from scratch because there were no free compilers available at the time. Individuals and businesses contributed to the Free Software Foundation, a non-profit organization established to support the GNU Project's efforts.
GCC was released for the first time in 1987. Being the first portable ANSI C optimizing compiler released as free software, this was a notable milestone. Since then, GCC has grown into one of the most significant tools for free software development.
In 1992, the 2.0 series of the compiler was released, which included the ability to compile C++. To increase optimization and C++ support, an experimental branch of the compiler (EGCS) was built in 1997. Following this work, EGCS was accepted as the new main-line for GCC development, and these capabilities were made generally available in GCC 3.0 in 2001.
GCC has been extended to support a variety of other languages throughout time, including Fortran, ADA, Java, and Objective-C. The "GNU Compiler Collection" is now referred to by the moniker GCC. The GCC Steering Committee, which is made up of representatives from GCC user communities in industry, research, and academia, oversees its development.
Features of GCC
To begin with, GCC is a portable compiler that runs on the majority of modern systems and can provide output for a variety of CPUs. It supports microcontrollers, DSPs, and 64-bit CPUs in addition to the processors used in personal computers.
GCC isn't just a native compiler; it can also cross-compile any programme, resulting in executable files for systems other than GCC's own. This makes it possible to compile software for embedded systems that lack the ability to execute a compiler. GCC is written in C with a heavy emphasis on portability, and it can compile itself, making it simple to adapt to new systems.
For parsing different languages, GCC includes numerous language frontends. Any architecture may compile or cross-compile programmes written in each language. An ADA programme, for example, can be compiled for a microcontroller, whereas a C programme can be compiled for a supercomputer.
GCC's modular design allows for the addition of new languages and architectures. When you add a new language front-end to GCC, you can use it on any architecture as long as you have the requisite run-time facilities (such as libraries). Adding support for a new architecture does the same thing, making it available to all languages.
Last but not least, GCC is free software, distributed under the GNU General Public License (GNU GPL). As with all GNU software, you have complete freedom to use and modify GCC. You can either add support for a new type of CPU, a new language, or a new feature yourself or hire someone to do it for you. If an issue is critical to your job, you can hire someone to fix it.
You also have the option of sharing any GCC improvements you create. You can also use enhancements to GCC made by others as a result of this flexibility. GCC's numerous features demonstrate how this flexibility to collaborate benefits you and everyone else who uses GCC.
Q13) Describe the data types in C?
A13) A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
There are the following data types in C language.
Types | Data Types |
Basic Data Type | Int, char, float, double |
Derived Data Type | Array, pointer, structure, union |
Enumeration Data Type | Enum |
Void Data Type | Void |
Basic Data Types
The basic data types are integer-based and floating-point based. C language supports both signed and unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
Data Types | Memory Size | Range |
Char | 1 byte | −128 to 127 |
Signed char | 1 byte | −128 to 127 |
Unsigned char | 1 byte | 0 to 255 |
Short | 2 byte | −32,768 to 32,767 |
Signed short | 2 byte | −32,768 to 32,767 |
Unsigned short | 2 byte | 0 to 65,535 |
Int | 2 byte | −32,768 to 32,767 |
Signed int | 2 byte | −32,768 to 32,767 |
Unsigned int | 2 byte | 0 to 65,535 |
Short int | 2 byte | −32,768 to 32,767 |
Signed short int | 2 byte | −32,768 to 32,767 |
Unsigned short int | 2 byte | 0 to 65,535 |
Long int | 4 byte | -2,147,483,648 to 2,147,483,647 |
Signed long int | 4 byte | -2,147,483,648 to 2,147,483,647 |
Unsigned long int | 4 byte | 0 to 4,294,967,295 |
Float | 4 byte |
|
Double | 8 byte |
|
Long double | 10 byte |
|
Q14) How to declare a variable in C?
A14) Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.
Example
Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function −
#include <stdio.h>
// Variable declaration:
Extern int a, b;
Extern int c;
Extern float f;
Int main () {
/* variable definition: */
Int a, b;
Int c;
Float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Printf("value of c : %d \n", c);
f = 70.0/3.0;
Printf("value of f : %f \n", f);
Return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of c : 30
Value of f : 23.333334
The same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −
// function declaration
Int func();
Int main() {
// function call
Int i = func();
}
// function definition
Int func() {
Return 0;
}
Q15) Explain input/output statements?
A15)
There are some library functions which are available for transferring the information between the computer and the standard input and output devices.
These functions are related to the symbolic constants and are available in the header file.
Some of the input and output functions are as follows:
i) printf
This function is used for displaying the output on the screen i.e the data is moved from the computer memory to the output device.
Syntax:
Printf(“format string”, arg1, arg2, …..);
In the above syntax, 'format string' will contain the information that is formatted. They are the general characters which will be displayed as they are
arg1, arg2 are the output data items.
Example: Demonstrating the printf function
Printf(“Enter a value:”);
● Printf will generally examine from left to right of the string.
● The characters are displayed on the screen in the manner they are encountered until it comes across % or \.
● Once it comes across the conversion specifiers it will take the first argument and print it in the format given.
Ii) scanf
Scanf is used when we enter data by using an input device.
Syntax:
Scanf (“format string”, &arg1, &arg2, …..);
The number of items which are successful are returned.
Format string consists of the conversion specifier. Arguments can be variables or array name and represent the address of the variable. Each variable must be preceded by an ampersand (&). Array names should never begin with an ampersand.
Example: Demonstrating scanf
Int avg;
Float per;
Char grade;
Scanf(“%d %f %c”,&avg, &per, &grade):
● Scanf works totally opposite to printf. The input is read, interpret using the conversion specifier and stores it in the given variable.
● The conversion specifier for scanf is the same as printf.
● Scanf reads the characters from the input as long as the characters match or it will terminate. The order of the characters that are entered are not important.
● It requires an enter key in order to accept an input.
Iii) getch
This function is used to input a single character. The character is read instantly and it does not require an enter key to be pressed. The character type is returned but it does not echo on the screen.
Syntax:
Int getch(void);
Ch=getch();
where,
Ch - assigned the character that is returned by getch.
Iv) putch
This function is a counterpart of getch. Which means that it will display a single character on the screen. The character that is displayed is returned.
Syntax:
Int putch(int);
Putch(ch);
Where,
Ch - the character that is to be printed.
v) getche
This function is used to input a single character. The main difference between getch and getche is that getche displays the (echoes) the character that we type on the screen.
Syntax:
Int getch(void);
Ch=getche();
Vi) getchar
This function is used to input a single character. The enter key is pressed which is followed by the character that is typed. The character that is entered is echoed.
Syntax:
Ch=getchar;
Vii) putchar
This function is the other side of getchar. A single character is displayed on the screen.
Syntax:
Putchar(ch);
Viii) gets and puts
They help in transferring the strings between the computer and the standard input-output devices. Only single arguments are accepted. The arguments must be such that it represents a string. It may include white space characters. If gets is used enter key has to be pressed for ending the string. The gets and puts function are used to offer simple alternatives of scanf and printf for reading and displaying.
Example:
#include <stdio.h>
Void main()
{
Char line[30];
Gets (line);
Puts (line);
}
Q16) Define library functions?
A16) Library functions are the inbuilt functions in C that are grouped and placed at a common place called the library. Such functions are used to perform some specific operations. For example, printf is a library function used to print on the console. The library functions are created by the designers of compilers. All C standard library functions are defined inside the different header files saved with the extension .h.
We need to include these header files in our program to make use of the library functions defined in such header files. For example, To use the library functions such as printf/scanf we need to include stdio.h in our program which is a header file that contains all the library functions regarding standard input/output.
The list of mostly used header files is given in the following table.
SN | Header file | Description |
1 | Stdio.h | This is a standard input/output header file. It contains all the library functions regarding standard input/output. |
2 | Conio.h | This is a console input/output header file. |
3 | String.h | It contains all string related library functions like gets(), puts(),etc. |
4 | Stdlib.h | This header file contains all the general library functions like malloc(), calloc(), exit(), etc. |
5 | Math.h | This header file contains all the math operations related functions like sqrt(), pow(), etc. |
6 | Time.h | This header file contains all the time-related functions. |
7 | Ctype.h | This header file contains all character handling functions. |
8 | Stdarg.h | Variable argument functions are defined in this header file. |
9 | Signal.h | All the signal handling functions are defined in this header file. |
10 | Setjmp.h | This file contains all the jump functions. |
11 | Locale.h | This file contains locale functions. |
12 | Errno.h | This file contains error handling functions. |
13 | Assert.h | This file contains diagnostics functions. |
Q17) What do you mean by the nitty gritty of the program?
A17) Nitty - Gritty of program
The two main aspects of C programming are algorithm and procedure.
Algorithm
The execution flow of a programme is defined by algorithms. It is a step-by-step procedure that provides a solution to the problem. The following is a typical logical assortment:
- Sequence
- Selection
- Iteration
- Case type statement
In C, "sequence statements" are essential, while "if then else" statements and case type statements like "switch statements" are used to make decisions. "while," "do-while," and "for" statements are iteration statements.
Pseudocodes
Pseudocodes are a slang term for an informal method of writing algorithms. It employs English-like terminology to represent algorithm steps. Before any novice grammar student begins coding and algorithm development, it is always advised that he or she completes the following: Write the pseudo code first because it helps you understand how the algorithm works. The following is a simple example of pseudocode:
If patient temperature is greater than 98 degree
Print “high fever”
Else
print “no fever”
Procedure
A procedure is a collection of code statements that describe an algorithm. A procedure is made up of assertions contained by a pair of {}. Some procedures added value to the programme construct called functions.
Program
A programme is a collection of explicit instructions written in a programming language. We need to offer some input data to the programme to get output once we have a programme as a solution to the problem.
Q18) What is the structure of C program?
A18)
The components above structure are:
A header file is a file with extension .h which contains C function declarations and macro definitions to be shared between several source files.
Some of C Header files:
- Stddef.h – Defines several useful types and macros.
- Stdint.h – Defines exact width integer types.
- Stdio.h – Defines core input and output functions
- Stdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocation
- String.h – Defines string handling functions
- Math.h – Defines common mathematical functions
Main Method Declaration: The next part of a C program is to declare the main() function. The syntax to declare the main function is:
Syntax to Declare the main method:
Int main()
{}
Variable Declaration: The next part of any C program is the variable declaration. It refers to the variables that are to be used in the function. Please note that in the C program, no variable can be used without being declared. Also in a C program, the variables are to be declared before any operation in the function.
Example:
Int main()
{
Int a;
.
.
Body: The body of a function in the C program, refers to the operations that are performed in the functions. It can be anything like manipulations, searching, sorting, printing, etc.
Example:
int main()
{
Int a;
Printf("%d", a);
.
.
Return Statement: The last part of any C program is the return statement. The return statement refers to the returning of the values from a function. This return statement and return value depend upon the return type of the function.
For example, if the return type is void, then there will be no return statement. In any other case, there will be a return statement and the return value will be of the type of the specified return type.
Example:
Int main()
{
Int a;
Printf("%d", a);
Return 0;
}
Writing first program:
Following is first program in C
#include <stdio.h>
Int main(void)
Printf("GeeksQuiz");
Return 0;
}
Let us analyze the program line by line.
Line 1: [ #include <stdio.h> ] In a C program, all lines that start with # are processed by a preprocessor which is a program invoked by the compiler.
In a very basic term, the preprocessor takes a C program and produces another C program. The produced program has no lines starting with #, all such lines are processed by the preprocessor.
In the above example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called header files in C. These header files generally contain declarations of functions. We need stdio.h for the function printf() used in the program.
Line 2 [ int main(void)] There must be a starting point from where execution of compiled C program begins. In C, the execution typically begins with the first line of main(). The void written in brackets indicates that the main doesn’t take any parameter.
Main() can be written to take parameters also. The int was written before main indicates return type of main().
The value returned by main indicates the status of program termination.
Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define scope and are mainly used in functions and control statements like if, else, loops. All functions must start and end with curly brackets.
Line 4 printf() is a standard library function to print something on standard output. The semicolon at the end of printf indicates line termination. In C, a semicolon is always used to indicate end of a statement.
Line 5 [ return 0; ] The return statement returns the value from main(). The returned value may be used by an operating system to know the termination status of your program. The value 0 typically means successful termination.
How to execute the above program:
In order to execute the above program, we need to have a compiler to compile and run our programs.
Q19) Describe Vim editor?
A19) The abbreviation Vim stands for Vi IMproved. Bram Moolenaar created this free and open source text editor. It was first launched in 1991 for UNIX variations, with the primary purpose of improving the Vi editor, which was first released in 1976.
Vim is a clone of the Vi editor. It's a command-centric editor, just like Vi. One of the benefits of learning Vim is that it is portable. Vim is installed by default on any UNIX variation, including Linux, Mac, HP-UX, AIX, and many others. Vim has never had a graphical user interface, but there is now a separate installer called gVim that does.
Why Vim was Created
Vim is based on Bill Joy's original Vi editor, which he invented in 1976. Vi was falling behind in the 1990s, and there was a so-called editor war between Vi and Emacs. As a result, Bram added a slew of missing features that the Emacs community used to argue that Emacs was superior to Vi/Vim.
Features of Vim
Some of Vim's key features are discussed here.
● It has a small memory footprint.
● It's all about commands. With a few commands, you can do sophisticated text-related tasks.
● It is very configurable and stores its settings in a simple text file.
● There are numerous Vim plug-ins available. These plug-ins can greatly increase the usefulness of the system.
● Multiple windows are supported. This function allows you to split your screen into numerous windows.
● Multiple buffers are supported in the same way as multiple windows are.
● It has several tabs, allowing you to work on multiple files.
● It has recording capabilities, allowing you to record and play Vim commands repeatedly.
Vim modes
Vim has a variety of modes. This section goes over some of the key modes that will be used on a daily basis.
Command mode
This is Vim's default mode when it starts up. In this mode, we can type editor commands. In this mode, we can utilise a number of commands such as copy, paste, remove, replace, and many more.
Insert mode
This mode allows you to type or edit text. Press the I key to switch from default command to insert mode. The current mode will be displayed in the editor's bottom left corner.
Once we're in insert mode, we can type whatever we want. This is depicted in the graphic below.
To return to command mode from this mode, press the Escape key.
Command line mode
This mode is also where commands are entered. In this mode, commands begin with a colon (:). In the previous section, for example, the quit command was input in this manner. This mode can be accessed from either command or insert mode.
● Simply type colon to go from command mode to this mode.
● Press Escape and type colon to move from insert mode to this mode.
Visual mode
We may visually choose text and run commands on selected areas in this manner.
● Type v to switch from command to visual mode.
● To transition from any other mode to visual mode, press Escape to return to command mode, then type v to enter visual mode.
Visual mode is shown in the lower left corner of the image below.
Q20) Define format specifier?
A20) Format specifiers in console formatted I/O functions
Some of the most commonly used format specifiers used in console formatted input/output functions are displayed in the table below -
Format Specifiers | Description |
%hi |
|
%hu |
|
%d |
|
%u |
|
%ld |
|
%lu |
|
%c |
|
%c |
|
%f |
|
%lf |
|
%Lf |
|
%s |
|
Optional specifiers within a format specifier
We could specify two more optional specifiers within each format specifier, such as integer value and a sign.
An integer value specifies the number of columns used on the screen for printing a value i.e. width. This integer value may or may not have a minus sign before it.
● A (-)minus sign before the integer value means left justification of the value to be printed on the screen and integer value following the minus sign is the number of blanks on its right.
● No minus sign before the integer value means right justification of the value to be printed on the screen and integer value specifies the number of blanks on its left.