Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Programming in C Unit 1

The document discusses the components of a computer including the input, central processing, and output units. It describes how the CPU processes information and has three main components: the arithmetic logic unit, control unit, and memory registers. The document also defines hardware and software.

Uploaded by

Manda Vaishnavi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Programming in C Unit 1

The document discusses the components of a computer including the input, central processing, and output units. It describes how the CPU processes information and has three main components: the arithmetic logic unit, control unit, and memory registers. The document also defines hardware and software.

Uploaded by

Manda Vaishnavi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT -1 : INTRODUCTION TO COMPUTING

Components of Computer
A computer is an electronic device that accepts data, performs operations,
displays results, and stores the data or results as needed. It is a combination
of hardware and software resources that integrate together and provides
various functionalities to the user. Hardware is the physical components of a
computer like a processor, memory devices, monitor, keyboard, etc., while
software is a set of programs or instructions that are required by the
hardware resources to function properly .

There are basically three important components of a computer:


1. Input Unit
2. Central Processing Unit(CPU)
3. Output Unit

1. Input Unit:
The input unit consists of input devices that are attached to the computer. These
devices take input and convert it into binary language that the computer understands.
Some of the common input devices are keyboard, mouse, joystick, scanner etc.
2. Central Processing Unit:
Once the information is entered into the computer by the input device, the processor
processes it. The CPU is called the brain of the computer because it is the control
centre of the computer. It first fetches instructions from memory and then interprets
them so as to know what is to be done. If required, data is fetched from memory or
input device. Thereafter CPU executes or performs the required computation, and
then either stores the output or displays it on the output device. The CPU has three
main components, which are responsible for different functions: Arithmetic Logic
Unit (ALU), Control Unit (CU) and Memory registers
A. Arithmetic and Logic Unit (ALU): The ALU, as its name suggests performs
mathematical calculations and takes logical decisions. Arithmetic calculations
include addition, subtraction, multiplication and division. Logical decisions
involve the comparison of two data items to see which one is larger or smaller
or equal.
B. Control Unit: The Control unit coordinates and controls the data flow in and
out of the CPU, and also controls all the operations of ALU, memory registers
and also input/output units. It is also responsible for carrying out all the
instructions stored in the program. It decodes the fetched instruction, interprets it
and sends control signals to input/output devices until the required operation is
done properly by ALU and memory.
C. Memory Registers: A register is a temporary unit of memory in the CPU.
These are used to store the data, which is directly used by the processor.
Registers can be of different sizes(16 bit, 32 bit, 64 bit and so on) and each
register inside the CPU has a specific function, like storing data, storing an
instruction, storing address of a location in memory etc. The user registers can be
used by an assembly language programmer for storing operands, intermediate
results etc.
3. Output Unit :
The output unit consists of output devices that are attached to the computer. It
converts the binary data coming from the CPU to human understandable form. The
common output devices are monitor, printer, plotter, etc
Concept of Hardware and Software
Hardware: The term hardware refers to mechanical device that makes up computer.
Computer hardware consists of interconnected electronic devices that we can use to
control computer’s operation, input and output.
Software: A set of instructions that drives computer to do stipulated tasks is called a
program. Software instructions are programmed in a computer language, translated
into machine language, and executed by computer.
Sr.No
Software Hardware
.

It is a
collection of
programs to
bring
1 It includes physical components of computer system.
computer
hardware
system into
operation.

It includes
numbers,
alphabets,
alphanumeric It consists of electronic components like ICs, diodes,
2
symbols, registers, crystals, boards, insulators, etc.
identifiers,
keywords,
etc.

Software
products
evolve by
adding new Hardware design is based on architectural decisions to
3 features to make it work over a range of environmental conditions and
existing time.
programs to
support
hardware.

It will vary
as per
computer
and its built-
4 It is mostly constructed for all types of computer systems.
in functions
and
programming
language.

It is designed
and
developed by
The hardware can understand only low-level language or
5 experienced
machine language.
programmers
in high-level
language.

6 It is The hardware works only on binary codes 1’s and 0’s.


