Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Problem Solving Using Computer: CDS101Module IIIISERBPR/CDS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

CDS101Module IIIISERBPR/CDS

Problem Solving using Computer


A computer is a tool to solve a problem.

Problem solving is the process of transforming the description of a problem into a


solution by using our knowledge of the problem domain and by relying on our ability
to select and use appropriate problem-solving strategies, techniques and tools.

Programming is a problem solving activity. When we write a program, we are


actually writing an instruction for the computer to solve something for us. Using a
computer as a problem solving tool following steps are involved

1. Problem Definition
A clearly defined problem is already half the solution. Computer programming
requires us to define the problem first before we even try to create a solution.

2. Problem Analysis:
Analyzing the problem require us to identify the following:

 Input(s) to the problem, their form and the input media to be used
 Output(s) expected from the problem, their form and the output media to be
used
 Special constraints or conditions (if any)
 Any formulas or equations to be used

For example, Compute the average marks obtained by students in "C-


Programming".

Inputs: Marks of individual students

Outputs: The average mark of students

Formula: Average = Total Marks / No of students

i.e. A =T/N

4. Coding:
Coding is the real job of programmer. The algorithm to solve a problem which is
described by pseudo-code or flow chart is converted into actual programming
CDS101Module IIIISERBPR/CDS

language code. The code written by programmer by using any programming


language like C is called the source code or source program.

5. Compilation and execution:


The source code written in any programming language is not directly executed by
the computer. It should be translated into to the machine readable format i.e. actual
machine language. The process of translation of source code into the target code is
called the compilation. Each programming language has its own compiler program
that translates the source code into its target code. The converted program in actual
machine language is then executed by the computer which is known as program
execution.

6. Debugging and Testing:


A written program may have errors, some errors can be detected by the language
compilers and some errors can not be identified by the compiler and occured during
the program run. Common types of errors are

 Syntax Errors: Identified by compiler at the program compilation time.


 Logical Errors: Not identified by the compiler at compile time and identified at
the execution time. e.g. misuse of operators

So testing is the process of checking the program for its correct functionality by
executing the program with some input data set and observing the output of the
program.

7. Documentation:
From the start of the problem solving to the end of the implementation of the
program, all the tasks should be documented i.e. kept for future reference. It is also
the important part of the problem solving or program development. Documentation
may be of two types

 Technical Documentation known as programmer's documentations which


includes the problem analysis to implementation details for that program. It is
needed for future reference for any modification, update of the program.

 User manual is the documentation prepared for the end-user of the program
that guides the user how to operate the program.
CDS101Module IIIISERBPR/CDS

Algorithms and Flowchart

Algorithm

–An algorithm is a clear and unambiguous specification of the steps needed to solve
a problem. It may be expressed in either:

a. Human language (e.g. English)

b. Pseudocode - which is a cross between human language and a programming


language.

A pseudocode is:

 An artificial and informal language that helps programmers to develop


algorithms
 Not an actual programming language
 Not actually executed on computers

Why do you need it?

 Helps to “think out” a program before writing it


 May be converted easily into a corresponding programming language code.

c. Graphical representation like a flowchart

Example of Algorithm:

Problem: Compute the average marks of students obtained in a TEST of "Computer


Programming"

Human Language Specification: (In English)

1. Read the no of students


2. Read the marks of each students
3. Sum the marks of all students as total marks.
4. Divide the total marks by number of students.
5. Report the result of division as average marks of students.

Pseudocode Specification:

1. Input N
2. Input N marks: m1, m2, m3,..... mN
CDS101Module IIIISERBPR/CDS

3. T = (m1+ m2 + m3 +... ... ....+ mN) / N


4. A = T / N
5. Output N.

Flow-Chart:

A flow-chart is the graphical representation of the algorithm for any problem. It is


useful for developing and representing algorithms. Flow charts are drawn using
certain special-purpose symbols connected by arrows called flowlines. The symbols
indicate the actions to be performed, and flowlines indicate the order in which actions
are to be performed.

Flow chart symbols

start/stop

