CSET 06101 - Basic Computer Programing
CSET 06101 - Basic Computer Programing
Introduction
‗C‘ is the most widely used computer language, which is being taught as a core
subject. C is general-purpose structural language that is powerful, efficient and
compact, which combines features of high-level language and low-level
language. It is closer to Man and Machine both. Due to this inherent flexibility
and tolerance it is suitable for different development environments .Due to these
powerful features C has not lost its importance and popularity in recently
developed and advanced software industry C can also be used for system level
programming, C is still considered as first priority programming language.
Even though people says that ―C‖ has been already superseded by languages
like C++, C# and Java but C is still important. According to Yashavant P.
Kanetkar the author of Let Us C disagree this opinion with the following reasons:-
a) C++, C# or Java make use of a principle called Object Oriented
Programming (OOP) to organize the program. This organizing principle
has lots of advantages to offer. But even while using this organizing
principle you would still need a good hold over the language elements of
C and the basic programming skills.
b) Though many C++ and Java based programming tools and frameworks
have evolved over the years the importance of C is still unchallenged
because knowingly or unknowingly while using these frameworks and
It is hoped that newcomers will find C a useful and friendly language. Care must
be taken in using C. Many of the extra facilities which it offers can lead to extra
types of programming error. You will have to learn to deal with these to
successfully make the transition to being a C programmer.
Editors
First of all we need a tool for writing the code of a program. For this purpose we
used Editors in which we write our code. We can use word processor too for this,
but word processors have many other features like bold the text, italic, coloring
the text etc, so when we save a file written in a word processor, lot of other
information including the text is saved on the disk. For programming purposes
we don‘t need these things we only need simple text. Text editors are such
editors which save only the text which we type. So for programming we will be
using a text editor
Compilers also translate the English like language (Code written in C) into a
language (Machine language) which computers can understand. The Compiler
read the whole program and translates it into machine language completely. The
difference between interpreter and compiler is that compiler will stop translating
if it finds an error and there will be no executable code generated whereas
Interpreter will execute all the lines before error and will stop at the line which
contains the error. So Compiler needs syntactically correct program to produce
an executable code. We will be using compiler in our course
Debugger
Another important tool is Debugger. Every programmer should be familiar with
it. Debugger is used to debug the program i.e. to correct the logical errors. Using
debugger we can control our program while it is running. We can stop the
execution of our program at some point and can check the values in different
variables, can change these values etc. In this way we can trace the logical errors
in our program and can see whether our program is producing the correct
results. This tool is very powerful, so it is complex too
Linker
Most of the time our program is using different routines and functions that are
located in different files, hence it needs the executable code of those
routines/functions. Linker is a tool which performs this job, it checks our
program and includes all those routines or functions which we are using in our
program to make a standalone executable code and this process is called Linking
Linker and loaders are the part of development environment. These are part of
system software. The following figure represents a graphical explanation of all
the steps involved in writing and executing a program.
L oader
Loader puts program
in memory.
Disk ..
..
..
WHAT IS LANGUAGE?
You are aware with the term language. It is a system of communication between
you and me. Some of the basic natural languages that we are familiar with are
English, Swahili, French etc. These are the languages used to communicate
among various categories of persons. But how you will communicate with your
computer. Your computer will not understand any of these natural languages for
transfer of data and instruction. So there are programming languages specially
developed so that you could pass your data and instructions to the computer to
do specific job. You must have heard names like FORTRAN, BASIC, COBOL etc.
These are programming languages. So instructions or programs are written in a
particular language based on the type of job. As an example, for scientific
application FORTRAN and C languages are used. On the other hand COBOL is
used for business applications.
Programming Languages
There are two major types of programming languages. These are Low Level
Languages and High Level Languages. Low Level languages are further divided
in to Machine language and Assembly language.
1011000111101
It is not an easy language for you to learn because of its difficult to understand. It
is efficient for the computer but very inefficient for programmers. It is considered
to the first generation language. It is also difficult to debug the program written
in this language.
Advantage
The only advantage is that program of machine language run very fast because
no translation program is required for the CPU.
Disadvantages
1. It is very difficult to program in machine language. The programmer has
to know details of hardware to write program.
2. The programmer has to remember a lot of codes to write a program which
results in program errors.
3. It is difficult to debug the program.
Advantages:
1. The symbolic programming of Assembly Language is easier to understand
and saves a lot of time and effort of the programmer.
2. It is easier to correct errors and modify program instructions.
3. Assembly Language has the same efficiency of execution as the machine level
language. Because this is one-to-one translator between assembly language
program and its corresponding machine language program.
Disadvantages:
One of the major disadvantages is that assembly language is machine dependent.
A program written for one computer might not run in other computers with
different hardware configuration.
Higher level languages are simple languages that use English and mathematical
symbols like +, -, %, / etc. for its program construction.
You should know that any higher level language has to be converted to machine
language for the computer to understand.
Thus a problem oriented language designed in such a way that its instruction
may be written more like the language of the problem. For example,
businessmen use business term and scientists use scientific terms in their
respective languages.
Compiler
It is a program translator that translates the instruction of a higher level language
to machine language. It is called compiler because it compiles machine language
instructions for every program instructions of higher level language. Thus
compiler is a program translator like assembler but more sophisticated. It scans
the entire program first and then translates it into machine code.
A compiler can translate only those source programs, which have been written,
in that language for which the compiler is meant for. For example FORTRAN
compiler will not compile source code written in COBOL language.
Interpreter
An interpreter is another type of program translator used for translating higher
level language into machine language. It takes one statement of higher level
languages, translate it into machine language and immediately execute it.
Translation and execution are carried out for each statement. It differs from
compiler, which translate the entire source program into machine code and does
involve in its execution.
.
The advantage of interpreter compared to compiler is its fast response to changes
in source program. It eliminates the need for a separate compilation after
changes to each program. Interpreters are easy to write and do not require large
memory in computer. The disadvantage of interpreter is that it is time
Programming Language
a standardized communication technique for expressing instructions to a
computer
Like human languages, each language has its own syntax and grammar
There are different types of programming languages that can be used to
create programs, but regardless of what language you use, these
instructions are translated into machine language that can be understood
by computers.
1-3: Algorithms: 8
The art of taking a problem and breaking it down into a set of instructions
you can give a computer is the interesting part of programming.
Unfortunately it is also the most difficult part of programming as well. If
you think that learning to program is simply a matter of learning a
programming language you are very wrong. In fact if you think that
programming is simply a matter of coming up with a program which
solves a problem you are equally wrong!
There are many things you must consider when writing a program; not all
of them are directly related to the problem in hand. I am going to start on
the basis that you are writing your programs for a customer. He or she has
problem and would like you to write a program to solve it. We shall
assume that the customer knows even less about computers than we do!
Initially we are not even going to talk about the programming language,
type of computer or anything like that, we are simply going to make sure
that we know what the customer wants. Coming up with a perfect
solution to a problem the customer has not got is something which
happens surprisingly often in the real world.
Further, such an analysis will also help you remember what you have
done and modify, if necessary, at a much later date. Also, if some other
person wants to know your sequence of reasoning, obviously it should be
possible for you to describe your logic in simple, unambiguous steps.
Because of all these reasons, it is highly essential to develop some form of
intermediary mechanism to describe the problem on hand as a sequence
of steps, which can be later converted to a program. There are two such
commonly used and universally accepted methods of describing the
solution process.-
a) The Flow Charts, and
b) The Algorithms
1-3: Algorithms:
The other concept is the algorithm. It is a step by step description of the
problem in a language similar to English, but not in full sentences, but as a
set of commands. Some of the examples below will classify the concepts.
Examples 1-1:
Simple interest is calculated using the formula SI=(P * T * R)/100
Flowchart Algorithm
Step 1: START
Step 4 : Write 1
Step 5 : End
Flowchart Algorithm
Step 1 : START
Step 7 : End
Example 1-3
The flowchart and algorithm for adding the integers from 1 to 10.
Algorithm
Flowchart
Step 6 : Calculate
SUM=SUM+N
N=N+1 End if
Step 7 : Go to Step 3
Example 1-4
A Flowchart to calculate the largest and the smallest numbers in a list of
input values is as shown in figure. The last input value is 99999.
Algorithm:
Read marks
If marks >= 90
Declare Grade = A
Else If marks >=80 declare grade = B
Else if marks >=65 declare Grade = C
Else declare Grade = D
Write Grade
End
Algorithm
Read the parameters of A,B,C
Evaluate D = b2 – 4 * a * c
If D>0,
Evaluate the first root as –b + sqrt (D) / (2 * a)
Second Root as –b – sqrt (D) / (2 * a)
Else
If D = 0
Evaluate First root as –b / 2 * a
Basic Programming – NTA 6 Page 12
Else
If D<0, Simply write complex roots.
End
Unit 2
Debugging and Program
Testing
2-1: Debugging and Program Testing 1
2-2: Types of Errors 1
2-3: Formal Program Testing: 2
2-1
printf ("Enter the distance traveled in miles > ");
b. Runtime Errors
Your program compiles, but when it runs, in certain cases it
terminates abruptly. An example of this would be a program that
attempted to divide by zero while running. Compilers aren't
perfect and so can't catch all errors at compile time. This is
especially true for logic errors such as infinite loops. This type of
error is called runtime error.
Example:
If the user enters a value of 0 for the miles_per_gallon, the
resulting calculation
c. Semantic/Logical Error:
Your program compiles and executes without abnormal
termination, but does not always produce the desired results.
The following code fragment is NOT semantically correct, the
formula for calculating kilometers is wrong. Why?
2-2
patches must be designed and ship out. Besides the customer are not very
happy. Software companies generally have a special team for code test,
besides allocating time for program testing. Beta releases are distributed
for evaluation by the end user.
Validation or appropriate:
Verification or correctness
Testing:
You can do component testing in your programs. There are basically two
types of testing technique black box and white box.
Black box testing implies that you will test for all possible input
types. To test for all possible data inputs would take too long so
2-3
we identify input types, this process is called partitioning the
inputs.
White box testing implies we have access to code and test all
possible paths that a program may take. Therefore we must
analyze the program, this is a good time to double check
conditionals.
Paths are the different routes the computer can take through the
program.
If example:
if (w >x){
a = a + 1;
}
else {
a = a + 3;
}
if ( y < z) {
a = a + 3;
}
else{
a = a + 4;
}
How many paths are there in this example? What are they?
2-4
Unit 3
C-FUNDAMENTALS
3-1: C-FUNDAMENTALS 2
3-2 Character of C 2
3-3: Types of C Constants 2
3-4: Rules for Constructing Integer Constants 3
3-5: Rules for Constructing Real Constants 3
3-6: Rules for Constructing Character Constants 4
3-7: Types of C Variables 4
3-8: Rules for Constructing Variable Names 5
3-9: C Keywords 5
3-10: C Instructions 6
3-11: Type Declaration Instruction 6
3-12: Arithmetic Instruction 7
3-13: Integer and Float Conversions 10
3-14 Type Conversion in Assignments 10
3-14: Associativity of Operators 13
3-15 Control Instructions in C 16
3-2 Character of C
C makes use of the normal characters of English – a to z, 0 – 9 and several
special characters like + - * / , . % # $ & ― = ; ( ) { } \ and so on. Most of the
compilers are also case sensitive. i.e. they do differentiate between capital
and small letters so you should not go about mixing them. It is a good
practice and also pleasing to type all program with small letters.
Alphabets A, B, ….., Y, Z
a, b, ……, y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols ~‗!@#%^&*()_-+
=|\{}
[]:;"'<>,.?/
a) Primary Constants
b) Secondary Constants
A declaration begins with the type, followed by the name of one or more
variables. For example,
int high, low, results[20];
b) Arithmetic Instruction
c) Control Instruction
This instruction is used to declare the type of variables being used in the
program. Any variable used in the program must be declared before using it
in any statement. The type declaration statement is written at the beginning
of main( ) function
Example:
int bas ;
float rs, grosssal ;
char name, code ;
is not. This is because here we are trying to use a even before defining
it.
Once again we are trying to use b (to assign to a) before defining it.
Ex.: int ad ;
float kot, deta, alpha, beta, gamma ;
ad = 3200 ;
kot = 0.0056 ;
deta = alpha * beta / gamma + 3.2 * 2 / 5 ;
Here,
*, /, -, + are the arithmetic operators.
= is the assignment operator.
2, 5 and 3200 are integer constants.
Basic Programming – NTA 6 Page 7
3.2 and 0.0056 are real constants.
ad is an integer variable.
kot, deta, alpha, beta, gamma are real variables.
The variables and constants together are called ‘operands’ that are operated
upon by the ‘arithmetic operators’ and the result is assigned, using the
assignment operator, to the variable on left-hand side.
Though Arithmetic instructions look simple to use one often commits mistakes in
writing them. Let us take a closer look at these statements. Note the following
points carefully.
Here in the first assignment statement though the expression‘s value is a float
(3.5) it cannot be stored in i since it is an int. In such a case the float is
demoted to an int and then its value is stored. Hence what gets stored in i is
3. Exactly opposite happens in the next statement. Here, 30 is promoted to
30.000000 and then stored in b, since b being a float variable cannot hold
anything except a float value.
In the first statement, since both 2 and 9 are integers, the result is an
integer, i.e. 0. This 0 is then assigned to k. In the second statement 9 is
promoted to 9.0 and then the division is performed. Division yields
0.222222. However, this cannot be stored in k, k being an int. Hence it gets
demoted to 0 and then stored in k.
Hierarchy of Operations
Operators are the special symbol use to perform special operation (for
example, arithmetic & logical) on operands. Operands are the variables,
constants or expressions on which operators perform operation.
2 * b * y / ( d + 1 ) – x /3 * (
z+y)
Here both assignment operators have the same priority and same
associativity (Right to Left)
Here * and / enjoys same priority and same associativity (Left to Right)
Here since left operands for both operators are unambiguous Compiler is free
to perform * or / operation as per its convenience since no matter which is
performed earlier the result would be same.
Precedence Table
C has several assignment operators. The most basic one, of course, is =, which
simply assigns the value of the expression at its right to the variable at its left.
The other assignment operators update variables. Each is used with a variable
name to its left and an expression to its right. The variable is assigned a new
value equal to its old value adjusted by the value of the expression at the right.
The exact adjustment depends on the operator. For example,
The preceding list uses simple numbers on the right, but these operators also
work with more elaborate expressions, such as the following:
The assignment operators we've just discussed have the same low priority that =
does—that is, less than that of + or *. This low priority is reflected in the last
example in which 12 is added to 3 * y before the result is multiplied by x.
You are not required to use these forms. They are, however, more compact, and
they may produce more efficient machine code than the longer form. The
combination assignment operators are particularly useful when you are trying to
squeeze something complex into a for loop specification.
The Sequence control instruction ensures that the instructions are executed in
the same order in which they appear in the program. Decision and Case control
instructions allow the computer to take a decision as to which instruction is to
be executed next. The Loop control instruction helps computer to execute a
group of statements repeatedly.
Some Terminology
a) As long as you are learning the names of things, the proper term for
what we have called an "item" (as in "the item to the left of the =") is
operand. Operands are what operators operate on.
b) The addition operator causes the two values on either side of it to be
added together
c) The subtraction operator causes the number after the – sign to be
subtracted from the number before the sign.
When the minus sign is used in this way, it is called a unary operator,
meaning that it takes just one operand
e) C uses the / symbol to represent division. The value to the left of the /
is divided by the value to the right.
f) The modulus operator is used in integer arithmetic. It gives the
remainder that results when the integer to its left is divided by the
integer to its right.
Before we begin with our first C program do remember the following rules that are
applicable to all C programs:
a) Comments
In the above program the first line in the program starts with /* and ends
with */. Any thing written between /* and */ is called a comment. In the C
Language comments are an aid to the programmer to read and understand a
program. It is not a statement of the language. The compiler ignores
Comment about the program should be enclosed within /* */. For example,
the first two statements in our program are comments.
Any number of comments can be written at any place in the program. For
example, a comment can be written before the statement, after the statement
or within the statement as shown below:
/* formula */ si = p * n * r / 100 ;
si = p * n * r / 100 ; /* formula */
si = p * n * r / /* formula */ 100 ;
The normal language rules do not apply to text written within /* .. */. Thus we
can type this text in small case, capital or a combination. This is because the
comments are solely given for the understanding of the programmer or the
fellow programmers and are completely ignored by the compiler
b) PREPROCESSOR DIRECTIVE
Now let us observe the line
# include <stdio.h>
All preprocessor directives begin with pound sign # which must be entered
in the first column. The # include line must not end with a semicolon. Only
one preprocessor directive can appear in one line.
Here is a very simple example which illustrates the purpose of include files.
Assume that we were to write programs which depend on predefined
physical constants, such as h, c, G, k etc. Instead of looking the values up and
entering them directly into each of our programs, we could write a short text
(i.e. ASCII) file using the QuickC editor. Something like this:
/* SI Constants */
/* File Name:
*/
myconst.h
/* this statement defines the
#define c 3.0e8 */
constant 'c'
/* see section I. c) for more information on
'define' statements. */
#define G 6.67e- /* this defines the constant 'G' */
Next, we save this file in the include subdirectory as "myconst.h" (Note, the
extension ".h" is used to distinguish include files from C programs which
have extension .c). If we enter in any of our future programs:
#include <myconst.h>
then all the above defined constants can be used directly in such a program
and they do not have to be declared or entered again. In other words, when
your program compiles, the entire content of 'myconst.h' is directly pasted or
'included' in the program. The most commonly used include files contain
function declarations for predefined C functions. Each C function must be
declared somewhere, i.e. the function's name, its type and the arguments
must be declared before it can be used. In our programs, we will be using
numerous predefined C functions such as sin(), printf(), scanf() etc. Since
these functions must be declared we should type their often lengthy and
cumbersome declarations in our programs. Lucky for us, someone has
already entered all predefined function declarations in various include files.
Hence, using an include statement in our program which refers to a particular
include file is identical to typing all the statements in the include file directly
into our program.
The declarations from related functions are usually grouped together. For
example, the declarations for all predefined math functions, such as sin(),
exp(), rand(), log() etc., are stored in the file 'math.h'. To find out which
include file is needed for a particular function, read the summary help screen
(i.e. move the cursor to the function statement in your program and press f1).
Note, if you forget to enter the corresponding include file for a function, the
program may still compile without error messages but it may not work;
hence, always check that each predefined C function has its corresponding
include file declared!
c) Main( ) Function
The next line is main( ). It defines what is known as a function in C. A C
program is made up of many functions. The function main( ) is required in all
C programs. It indicates the start of a C program. We will use main( ) at the
beginning of all programs. Observe that main( ) is not followed by a comma
or semicolon.
d) Braces {And}
Braces {and} enclose the computations carried out by main ( ). Each line in the
program is a statement. Every statement is terminated by a semicolon; The
statement itself can be written anywhere in a line. More than one statement
can be on a line as a semicolon separates them.
However it is a good practice to write one statement per line.
e) Declaration
f) Assignment Statements
The statement p=4; is an assignment statement. It commands that the integer
4 be stored in the memory box named p. when the statement is executed the
integer 4 will be stored in the memory box named p
g) Arithmetic Statement
The statement area=p*q; is an arithmetic statement. It commands that the
numbers stored in memory boxes p and q should be copied in to the CPU.
The original contents of p and q remain in their respective boxes. These
numbers are multiplied by the CPU and product is stored in box named area.
After executing this statement the box named area will contain 24 as shown
below:-
h) printf
This formatted output function statement defined in stdio.h file used to print
the string or the values of variables on the output screen.
Syntax:
printf(“<format string>”, <variables-list>);
Here, the format string will contain the string and the format specifiers or
format codes to display the values of variables in the sequence of format
specifiers.
Here the %d is called as integer format specifier and used to print the integer
value of variable on the screen. Such 16 different format specifiers / format
codes are used in printf as well as scanf. These are listed below:
The format string is % d\n The symbol % d says interpret the variable area
occurring after the comma in the printf statement as an integer and display
its value‖. The symbol \n causes the display to advance to the next line. Thus
when this statement is carried out we will see on the screen
In addition to format specifiers like %f, %d and %c the format string may also
contain any other characters. These characters are printed as they are when the
printf( ) is executed.
Following are some examples of usage of printf( ) function:
printf ( "%f", si ) ;
printf ( "%d %d %f %f", p, n, r, si ) ;
printf ( "Simple interest = Tshs. %f", si ) ;
printf ( "Prin = %d \nRate = %f", p, r ) ;
What is ‗\n‘ doing in this statement? It is called newline and it takes the cursor
to the next line. Therefore, you get the output split over two lines. ‗\n‘ is one of
the several Escape Sequences available in C.
Character Meaning
\n New line
\t Tab
\b Backspace
\v Vertical tab
\a Audible Alert (Bell)
i) Scanf
This formatted input function statement defined in stdio.h file and used
to accept the values of variables from the keyboard.
Syntax:
scanf(“<format string>”, <variables-list>);
For example:
int var1;
float var2;
scanf(“%d%f”, &var1, &var2);
Here, the format string will contain the format specifiers or format codes
to accept the values of variables in the sequence of format specifiers.
Note that the ampersand (&) before the variables in the scanf( ) function is a
must. & is an ‗Address of‘ operator. It gives the location number used by the
variable in memory. When we say &a, we are telling scanf( ) at which
memory location should it store the value supplied by the user from the
keyboard.
j) Define Statements
Define statements declare constants. Constants are 'variables' that will not
change during the program execution. Define statements can be stored in a
separate include file which is useful if there is a large number of them. You
don't need to use capital letters for the constant names, but it is a good (and
very common) practice and helps to distinguish them from variables.
Three very common mistakes with define statements are:
1) to include an equal sign between the name and its declaration,
2) to use a semicolon at the end of the statement,
3) to use type definitions, such as short, float etc. with define
statements.
#define PI = 3.1416 /* W R O N G ! ! ! */
#define PI 3.1416; /* W R O N G
! ! ! */
#define PI 3.1416 /* R I G H T
Example 4-1
Write a program to convert a temperature given in Celsius to Fahrenheit -
The formula for conversion is f = 1.8C + 32
# include <stdio.h>
main ( )
{
float fahrenheit, celsius;
scanf(“%f”, & celsius);
fahrenhit = 1.8*celsius + 32.0;
printf (“fahrenheit = % f\n”, fahrenheit);
} /* End of main */
Example 4-2
Write a program to multiply two number..
Output:
300.000000 times 0.600000 is 180.000000
Example 4-3
Write a program to compute average of three numbers
Output:
The average of 8,10,4 is is 7.000000 and 1/3
Example 4-4
Write a program to find the area and perimeter of a circle given its radius.
Algorithm :
1. Start
2. Assign Pi ← 3.1415
3. Input radium
4. Calcualte area ← 2*pi*r
peri ← 2*pi*r
5. Output Area, Perimeter
6. Stop
Example 4-5
Write a program to find the area and perimeter of a rectangle having
length, l and breadth b.
Algorithm:
1. Start
2. Input length & breadth
3. Calculate area←length * breadth
peri←* (length + breadth)
4. Output area,peri
5. Stop.
Example 4-5
Algorithm :
1. Start
2. Input temperature in Fahrenheit(F)
3. Calculate Celsius <-5.0/9.0*(F-32.0)
4. Output temperature in Celsius(C)
5. Input temperature in Celsius(C)
6. Calculate Fahrenheit <- (C*9.0/5.0) +32.0
7. Output temperature in Fahrenheit
8. Stop
Example 4-6
#include<stdio.h>
void main( )
{
float Basic, DA, HRA, GS;
printf(“Enter the basic salary”);
scanf(“%f”, &basic);
DA = (40/100) * basic;
HRA = (20/100)* basic;
GS = DA + HRA + Basic;
printf (“Gross salary = %f ”,GS);
}
Example 4-7
#include <stdio.h>
void main()
{
int n1,n2,add,sub,prod,quot,remain;
printf("\nENTER NUMBER-1: " );
scanf("%d",&n1);
printf("\nENTER NUMBER-2: " );
scanf("%d",&n2);
add=n1+n2;
sub=n1-n2;
prod=n1*n2;
quot=n1/n2;
remain=n1%n2;
printf("\nADDITION OF THE NUMBERS: %d",add);
printf("\nSUBSTRACTION OF THE NUMBERS: %d",sub);
Example 4-9
EXERCISE
1. Determine which of the following are valid identifiers. If invalid, explain why ?
(a) record 1 (b) return (c) name_and_address (d) name-and-address
2. What is the range of long double?
3. What does a declaration do?
4. What are the rules for naming variables?
5. What is the purpose of the preprocessing directive:
#include <stdio.h>
6. Discuss the various types of constants?
7. What is an operator ? Describe several different type of operator included in C.
8. What are the basic modules of a C program called?
9. What is a syntax error? Give an example of one in English and one in C.
10. What is a semantic error? Give an example of one in English and one in C.
11. Which of the following are C keywords? main, int, function, char, =
12. Which data type would you use for each of the following kinds of data?
a. The population of East Simpleton
b. The cost of a movie on DVD
c. The most common letter in this manual
d. The number of times that the letter occurs in this manual.
13. Why would you use a type long variable instead of type int?
14. Identify the type and meaning, if any, of each of the following constants:
a. '\b'
b. 1066
c. 99.44
18. Construct statements that do the following (or, in other terms, have the
following side effects):
a. Increase the variable x by 10.
b. Increase the variable x by 1.
c. Assign twice the sum of a and b to c.
d. Assign a plus twice b to c.
45. What is meant by ―top-down‘‘ programming? What are its advantages? How is
it carried out?
46. What is pseudocode? What advantage is there in using pseudocode to plan a
new program?
47. What is meant by ―bottom-up‖ programming? How does it differ from top-
down programming?
48. How much flexibility does the programmer have in the logical sequencing of
the statements within a C program? Explain.
49. Why are some statements indented within a C program? Is this indentation
absolutely necessary?
50. What are the reasons for placing comments within a C program? How
extensive should these comments be?
51. Name two factors that contribute to the generation of clear, legible output data.
52. What useful information is provided by prompts?
53. How is a program entered into the computer in most contemporary C
programming environments?
54. What is a program name extension?
55. What is a syntactic error? Name some common syntactic errors.
Basic Programming – NTA 6 Page 18
56. What is an execution error? Name some common execution errors.
57. How do syntactic errors and execution errors differ from one another?
58. What is a logical error? How do logical errors differ from syntactic and
execution errors?
59. What are diagnostic messages?
60. What is the difference between compilation messages and execution messages?
Name some situations in which each type of diagnostic message would be
generated.
61. What is error isolation? For what is it used? How is error isolation carried out?
62. Pick up the correct alternative for each of the following questions:
(c) C programs are converted into machine language with the help of
(1) An Editor
(2) A compiler
(3) An operating system
(4) None of the above
(d) The real constant in C can be expressed in which of the following forms
(1) Fractional form only
(2) Exponential form only
(3) ASCII form only
(4) Both fractional and exponential forms
(k) Which of the following shows the correct hierarchy of arithmetic operators in C
(1) **, * or /, + or -
(2) **, *, /, +, -
(3) **, /, *, +, -
(4) / or *, - or +
(y) Which of the following shows the correct hierarchy of arithmetic operations in C
(1) / + * -
(2) * - / +
(3) + - / *
(4) * / + -
(z) What will be the value of d if d is a float after the operation d = 2 / 7.0?
(1) 0
(2) 0.2857
(3) Cannot be determined
(4) None of the above
1. The distance between two cities (in km.) is input through the keyboard. Write a
program to convert and print this distance in meters, feet, inches and centimeters
.
/*
Distance Conversion:
1Km = 39370 inches
1Km = 3281 Feet
1Km = 100000 Cm
1Km = 1000 metres
#include<stdio.h>
main()
{
float km,m,cm,inch,foot;
inch = 39370*km;
foot = 3281*km;
cm= 100000*km;
m = 1000*km;
Alternative method:
#include<stdio.h>
int main()
{
float km,metres,feet,inches,cm;
/*conversions*/
metres = km *1000;
feet = km * 3280.83;
inches = km * 39370.0787;
cm = metres *100;
#include<stdio.h>
main()
{
printf ("Enter the marks obtained by the student in all the five subjects: ");
scanf ("%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5);
total= m1+m2+m3+m4+m5;
percentage = total/5;
printf ("\nThe aggregate marks obtained by the student are: %d", total);
printf ("\nThe percentage obtained by the student are %f", percentage);
Alternative method:
#include<stdio.h>
int main()
{
float s1,s2,s3,s4,s5;
float total,avg;
total = (s1+s2+s3+s4+s5);
avg = (total/500)*100;
#include<stdio.h>
int main()
{
float fh,cs;
cs = (fh-32.0)*(5.0/9.0);
return 0;
}
4. The length and breadth of a rectangle and radius of a circle are input through the
keyboard. Write a program to calculate the area and perimeter of the rectangle,
and the area and the circumference of the circle.
/*
aor: area of rectangle
por: perimeter of rectangle
aoc: area of circle
coc: circumference of circle
*/
#include <stdio.h>
aor = length*breadth;
por= 2*(length+breadth);
aoc = 3.14*radius*radius;
coc = 2*radius*3.14;
printf("\n\nThe area of the Circle with radius %f is: %f ", radius, aoc);
}
Or
#include<stdio.h>
int main()
{
float len,bre,rad;
float peri,circum,area_rec,area_circle;
return 0;
}
5. Two numbers are input through the keyboard into two locations C and D.
Write a program to interchange the contents of C and D.
#include<stdio.h>
main ()
{
int A,C,D;
printf ("Enter the value of C and D: ");
A=C;
C=D;
D=A;
#include<stdio.h>
main ()
{
int number, last_digit, next_digit, total;
last_digit = number%10;
total = last_digit;
printf ("The sum of the digits of the entered number is: %d", total);
*/
/*To understand the program, assume that the five digit number -- 12345 is entered
Calculate the values manually and check against the given number.
#include<stdio.h>
main()
{
int number, rev_num, next_digit,last_digit;
rev_num = last_digit; /* 5 */
/*HINT: If a number is divided using % , then the number to the right side of the decimal
point is the result. (This applies only to integers.) */
#include<stdio.h>
main ()
total = last_digit;
printf ("The total of the first and the last digit of the entered number is: %d", total);
}
9. A cashier has currency notes of denominations 10, 50 and 100. If the amount to
be withdrawn is input through the keyboard in hundreds, find the total number
of currency notes of each denominations the cashier will have to give to the
withdrawer.
clrscr();
printf("Enter currency in hundreds: ");
scanf("%d",&cur);
hun = cur/100;
ten = cur/10;
fifty = cur/50;
hunR = cur%100;
tenR = cur%10;
fiftyR = cur%50;