represented
in any high-
level
language
such as
BASIC,
COBOL, C,
C++, JAVA,
etc.

The software
is
categorized
as operating
system, The hardware consists of input devices, output devices,
7
utilities, memory, etc.
language
processor,
application
software, etc.

FLOW CHART AND ALGORITHM

The main purpose of using an algorithm is to illustrate the flow of data and problem
solution logic.
What is Algorithm?
An algorithm is a finite sequence of well-defined steps or operations for solving a
problem in asystematic manner. In another words we can say that an algorithm is a
step-by-step problem-solvingprocedure. An algorithm generally takes some input,
carries out a number of effective steps in a finite amount oftime, and produces some
output.
Rules for writing Algorithm:
1. Each instruction should be precise and unambiguous.2. Each instruction should be
executed in a finite time.3. One or more instructions should not be repeated
infinitely.4. After executing the instructions, the desired results are obtained.

Algorithm Example 1: Write an algorithm to add two nos.


Step1: start
Step2: Read a, b
Step3: sum = a + b
Step4: write sum
Step5: stop
Algorithm Example 2 Simple Calculator:
1. Start
2.Read a, b
3.Compute sum = a + b
4.Compute sub = a – b
5.Compute mul = a * b
6.Compute div = a / b
7.Compute mod = a % b
8.Write sum, sub, mul, div, mod
Write sum, sub, mul, div, mod

Algorithm Example 3 Find volume of a circle


1. Start
2. Read
3. v = 4/3*(3.14)*(r*r*r)
4. Write v
5. Stop
What is Flow chart?
It is a graphical representation of a program flow or an algorithm of a problem to be
solved by a computer. It is an aid to solve a complex problem easily and efficiently. It
shows the detailed view of a program flow.

Rules for drawing flowchart:


1.Use common statements that are easy to understand for words within flowchart
symbols.
2.Be consistent in using names and variables in the flowchart.
3.Go from left to right and top to bottom in constructing flowcharts.
4.Keep the flowchart as simple as possible.
5.If a new flow charting page is needed, break the flowchart at an input or output
point. Use properly labelled connectors to link the flowchart on different pages.

Advantages of drawing a flowchart:


1.It helps a programmer to get a good visual reference of the structure of a program.
2.It not only serves as program documentation but also helps as a means to
communicate with several programmers, as it is language independent.
3.It allows a programmer to test alternative solutions to a problem without even
coding the program. It is much easier to find and correct logic errors prior to coding.
4.It serves as a useful reference or a programming aid due to its simple and efficient
method of representing the program logic of a problem.
Rules for drawing flowchart:
1.Use common statements that are easy to understand for words within flowchart
symbols.
2.Be consistent in using names and variables in the flowchart.
3.Go from left to right and top to bottom in constructing flowcharts.
4.Keep the flowchart as simple as possible.
5.If a new flow charting page is needed, break the flowchart at an input or output
point. Use properly labelled connectors to link the flowchart on different pages.
Overview of C Language:
C is an imperative, procedural language in the ALGOL tradition. It has a static type
system. In C, all executable code is contained within subroutines (also called
"functions", though not in the sense of functional programming). Function
parameters are passed by value, although arrays are passed as pointers, i.e. the address
of the first item in the array. Pass-by-reference is simulated in C by explicitly passing
pointers to the thing being referenced.
C program source text is free-form code. Semicolons terminate statements,
while curly braces are used to group statements into blocks.
The C language also exhibits the following characteristics:

 The language has a small, fixed number of keywords, including a full set
of control flow primitives: if/else , for , do/while , while , and switch . User-
defined names are not distinguished from keywords by any kind of sigil.
 It has a large number of arithmetic, bitwise, and logic operators: + , += , +
+ , & , || , etc.
 More than one assignment may be performed in a single statement.
 Functions:
o Function return values can be ignored, when not needed.
o Function and data pointers permit ad hoc run-time polymorphism.
o Functions may not be defined within the lexical scope of other
functions.
o Variables may be defined within a function, with scope.
o A function may call itself, so recursion is supported.
 Data typing is static, but weakly enforced; all data has a type, but implicit