Oval symbol (or termination symbol) indicates the beginning or end of a program, or
a section of code

read/print

Parallelogram symbol for input/output operation

processing statement

Rectangle symbol (or action symbol) indicates any type of processing,

calculation
CDS101Module IIIISERBPR/CDS

condition check

Diamond symbol (or decision symbol) indicates that a decision is to be made

direction of flow

Flowline connects one symbol to another

connectors

Entry or exit points are used to attach the one flowchart to another

Example of flow -chart for above problem solving:


CDS101Module IIIISERBPR/CDS

Another Example: Pseudo code and flow chart for calculation of grade of students

Input the marks of student

if mark is greater than or equal to 90

print “A”

else

if student’s mark is greater than or equal to 80


CDS101Module IIIISERBPR/CDS

print “B”

else

if student’s mark is greater than or equal to 70

print “C”

else

if student’s mark is greater than or equal to 60

print “D”

else

print “F”

Another Example:

The algorithm sums all the even numbers between 1 and 20 inclusive and then
displays the
CDS101Module IIIISERBPR/CDS

sum. It uses a repeat loop and contains a null else within the repeat loop.

The major reasons are that the flow chart.

 is easier to read
 more closely follows a standard, this is not the the case with pseudocode
 easier to understand than pseudocode

History of C
CDS101Module IIIISERBPR/CDS

C is a general-purpose computer programming language developed between 1969


and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix
operating system. according to Ritchie, the most creative period occurred in 1972. It
was named "C" because its features were derived from an earlier language called
"B", which according to Ken Thompson was a stripped- down version of the BCPL
programming language. Although C was designed for implementing system
software, it is also widely used for developing portable application software.

C is one of the most widely used programming languages of all time and there are
very few computer architectures for which a C compiler does not exist. C has greatly
influenced many other popular programming languages, most notably C++, which
began as an extension to C. The origin of C is closely tied to the development of the
Unix operating system, originally implemented in assembly language on a PDP-7 by
Ritchie and Thompson, incorporating several ideas from colleagues. Eventually they
decided to port the operating system to a PDP-11. B's inability to take advantage of
some of the PDP-11's features, notably byte addressability, led to the development
of an early version of C.

The original PDP-11 version of the Unix system was developed in assembly
language. By 1973, with the addition of struct types, the C language had become
powerful enough that most of the Unix kernel was rewritten in C. This was one of the
first operating system kernels implemented in a language other than assembly.
(Earlier instances include the Multics system (written in PL/I), and MCP (Master
Control Program) for the Burroughs B5000 written in ALGOL in 1961.) In 1978, Brian
Kernighan and Dennis Ritchie published the first edition of The C Programming
Language. This book, known to C programmers as "K&R", served for many years as
an informal specification of the language. The version of C that it describes is
commonly referred to as K&R C. The second edition of the book covers the later
ANSI C standard

Structure of C program (preprocessor directive)

The C – Preprocessor

The preprocessor is a program that processes the source code before it passes
through the compiler. It operates under the control of preprocessor command line or
directives. Preprossor directives are placed in the source program before the main
line. Before the source code passes through the compiler, it is examined by
preprocessor. After taking appropriate actions as directed by preprocessor, the
source program is handed over to the compiler.

The syntax of pre-processor directives begin with the symbol # and do not require
semi colon (;) at the end. The pre-processor directives can be divided into three
categories.

1. Macro substitution (#define directives)


2. File Inclusion (#include directives)
3. Compiler control Directives
CDS101Module IIIISERBPR/CDS

The first C Progam

/* This program prints the Welcome to C Programming. */

#include <stdio.h> /* header file */

main()

printf(“Welcome to C programming.\n”);

} /*End of program */

Analysis:

Comments: See the lines 1,2,6 of the program

Any things between /* and */ is treated as comments in C. These are for only
programmer references . Comments are escaped by C compiler during compilation
of program.

Preprocessor: See in line 2.

#include<stdio.h>

stdio.h is an input output header file which contains the input/output and file handling
functions which are used in C programs. The required header file should be included
using #include preprocessor directive.

main():

C programs are made of functions. main() is a special function which should be there
in each c program. Each C program starts executing from main() function. As
program cannot have many starting points, C program should have main function
once and only once. main() may call other function to perform the given task.

printf()

printf is an output function which has been defined in stdio.h file. What ever is put
inside the function printf between two double quotes is printed on the screen

New lines: Note that printf never puts new line automatically. To put new line we
require to put ‘\n’ between double quotes inside ‘printf’ function.
CDS101Module IIIISERBPR/CDS

Eg

printf(“Welcome to ”);

printf(“C programming”);

Output: Welcome to C programming

Using new line:

printf(“Welcome to\nC programming”);

Prints the line as

Welcome to

C programming.

Statements: C programs are made of functions. Functions contain statements.


Statement performs a specific action and terminated by semicolon ‘;’ . In the above
program

printf(“Welcome to C programming”); is only statement.

You can write printf statement in multiple line . for example

The statement:

printf(“ The increasing popularity of C is probably”

“ Due to its many desirable quantities/.”

“It is a robust language whose rich set is “);

is a single statement.

Structure of C program (#define directives)

Macro Substitution:
CDS101Module IIIISERBPR/CDS

In macro substitution, an IDENTIFIER is replaced by pre-defined string. The


preprocessor accomplishes this job under the direction of #define directives which is
called macro. The syntax for macro definition is:

#define IDENTIFIER string

If this line is included at the beginning of the program, preprocessor replaces


IDENTIFIER in source code by string defined in macro. The IDENTIFIER must be C
valid name.

There are three different forms of macro substitutions:

1. Simple macro substitution


2. Arguemented macro substitution
3. Nested macro substitution

A simple macro:

A simple macro is generally used to define symbolic constants.

example:

#define PI 3.14159
#define TRUE 1
#define CITY “Kathmandu”
#define TWO_PI 2*(22/7)
#define BLANK_LINE printf(“\n”);
#define INCREMENT ++
#define START {
#define END }
etc.

The Uppercase letter for IDENTIFIER is conventions for defining Constants.

Arguemented macro :

We can define complex macro with arguments. The syntax is

#define IDENTIFIER(a1,a2,…..,an) string

 There is no space between IDENTIFIER and parenthesis .


 a1,a2,….,an are macro formal parameters.
 When a macro is called , the preprocessor substitutes the string, replacing the
formal parameters with actual parameters( passed when calling macro )

Example:
CDS101Module IIIISERBPR/CDS

#define SQUARE(x) ((x)*(x))


#define CUBE(x) ((x)*(x)*(x))
We can call these macro in our source program as

Area = PI*SQUARE(radius);
Which is equivalent to :

Area = PI*((radius)*(radius)); /*substitution of macro */

Other examples of arguemented macro:

#define MAX(a,b) (((a)>(b))? (a): (b))


#define MIN(a,b) (((a)<(b))? (a) : (b))
#define MODVAL(x) (((x)>0) ? (x) : (-(x)))
#define RECIPROCAL(x) (1.0/(x))
etc.

Nesting macro:

We can use one pre-defined macro to define new macro. This is called nesting of
macro definition.

Example:

#define PI 3.14159

#define TWO_PI 2*PI

#define SQUARE(x) ((x)*(x))

#define CUBE(x) ((x)*SQUARE(x))

#define SIX_POWER(x) ((CUBE(x))*(CUBE(x)))

 Given the definition of macro MAX(a,b) , We can use nested call of macro to
fine maximum of three numbers a,b,c as: MAX(a,MAX(a,b))
 To define multiple lines we can use \ character at the end of each line:

Undifining a Macro:

A defined macro can be undefined, using the statement:

#undef IDENTIFIER

it is useful when to restrict the definition only to a particular part of the program.
CDS101Module IIIISERBPR/CDS

Structure of C program(#include directives)

File inclusion directives: (#include directives)

A file which contains the pre-defined macros and functions can be included in our
source program using #include directive. If we include pre-written file in our source
program we need not to rewrite the functions and macro which are defined in that
file.

The syntax for file inclusion directive is :

#include<filename> or #include “filename”

 When #include<filename> is used, the file inside < > is searched in the
standard directory and included in the source program where it is written. If
file is not find an error is reported.
 When #include “filename” is used , the file inside “ ” is searched first in the
current directory and then standard directory included in the source program
where it is written.

If file is not find an error is reported.

A simple example of file inclusion:

Consider a file named test.c which includes the definition of functions for square and
cube and macro to find the maximum of two numbers , and constant PI.

/* test.c */
#define PI 3.14
#define MAX(x,y) ( ( (x) > (y) ) ? (x) : (y) )

int square(int x) /*square function */


{
return x*x;
}

int cube(int x) /*cube function */


{
turn (x*x*x);
}

Now we have to write a program that uses functions and macros defined in test.c.
the source program is as:

/*source.c */
#include<stdio.h>
#include “test.c”
CDS101Module IIIISERBPR/CDS

void main()
{
int x =10, y=20;
printf(“\nThe square of %d is %d” , x, square(x));
printf(“\nThe cube of %d is %d “, x, cube(x));
printf(“\n The larger no is %d.”, MAX(a,b));
}

when we run the source file source.c the output will be

The square of 10 is 100

The cube of 10 is 1000

The larger no is 20.

Elements Of C Program
The Structure of a C Program #

All C programs will consist of at least one function, but we can write a C programs
that have several functions body . The only function that has to be present is the
function main. For more advanced programs the main function will act as a
controling function calling other functions in their turn to do the dirty work! The main
function is the first function that is called when your program executes. So main is
the starting of execution of program.

The general form of a C program is as follows :

preprocessor directives

global declarations of user functions

global variables declarations

main()

local variables to function main ;

statements associated with function main ;


CDS101Module IIIISERBPR/CDS

definitions of functions like

function1()

local variables to function 1 ;

statements associated with function 1 ;

function2()

local variables to function f2 ;

statements associated with function 2 ;

... etc

Note the use of the bracket set () and {}: () are used in conjunction with function
names whereas {} are used with the C statements that are associated with that
function and used for statements block. A semicolon (;) is used to terminate C
statements. C is a free format language and long statements can be continued,
without truncation, onto the next line. The semicolon informs the C compiler that the
end of the statement has been reached. Free format also means that you can add as
many spaces as you like to improve the look of your programs. A very common
mistake made by everyone, who is new to the C programming language, is to miss
off the semicolon. The C compiler will concatenate the various lines of the program
together and then tries to understand them - which it will not be able to do. The error
message produced by the compiler will relate to a line of program which could be
some distance from the initial mistake.

Constants/ Literals #

Like a variable, a constant is a data storage location used by our program. Unlike a
variable, the value stored in a constant can't be changed during program execution.
C has two types of constants, each with its own specific uses.

The constants in C are illustrated in figure below:


CDS101Module IIIISERBPR/CDS

Integer Constants are sequences of digits. There are three types of integers
namely decimal ,octal and hexadecimal .

The largest integer value that can be stored is machine-dependent. It is 32767 on 16


bit machine and 2,147,483,647 on 32-bit machine. But it is also possible to store
larger integer constants on these machines by appending qualifiers such as U,L and
UL to the constants.

e.g.

56789U or 56789u for unsigned integer

987612347UL or 987612347ul for unsigned long integer.

9876543L or 9876543l for long integer.

Real Constants are the numbers with fractional parts and optional leading + or –
symbol.

e.g. 0.9876, -9.786, +98.765 etc which are in decimal notation.

0.65e4, 1.5e+5, -1.2E-1 etc. in scientific notations.

Single Character constants contains a single character enclosed within a pair of


single quote marks. Example: ‘c’, ‘%’, ‘&’, ‘7’ etc.
CDS101Module IIIISERBPR/CDS

A String Constant is a sequence of characters enclosed in double quotes. The


characters may be letters, numbers special characters and blank space.

Example: “Well come”, “a”, “890”, “*&^%$” etc.

In addition C supports some special backslash character constants that are used in
outputfunctions.

For example: ‘\n’ for newline, ‘\t’ for tab, ‘\b’ for back space, ‘\”’ for double quote ‘\\’
for \ and so on.

A small program to illustrate the constants in c.

/* this program illustrates the constants used in C */


#include<stdio.h>

main()
{
printf(“\nIntegers: ”);
printf(“%d, %d , %d”, 32767, 32767+1, 32767+10);
printf(“\nLong integers: ”);
printf(“%ld, %ld, %ld “, 32767, 32767+1, 32767+10);
printf(“\nUnsigned integers: ”);
printf(“%u,%u,%u”, 32767, 32767+1, 32767+10);
printf(“\nReal constants:”);
printf(“%f, %f, %f”, 3.4, 9.9e3, -1.2e-6);
printf(“\nCharacter :%c “,’A’);
printf(“\nA string :%s “, “C programming”);
return 0;
}

output

Integers: 32767, -32768 , -32759

Long integers: 32767, 32768, 32777

Unsigned integers: 32767, 32768, 32777

Real constants: 3.400000, 9100.000000, -0.000001

Character: A

A String: C programming
CDS101Module IIIISERBPR/CDS

All the types of above constants can be classified in to two main categories.

1. Literal Constants
2. Symbolic Constants.

Literal Constants

A literal constant is a value that is typed directly into the source code wherever it is
needed. Here are two examples:

int count = 20;

float tax_rate = 0.28;

The 20 and the 0.28 are literal constants. The preceding statements store these
values in the variables count and tax_rate. Note that one of these constants contains
a decimal point, whereas the other does not. The presence or absence of the
decimal point distinguishes floating-point constants from integer constants.

A literal constant written with a decimal point is a floating-point constant and is


represented by the C compiler as a double-precision number. Floating-point
constants can be written in standard decimal otation, as shown in these examples:

123.456

0.019

100.

Note that the third constant, 100., is written with a decimal point even though it's an
integer (that is, it has no fractional part). The decimal point causes the C compiler to
treat the constant as a double- precision value. Without the decimal point, it is
treated as an integer constant.

Floating-point constants also can be written in scientific notation. In C, scientific


notation is written as a decimal number followed immediately by an E or e and the
exponent:
CDS101Module IIIISERBPR/CDS

1.23E2 is 1.23 times 10 to the 2nd power, or 123

4.08e6 4.08 times 10 to the 6th power, or 4,080,000

0.85e-4 0.85 times 10 to the -4th power, or 0.000085

A constant written without a decimal point is represented by the compiler as an


integer number. Integer constants can be written in three different notations:

A constant starting with any digit other than 0 is interpreted as a decimal integer (that
is, the standard base-10 number system). Decimal constants can contain the digits 0
through 9 and a leading minus or plus sign. (Without a leading minus or plus, a
constant is assumed to be positive.)

e.g.

123

-670

8965 etc.

A constant starting with the digit 0 is interpreted as an octal integer (the base-8
number system). Octal constants can contain the digits 0 through 7 and a leading
minus or plus sign.

e.g. 065 034 etc.

A constant starting with 0x or 0X is interpreted as a hexadecimal constant (the base-


16 number system). Hexadecimal constants can contain the digits 0 through 9, the
letters A through F, and a leading minus or plus sign.

e.g. 0x9F 0X7C 0xAB etc.

Symbolic Constants

A symbolic constant is a constant that is represented by a name (symbol) in our


program. Like a literal constant, a symbolic constant can't change. Whenever we
CDS101Module IIIISERBPR/CDS

need the constant's value in our program, we use its name as we would use a
variable name. The actual value of the symbolic constant needs to be entered only
once, when it is first defined.

Symbolic constants have two significant advantages over literal constants, as the
following example shows. Suppose that we're writing a program that performs a
variety of geometrical calculations. The program frequently needs the value ,,
(3.14159) for its calculations.For example, to calculate the circumference and area of
a circle with a known radius, we could write

circumference = 3.14159 * (2 * radius);


area = 3.14159 * (radius)*(radius);

If, however, we define a symbolic constant with the name PI and the value 3.14, we
could write

circumference = PI * (2 * radius);
area = PI * (radius)*(radius);

The resulting code is clearer. Rather than puzzling over what the value 3.14 is for,
we can see immediately that the constant PI is being used.

The second advantage of symbolic constants becomes apparent when we need to


change a constant. Continuing with the preceding example, we might decide that for
greater accuracy our program needs to use a value of PI with more decimal places:
3.14159 rather than 3.14. If we had used literal constants for PI, we would have to go
through our source code and change each occurrence of the value from 3.14 to
3.14159. With a symbolic constant, we need to make a change only in the place
where the constant is defined.

C has two methods for defining a symbolic constant: the #define directive and the
const keyword. The #define directive is one of C's preprocessor directives which is
used as follows:

#define CONSTNAME literal

This creates a constant named CONSTNAME with the value of literal. literal
represents a literal constant(i.e.value for constant). CONSTNAME follows the same
rules described for variable names. By convention, the names of symbolic constants
are uppercase. This makes them easy to distinguish from variable names, which by
convention are lowercase. For the previous example, the required #define directive
would be

#define PI 3.14159
CDS101Module IIIISERBPR/CDS

Note that #define lines don't end with a semicolon (;). #defines can be placed
anywhere in our source code, but they are in effect only for the portions of the source
code that follow the #define directive. Most commonly, programmers group all
#defines together, near the beginning of the file and before the start of main().

How a #define Works

The precise action of the #define directive is to instruct the compiler as follows: "In
the source code, replace CONSTNAME with literal." Note that #define doesn't
replace instances of its target that occur as parts of longer names, within double
quotes, or as part of a program comment. For example, in the following code, the
instances of PI in the second and third lines would not get changed:

#define PI 3.14159
/* You have defined a constant for PI. */
#define PIPETTE 100

Defining Constants with the const Keyword

The second way to define a symbolic constant is with the const keyword. const is a
modifier that can be applied to any variable declaration. A variable declared to be
const can't be modified during program execution-only initialized at the time of
declaration. Here are some examples:

const int count = 100;


const float pi = 3.14159;
const long debt = 12000000, float tax_rate = 0.21;

const affects all variables on the declaration line. In the last line, debt and tax_rate
are symbolic constants. If our program tries to modify a const variable, the compiler
generates an error message, as shown here:

const int count = 100;


count = 200; /* Does not compile! Cannot reassign or alter the value
of a constant. */

Now look at this small program that demonstrates the use of variables and
constants.

/* Demonstrates variables and constants */


#include <stdio.h>
CDS101Module IIIISERBPR/CDS

/* Define a constant to convert from pounds to grams */


#define GRAMS_PER_POUND 454

/* Define a constant for the start of the next century */


const int NEXT_CENTURY = 2000;

/* Declare the needed variables */


long weight_in_grams, weight_in_pounds;
int year_of_birth, age_in_2000;

main()
{
/* Input data from user */

printf("Enter your weight in pounds: ") scanf("%d", &weight_in_p


ounds);
printf("Enter your year of birth: ");
scanf("%d", &year_of_birth);

/* Perform conversions */

weight_in_grams = weight_in_pounds * GRAMS_PER_POUND;


age_in_2000 = NEXT_CENTURY - year_of_birth;

/* Display results on the screen */

printf("\nYour weight in grams = %ld", weight_in_grams);


printf("\nIn 2000 you will be %d years old\n" age_in_2000);

return 0;
}

Analysis: This program declares the two types of symbolic constants in lines 5 and
8. In line 5, a constant is used to make the value 454 more understandable. Because
it uses GRAMS_PER_POUND, line 25 is easy to understand. Lines 11 and 12
declare the variables used in the program. Notice the use of descriptive names such
as weight_in_grams. We can tell what this variable is used for. Lines 18 and 20 the
printf() print prompts on-screen. To allow the user to respond to the prompts, lines 19
and 21 use another library function, scanf() which gets input information. Lines 25
and 26 calculate the user's weight in grams and his or her age in the year 2000. To
finish the program, lines 30 and 31 display the results for the user.

NOTE: DON'T try to assign a value to a constant after it has already


been initialized

Expressions #
CDS101Module IIIISERBPR/CDS

Expressions

In C, an expression is anything that evaluates to a numeric value. C expressions come in all


levels of complexity.

Simple Expressions

The simplest C expression consists of a single item: a simple variable, literal constant, or
symbolic constant. Here are four expressions:

Expression Description

PI A symbolic constant (defined in the program)

20 A literal constant

Rate A variable

-1.25 Another literal constant

A literal constant evaluates to its own value. A symbolic constant evaluates to the value it
was given when we created it using the #define directive. A variable evaluates to the current
value assigned to it by the program.

Complex Expressions

Complex expressions consist of simpler expressions connected by operators.

For example:

2 + 8

is an expression consisting of the sub-expressions 2 and 8 and the addition operator +. The
expression 2 + 8 evaluates 10. we can also write C expressions of great complexity:

1.25 / 8 + 5 * rate + rate * rate / cost

Consider the following statement:

x = a + 10;
CDS101Module IIIISERBPR/CDS

This statement evaluates the expression a + 10 and assigns the result to x. In addition, the
entire statement x = a + 10 is itself an expression that evaluates to the value of the variable on
the left side of the equal sign.

Thus, we can write statements such as the following, which assigns the value of the
expression

a + 10 to both variables, x and y as:

y = x = a + 10;

We can also write statements such as this:

x = 6 + (y = 4 + 5);

All of these are complex expression.

Statements #

Statements

A statement is a complete direction instructing the computer to carry out some task.
In C, statements are usually written one per line, although some statements span
multiple lines. C statements always end with a semicolon (except for preprocessor
directives such as #define and #include.

For example:

x = 2 + 3;
is an assignment statement. It instructs the computer to add 2 and 3 and to assign
the result to the variable x.

Statements and White Space

The term white space refers to spaces, tabs, and blank lines in the source code. The
C compiler isn't sensitive to white space. When the compiler reads a statement in the
source code, it looks for the characters in the statement and for the terminating
semicolon, but it ignores white space. Thus, the statement

x=2+3;

is equivalent to this statement:


CDS101Module IIIISERBPR/CDS

x = 2 + 3;

It is also equivalent to this:

x =
2
+
3;

This gives us a great deal of flexibility in formatting our source code. We shouldn't
use formatting like the previous example, however. Statements should be entered
one per line with a standardized scheme for spacing around variables and operators.
The point is to keep our source code readable.

However, the rule that C doesn't care about white space has one exception: Within
literal string constants, tabs and spaces aren't ignored; they are considered part of
the string. A string is a series of characters. Literal string constants are strings that
are enclosed within quotes and interpreted literally by the compiler, space for space.
Although it's extremely bad form, the following is legal:

printf(
"Hello, world!"
);

This, however, is not legal:

printf("Hello,
world!");

To break a literal string constant line, you must use the backslash character (\) just
before the break. Thus, the following is legal:

printf("Hello,\
world!");

Null Statements

If we place a semicolon by itself on a line, we create a null statement i.e. a statement


that doesn't perform any action. This is perfectly legal in C. Later

Eg, the null statement is: ;


CDS101Module IIIISERBPR/CDS

Compound Statements

A compound statement, also called a block, is a group of two or more C statements


enclosed in braces. Here's an example of a block:

{
printf("Hello, ");
printf("world!");
}

In C, a block can be used anywhere a single statement can be used. Note that the
enclosing braces can be positioned in different ways. The following is equivalent to
the preceding

example:

{printf("Hello, ");
printf("world!");}

It's a good idea to place braces on their own lines, making the beginning and end of
blocks clearly visible. Placing braces on their own lines also makes it easier to see
whether we've left one out. But if there are large number of statements inside the
block , it is not possible to place braces in one lines.

Notes:

 DO put block braces on their own lines. This makes the code easier to read.
 DO line up block braces so that it's easy to find the beginning and end of a
block.
 DON'T spread a single statement across multiple lines if there's no need to do
so. Limit statements to one line if possible.

You might also like