conversions are possible.
 User-defined (typedef) and compound types are possible.
o Heterogeneous aggregate data types ( struct ) allow related data
elements to be accessed and assigned as a unit. The contents of
whole structs cannot be compared using a single built-in operator
(the elements must be compared individually).
o Union is a structure with overlapping members; it allows multiple
data types to share the same memory location.
o Array indexing is a secondary notation, defined in terms of
pointer arithmetic. Whole arrays cannot be assigned or compared
using a single built-in operator. There is no "array" keyword in
use or definition; instead, square brackets indicate arrays
syntactically, for example month[11] .
o Enumerated types are possible with the enum keyword. They are
freely interconvertible with integers.
o Strings are not a distinct data type, but are
conventionally implemented as null-terminated character arrays.
 Low-level access to computer memory is possible by converting machine
addresses to pointers.
 Procedures (subroutines not returning values) are a special case of function,
with an empty return type void .
 Memory can be allocated to a program with calls to library routines.
 A preprocessor performs macro definition, source code file inclusion,
and conditional compilation.
 There is a basic form of modularity: files can be compiled separately
and linked together, with control over which functions and data objects are
visible to other files via static and extern attributes.
 Complex functionality such as I/O, string manipulation, and mathematical
functions are consistently delegated to library routines.
 The generated code after compilation has relatively straightforward needs
on the underlying platform, which makes it suitable for creating operating
systems and for use in embedded systems.
While C does not include certain features found in other languages (such as object
orientation and garbage collection), these can be implemented or emulated, often
through the use of external libraries

Here is a simple Hello World program in C programming:

#include <stdio.h>
int main() {

printf("Hello, World!");

return 0;

Output:
Hello, World!

History of C Language

To learn about the history of C language, let's first start with its root and early
developments. The root of all modern languages is ALGOL (Algorithmic Language).
ALGOL was the first computer programming language to use a block structure, and it
was introduced in 1960. In 1967, Martin Richards developed a language called BCPL
(Basic Combined Programming Language). BCPL was derived from ALGOL.
In 1970, Ken Thompson created a language using BCPL called B. Both BCPL and B
programming languages were typeless. After that, C was developed using BCPL and
B by Dennis Ritchie at the Bell lab in 1972. So, in terms of history of C language, it
was used in mainly academic environments, but at long last with the release of many
C compilers for commercial use and the increasing popularity of UNIX, it began to
gain extensive support among professionals
History of C Language

C is a procedural language that supports structured programming; it has a static


system and a compiler written in C itself. Since its release, C has become a milestone
in computing history and has become the most critical component throughout the
computer industry.

Dennis Ritchie wrote an article explaining the reason for C's success which are
enumerated as follows:

 The success of Unix was the most important factor as Unix used C for building
its utilities, and its success had carried C.

 C remained a simple and small language meant for building system


components. C was held to be sufficiently abstract that humans can read –
which is why C is considered a middle-level language.

 C was not designed in isolation but to write useful tools that interact with large
systems. C is regarded as a tool for building larger tools. Moreover, C's core
library covers the essential needs of most programmers but does not supply too
much of it.
Because C works very closely with the processor, performance-critical applications
are mostly written in C, and because of its unmatched popularity programming
languages derived a familiar C-style syntax along with the set of constructs that came
with C (e.g., pointers, macros, etc.). C has become the backbone of modern computing
systems – operating systems, compilers, interpreters, third-party libraries, and
databases. In addition, C is a small language that is designed to cost minimal
performance overhead which makes it ideal for embedded systems.

Structure of C Program
The basic structure of a C program is divided into 6 parts which makes it easy to
read, modify, document, and understand in a particular format. C program must
follow the below-mentioned outline in order to successfully compile and execute.
Debugging is easier in a well-structured C program

Sections of C Program

There are 6 basic sections responsible for the proper execution of a program.
Sections are mentioned below:
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs

1. Documentation

This section consists of the description of the program, the name of the program, and
the creation date and time of the program. It is specified at the start of the program
in the form of comments. Documentation can be represented as:

// description, name of the program, programmer name, date, time etc.


or Anything written as comments will be treated as documentation of
the program and this will not interfere with the given code. Basically, it gives an
overview to the reader of the program.
2. Preprocessor Section

All the header files of the program will be declared in the preprocessor section of the
program. Header files help us to access other’s improved code into our code. A copy
of these multiple files is inserted into our program before the process of
compilation.

Example:

#include<stdio.h>
#include<math.h>

3. Definition

Preprocessors are the programs that process our source code before the process of
compilation. There are multiple steps which are involved in the writing and
execution of the program. Preprocessor directives start with the ‘#’ symbol. The
#define preprocessor is used to create a constant throughout the program. Whenever
this name is encountered by the compiler, it is replaced by the actual piece of
defined code.
Example:
#define long long ll

4. Global Declaration

The global declaration section contains global variables, function declaration, and
static variables. Variables and functions which are declared in this scope can be used
anywhere in the program.
Example:
int num = 18;

5. Main() Function

Every C program must have a main function. The main() function of the program is
written in this section. Operations like declaration and execution are performed
inside the curly braces of the main program. The return type of the main() function
can be int as well as void too. void() main tells the compiler that the program will
not return any value. The int main() tells the compiler that the program will return an
integer value.
Example:
void main()
or
int main()

6. Sub Programs

User-defined functions are called in this section of the program. The control of the
program is shifted to the called function whenever they are called from the main or
outside the main() function. These are specified as per the requirements of the
programmer.
Example:
int sum(int x, int y)
{
return x+y;

Example: Below C program to find the sum of 2 numbers:

// Documentation
/**
* file: sum.c
* author: you
* description: program to find sum.
*/

// Link
#include <stdio.h>

// Definition
#define X 20

// Global Declaration
int sum(int y);

// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}

// Subprogram
int sum(int y)
{
return y + X;
}

Output

Sum: 75

Getting the computer to understand your program is no guarantee that people will be
able to follow it. Just as you would edit an English composition, you should spend
time revising a computer program to make it elegant and readable. The following
guidelines will help you write programs that are easy to read and modify. The grader
may expect your assignments to conform to these style and documentation
conventions.

 Include a header comment at the top of the file. This header should contain:
1. Your name (and the names of any people you work with)
2. The course number (e.g., CPSC 211) and your section number (e.g., 201-
203)
3. The name of the programming assignment (e.g., Program 1)
4. The date of last modification to the file.
5. Under the heading "PURPOSE", describe the purpose of the code in that
file. Be brief and informative. Communicate your approach to solving
the problem.
6. Under the heading "ASSUMPTIONS", state assumptions you make
regarding the problem to be solved, the kinds of inputs your program
will accept, and deviations from the assignment requirements (note that
any significant deviations should be cleared with the instructor in
advance.) This header must include:
 any assumptions made about the input
 limitations of the program with regard to the requirements
 known bugs

Specific assumptions regarding particular functions may be expressed in


header blocks above the relevant functions.

 Include a brief header block comment at the top of each function and
typedef. The format is shown below:

 Use inline comments sparingly but whenever necessary. Use inline


comments whenever the meaning of the code is not immediately obvious from
the text. For example, inline comments can be useful to summarize cases in a
conditional expression as follows:

 Write self-documenting code.


1. Choose meaningful names for all variables, parameters, and functions.
Use complete words instead of abbreviations where practical.
2. Use named constants instead of sprinkling numbers throughout your
code. Rule of thumb: if a constant is used more than once, give it a
name.
3. Avoid repetitious code by writing an appropriately named function and
calling it multiple times.
 Follow standard formatting conventions.

o Capitalization:

variables and function names


the first letter is lower case, with the first letter of each subsequent word
capitalized
for example, int caloriesFromFat = 18;
constants
the entire word is capitalized
for example, const PI = 3.14159;

o Indentation:

braces
the open brace ({) goes at the end of the line before the start of the code block.
the close brace (}) goes on its own line, indented to match the beginning of the
line containing the corresponding open brace, and include a descriptor on the
closing brace line that indicates which opening brace it matches
code inside braces
indent one level (about 3 spaces) for each level of curly braces ({})
code inside conditional statements and loops
indent one level for lines of code in conditional statements and loops
continued lines
when a statement continues across two or more lines, indent the second and
remaining lines an equal amount past the start of the first line of the statement.

Example of proper indentation technique:


 Use common sense. Remember that this style guide is only a guide. Your
primary concern should be making sure that others can read and understand the
text of your program. If you think an additional comment or particular
organization will get your ideas across more effectively, do it. However, if you
are considering deviating significantly from the guidelines or if you are in
doubt about something, please discuss it with us first

Execution of C Program

Below given the image of the steps of execution of the C program into the C compiler.
Now let us discuss the steps of execution of the C program in detail :

C code: When you first write the code in the C language, that source code is sent to
the Preprocessing section.

Preprocessing: In this section our source code is attached to the preprocessor file.
Different types of header files are used like the studio.h, math.h, etc. Our C source
code is attached to these types of files and the final C Source generates. (some of the
preprocessor directives are #include,#define). After generating the preprocessed C
source code, the C source code is sent to the compiler section.
Compiler: The preprocessed source code moves to the compiler, and an assembly-
level code is generated by the compiler after the compilation of the whole C source
code program. All the different files which have the C program must be saved with
the .c extension. For the compiler to understand whether the program file is a C
program file or not, it is necessary to have the '.c' extension. Suppose there is a
program file named as first.c, The file first.c will be the source file which will consist
of the C source code of the program. Now, when the file is compiled, the first thing
the C compiler does is to search for any error. If there is no error, the C compiler will
report for no error, after that the compiler will store the file as a .obj file of the same
name, which is termed as the object file. So by this process, the compiler will create
the first.obj. Although this .obj file will not be executable. After the compilation, the
process is continued by the assembler section.

Assembler: This part usually generates the Object code, after taking the assembly-
level code from the compiler. This object code is quite similar to the machine code or
the set of binary digits. After this assembler part, The Linker continues the process,
producing an executable.exe file at the end.

Linker: Before getting started with this, we should know that the library functions are
a part of the C software but not of any C program. Hence, the compiler has no idea
about the working of the function, whether it is a printf function or scanf function.
The information for each of these functions is kept in the corresponding library, which
the compiler ought to be able to connect. The linker does this task. So, when
the #include is written, it includes the studio.h library, which is basically used for
giving access to the Standard Output and Input. The basic goal of the linker is to link
the object file to the library functions so that the programme may be run as an
executable file (.exe). In this Linker process, the first.exe file will be created and this
file is in an executable format. After this process, the next step is the loader process.

Loader: Whenever the command is given for the execution of a particular program,
The loader plays an important role. With the help of the loader, the .exe file is loaded
in the RAM and the CPU is informed of the starting point of the address of the
program where it is loaded
Let us understand the above diagram in detail:

Instruction Register: The current instructions which are executed by the CPU, is
held by this.

Program Counter: The address of the next instructions which is to be executed by


the CPU, is held by this.

Accumulator: The accumulators usually store all the information which are related to
the calculations.

The first instruction is informed by the loader to the Program Counter, and after that,
the execution is initiated, and the Program Counter handles the task.

Syntax:

Let us look at the image syntax of the steps of execution of C program.


Example:

Now let us look at the example of the execution of the C programming language.

Abstract:

In this code example, we will see the execution of any C program code step by step.

Code:

#include <stdio.h>

int main()
{
char strMsg[] = "Hello, World!";
printf("%s\n", strMsg);
return 0;
}

Output:

Hello, World!

Explanation:

Let us now understand how we can execute this C program step by step :
 Step 1: At first we will save this code as helloworld.c (make sure to add the c
extension).
 Step 2: Then we will open the command prompt or terminal.
 Step 3: Then we will go to the current directory where the code is saved. We
can change the directory with the cd command.
 Step 4: After that we will compile the C code with the help of this command:

gcc helloWorld.c

The above command will compile the C code file, and create an executable file. In the
case of the windows system, it will create an a.exe file, and in the case of the Linux
system, it will create an /a.out file.

 Step 5 : Finally the C program file is executed.

You might also like