Structured Programming With C Language
Structured Programming With C Language
COLLEGE OF ENGINEERING
2012/2013 SECOND SEMESTER
ENG 224: STRUCTURED COMPUTER PROGRAMMING WITH C
INSTRUCTOR:
Mrs Ikpeze O. F.
COURSE DESCRIPTION
Algorithm, Top-down, Bottom-up design, flowchart, pseudo-codes and state diagrams.
Modular designs and sequence looping decision mechanism.
Flow of control in programming languages
User defined expressions and statements
Abstractions: Sub programming and co-routines
Exception handling
Parameter passing method, closures, continuation, and higher order functions
Program construction: object oriented functional and logic paradigms
Programming Paradigms: Visual Basic 6
REQUIREMENTS
Visual Studio C++ express 2010 or higher
Visual basic.Net
Laptops or Desktops
ICT Lab and Interactive Board
COURSE EVALUATION
Assignments, Attendance and Test: 30%
Final examination: 70%
1 2 3 4 5 6 7 8 9 10 10 5
1
5
0
10
0
30
80
1
70
0
100
0
GRADE
A
REG
Registered
COURSE POLICIES
Late Assignment without a valid excuse will be lowered 10% for each day late. A late
assignment will not be accepted once the solution is discussed in class.
Collaboration is inappropriate in this course. However, you are encouraged to discuss the
assignment specifications with your instructors and your fellow students. anything you
submit for grading must be unique and should NOT be a duplicate of another source. For
collaboration assignment penalty will be failure.
Cell Phone: Do extend courtesy to your instructors and fellow students by turning off your
cell phones.
Attendance and Quiz: You are expected to attend all lectures except under very extreme
circumstances. Quiz will be conducted in class without prior notice.
Lecture notes are intended to serve as a supplement and not as a substitute for attending
class.
Lateness to class after 15 Mins into the lecture will not be allowed without a valid excuse.
The Instructors or Management reserves the right to modify course policies, course calendar,
course content, assignment values and due dates, as circumstances require.
`
SUGGESTED READINGS
C Programming Essentials By: K. N. Dey; S. K. Bandyopadhyay, Safari Books Online
C FOR Dummies 2nd edition by Dan Gookin
C Programming for Embedded Systems by Kirk Zurell
C Language Tutorial
PART 1.. 4
1.2. Systems Software.. Error! Bookmark not defined.
1.3. Application Software.. Error! Bookmark not defined.
1.4. Program Development Process. 4
1.5. Algorithms. 5
1.6. Analysis of Algorithms. 5
1.7. Flowcharts. 6
1.8. Programming Language Classifications. 7
1.9
Programming Techniques. 11
Terminology Checklist. 14
Exercises. 16
PART 2.. 18
1.11. History of C Language.. 18
1.12. C Language Overview.. 18
PART 1
Understanding the Specifications: The specification for the problem must be clear and
unambiguous.
Role of the System Analyst: The system analyst determines the nature of the inputs
and outputs needed, and provides the input and output layouts along with the
processing requirements for the programmers.
Solution Design: Involves testing the various conditions, taking alternate paths in the
procedure depending on the outcome of the test, and determining the sequence of the
steps. There are two ways of accomplishing this task:
o
Testing and Debugging: A computer program may not run properly the first time due
to the possibility of logical and/or syntactic errors. These errors are referred as bugs.
The process of removing these bugs is called debugging. The errors in the program
are checked by testing it at various stages.
o
Use of Test Data: Test data should be prepared in such a way that the
programs run by using this data. It should be prepared so as to include all the
conditions that the program is expected to test.
Use of Diagnostic Tools: There are diagnostic aids, which programmers may
deploy to detect errors when a program fails to run correctly. The diagnostic
procedures may vary from one language to another. The diagnostic tools
provide, in general, a method for testing the execution of a program at each
step or each time the program follows a particular path. Breakpoints may also
be used in code for debugging purposes.
Installation: The tested software is installed at the client end and finally tested with
real-time data.
1.3. Algorithms
An algorithm is a well-defined computational procedure (sequence of computational steps). It
takes a set of values as its input and produces a set of values as its output. It can be viewed as
a utility for solving a computational problem.
There are a number of important features that must be satisfied by any algorithm:
Finiteness: This imposes that the algorithm must terminate after executing a finite
number of steps, i.e., it cannot run infinitely.
Input and Output: An algorithm has a domain of values, which initialize the
procedures. These are called the input values to the algorithm. It must also generate a
set of result values called output values. Thus, an algorithm can be viewed as a
function or a transformation that maps input values to output values.
Example 1.
Design an algorithm for adding the test scores given below
26, 49, 98, 87, 62, 75, 41, 20, 100, 15
Algorithm Solution
1. Start
2. Sum = 0
3. Get the first testscore
4. Add first testscore to sum
5. Get the second testscore
6. Add to sum
7. Get the third testscore
8. Add to sum
9. Get the Forth testscore
10. Add to sum
11. Get the fifth testscore
12. Add to sum
13. Get the sixth testscore
14. Add to sum
15. Output the sum
16. Stop
1.4. Flowcharts
A flowchart is a graphic/pictorial representation of the steps necessary to solve a problem,
accomplish a task, complete a process, or illustrate the components of a system.
The various flowchart symbols are explained as follows:
Oval/Rounded Rectangle: These symbols indicate the start or end of the program as
indicated by the text written inside the symbol.
Rectangle: Indicates a processing step where the step performed is indicated inside
the rectangle.
Diamond: Indicates that a condition check is to be performed. The data under test and
the test performed are indicated inside the diamond.
Fig. 1.2 Flowchart for the Algorithm adding the test scores
1.5. Programming Language Classifications
A language is a medium for communication. The languages we speak are called natural
languages. A programming language is a subset of the set of natural languages. It contains all
the symbols, characters, and usage rules that permit a human being to communicate with
computers. A variety of programming languages have been invented over the years of
computer history. However, every programming language must accept certain types of
written instructions that enable a computer system to perform a number of familiar
operations.
In other words, every programming language must have instructions that fall under the
following categories:
Input/Output Instructions: A program needs input data from the external world with
which it performs operations on the input data, and generates output. Input/output
instructions, provide details on the type of input or output operations to be performed,
and the storage locations to be used during the operations.
Storage/Retrieval and Movement Instructions: These are used to store, retrieve, and
move data during processing. Data may be copied from one storage location to
another and retrieved as required.
Control Instructions: These are selection and loop constructs, which aid in out-ofsequence program flow.
Although all programming languages have an instruction set that permits these familiar
operations to be performed, a marked difference is found between the symbols and syntax
used in machine languages, assembly languages, and high-level languages.
For example, if a Zilog microprocessor is used, then the machine language understood is Z80. On the other hand, a flavour of the Intelassembly language is used for a
Pentium microprocessor which differs from the Z-80. Thus, assembly languages are
architecture-dependent.
The program mirrored the machine languages using symbols, or mnemonics, to represent the
various machine instructions. The languages developed in this manner were known as
symbolic languages. An assembler translates symbolic code into machine language thus
Assembly Language.
Increased Speed and Capacity of Hardware: The third and fourth generations of
computer hardware brought about a revolution in access time, memory and disk
capacities. This caused the time overhead incurred by the use of high-level languages
to be tolerable.
As stated earlier, the task of coding for a problem in a convenient programming language is
performed only after extensive effort in the problem-solving stage. The following sections
provide an insight into some commonly adopted programming techniques.
1.6.1. Bottom-up Design
Early programming techniques developed in the 1950s centered on problem-solving by using
bottom-up design of the solution in which the extreme details of the programming solution
were investigated first, as opposed to beginning with a breakdown by broad objectives. Each
program was written in isolation to solve a particular sub-problem. The difficulty arose when
the various sub-programs had to work together to produce the desired programs. Program
logic was guided by the limitations of primary memory, and programs were designed with the
objective of executing them as fast as possible. However, as application programs grew in
size, several programmers worked together to solve them. Project teams were set up,
consisting of several programmers and a project leader. However, programmers often switch
jobs and might leave a company before a project is fully developed, thus require another
programmer to continue the unfinished work midstream. This required formulation of a
definite summary of how a problem is to be solved. This was not provided by the bottom-up
approach to programming. Another approach was required.
1.6.2. Top-down Design
It allowed programs to be written in a more organized manner, i.e., in a structured manner,
producing code that is easier to read, analyze, and modify later if the need arose. With
increasing demands for software efficiency and programming standardization, a changed
approach saw the programmers examining the problem as a whole and outlining the major
steps to solve the problem. Then the process was repeated and the steps thus obtained were
broken down in finer details. This is the top-down programming approach and is used in
structured programming.
Each module involves processing of data that are logically related. Modules are
functional parts, which aid in processing. Ideally, each module works independent of
other modules, although this is sometimes impossible.
Modules are ranked by hierarchy and organized on the basis of importance. The lower
the module on the structure organization plan, more is the detail given to the
programming steps involved. The controlling module resides at the top level. It gives
the view of the overall structure for the entire program. The system is designed to give
more detail at each module level. A module is coded and tested, and then tested with
other tested modules. This procedure makes program testing easier, since there is only
one entry point and one exit point per module.
It implements modules (procedures / functions), each fulfilling some function and uses basic
programming constructs -sequence, selection and iteration.
The most common techniques used in structured programming to solve all problems are
called constructs. These constructs are also called control structures. Using three basic
control structures, it is possible to write standardized programs, which are easy to read and
understand.
Selection Structure: Selection refers to testing for a certain condition for data. There
are only two possible answers to questions regarding data true (yes) or false (no).
One selection-technique variation is known as the IF-THEN-ELSE. The instructions
that are to be executed when the condition is true follow the IF-THEN alternative. The
instructions followed by the ELSE alternative represent what is to be executed when
the condition is false. Figure (b) shows that if the condition is true, the control will
flow to function B and its statements will be executed; if it is false, function A is
executed. Another selection variation is the IF-THEN. It is used when some operation
is to be done only when the condition is true.
Repetition Structure: Repetition involves the use of a series of instructions that are
repeated until a certain condition is met. Repetition involves the use of two variations
the while and the do-while. The while performs a function as long as a condition is
true. On the other hand, do-while allows a function to be executed until the given
condition is false. Another marked difference is that the while first tests the given
condition and then executes the function, whereas do-while processes the function
before checking the condition. These are illustrated in Figure 1.3.
read number
write number
add 1 to total
end-repeat
OR
while total < = 50 do:
read number
write number
end-while
Algorithm Average
This algorithm reads a list of numbers and computes their average.
if COUNTER = 0 then
AVE = 0
else
AVE = SUM/ COUNTER
Stop.
S1
S1
S2
S2
S2
S1
Explanation
From the state transition table given above, it is easy to see that if the machine is in S1 and
the next input is character 1, the machine will stay in S1. If a character 0 arrives, the machine
will transition to S2 as can be seen from the second column. In the diagram this is denoted by
the arrow from S1 to S2 labeled with a 0.
Terminology Checklist
Program
Software
Algorithm
Assembly language
High-level Language
Flowchart
Debugging
Bottom-up design
Top-down design
Structured programming
Modular design
Pseudo Code
State Diagram
Exercises
1.Write an algorithm to find the maximum of three numbers a, b, and c. The output
should be stored in max.
2.An operating system never terminates it is infinite. Based on this statement,
justify whether an operating system is an algorithm.
3.Trace Euclids algorithm for GCD (in Section 1.5) for inputs (32, 14), (12, 9).
4.Modify Euclids algorithm (in Section 1.5) to accommodate a check of the input
variables so that the algorithm executes only on positive integer inputs and the
divide by zero error is detected.
5.Write an algorithm that accepts a positive integer number, n, and calculate the
factorial of the number. Reject inputs less than 1 or greater than 17.
6.Draw a flowchart to convert miles into kilometres, given that 1 km = 1.609 miles
and M is the input value in miles and K is the output value in kilometres.
7.Write an algorithm that calculates all the elements of rows and columns of a
square matrix and calculate the total of primary and secondary diagonal.
8.Write an algorithm that accepts two positive integer numbers n1 and n2 (n1 < n2),
and print the prime numbers in between n1 and n2, both inclusive.
9.What is validation of an algorithm?
10.What are the advantages and disadvantages of flowcharts?
PART 2
2.1 History of C Language
C has its origin in the early 1970, a project by AT&T Bell Labs, USA. Dennis Ritchie is
credited with defining and creating C. Many others also influenced the development of the
language. C is closely related to the UNIX operating system since it was developed along
with it. Most of the UNIX commands are written in C. Today, C has been implemented on
many different types of hardware and the language is used to tackle a large class of
programming problems.
2.2. C Language Overview
Several features make C a very attractive programming language for coding solutions. These
include:
#include <stdio.h>
int main()
{
printf("Hello Student, !\n");
return(0);
}
2.4 Hello Student Program Description
1. #include is known as a preprocessor directive. What it does is tell the compiler to
include text from another file, adding it right into your source code. Doing this
avoids lots of little, annoying errors that would otherwise occur.
2. 2. <stdio.h> The STDIO.H file contains information about the Standard
Input/Output functions required by most C programs. The H means header.The
whole statement #include <stdio.h> tells the compiler to take text from the file
STDIO.H and stick it into your source code before the source code is compiled.
3. 3. int main does two things. First, the int identifies the function main as an integer
function, meaning that main() must return an integer value when its done. Second,
that line names the function main, which also identifies the first and primary function
inside the program.
4. Two empty parentheses follow the function name. Sometimes, items may be in these
parentheses.
5. {} All functions in C have their contents encased by curly braces ({}). So, the function
name comes first (main in Item 3), and then its contents or the machine that
performs the functions job is hugged by the curly braces.
6. printf is the name of a C language function, It is written as printf(). Its job is to
display information on the screen. (Because printers predated computer monitors, the
commands that display information on the screen are called print commands.
7. Like all C language functions, printf() has a set of parentheses. In the parentheses, you
find text, or a string of characters. Everything between the double quote characters
() is part of printfs text string.
8. An interesting part of the text string is \n. Thats the backslash character and a little n.
What it represents is the character produced by pressing the Enter key, called a
newline in C.
9. The printf line, or statement, ends with a semicolon. The semicolon is C language
punctuation like a period in English. The semicolon tells the C compiler where one
statement ends and another begins. Note that all statements require semicolons in C,
even if only one statement is in a program or function.
10. The second statement in ex_1.C is the return command. This command sends the value 0
(zero) back to the operating system when the main () function is done. Returning a value is
required as part of the main () function. Note that even though this command is the last one in
the program, this statement ends in a semicolon.
Others
11. Scanf():scanf() is a function like printf(). Its purpose is to read text from the keyboard.
12. Comment: are explanatory remarks made within a program. When used carefully,
comments can be very helpful in clarifying what the complete program is about, what a
specific group of statements is meant to accomplish, or what one line is intended to do.
// comment
/* comment */
2.5 Conversion Control Sequence
Example Sum
#include <stdio.h>
int main()
{
printf("Sum of student score is %d \n", 6 + 14 +10 + 13 + 30);
return(0);
}
This statement passes two arguments to the printf () function.
The first argument is the message Sum of student score is %d \n".The second argument is the
value of the expression 6 + 14 +10 + 13 + 30.
The first argument passed to printf ( ) must always be a message. A message that also
includes a conversion control sequence, such as %d. Conversion control sequences have a
special meaning to the printf ( ) function. They tell the function what type of value is to be
displayed and where to display it. A conversion control sequence always begins with a %
symbol and ends with a conversion character (c, d, f, etc.).
Example Average
#include <stdio.h>
int main()
{
printf("Average of student score is %d \n", (6 + 14 +10 + 13 + 30)/5);
return (0);
}
2.6 Variables
A variable is a symbolic name for a memory location in which data can be stored and
subsequently recalled. Variables are used for holding data values so that they can be utilized
in various computations in a program.
int myValue; // integer =4 byte
char response; // Character = 1 byte
string name; //
double yCoord; // Double = 8 byte
Example
#include<stdio.h>
int main()
{
double PI = 3.14159;
double radius, area, circumference;
printf("Enter the radius in cm: ");
scanf_s("%d", &radius);
area = PI*radius*radius;
circumference = 2.0*PI*radius;
printf("The area is %d cm square.\n", area);
printf("The circumference is %d cm.\n", circumference);
return 0;
}
Example
Input/output operate to display first name, surname and matric number.
#include <stdio.h>
int main()
{
char sname[20];
char fname[20];
char matric[10];
Linker links several object (and library) files to generate an executable file. Links is a
computer program that takes one or more object files generated by a compiler and combines
them into a single executable program.
Library is a collection of implementations of behavior, written in terms of a programming
language, that has a well-defined interface by which the behavior is invoked.
Executable file causes a computer "to perform indicated tasks according to encoded
instructions.
2.8 Data Types and Operations
Identifiers are a name used to identify a variable, function, or any other user-defined item.
An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more
letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $,
and % within identifiers. C is a case sensitive programming language. Thus, ABUAD and
abuad are two different identifiers.
Example
mohd
zara
a23b9
retVal
Keywords These are reserved words and may not be used as constant or variable or any other
identifier names.
Auto
Else
long
switch
Break
enum
register
typedef
Case
extern
return
union
Char
Float
short
unsigned
Const
For
signed
void
continue
Goto
sizeof
volatile
Default
If
static
while
Do
Int
struct
_Packed
Double
2.8.1 Data Types
Data types refer to an extensive system used for declaring variables or functions of different
types.
Integer Types
Following table gives you details about standard integer types with its storage sizes and value
ranges:
Type
Char
1 byte
0 to 255
signed char
1 byte
-128 to 127
Int
unsigned int
Short
2 bytes
-32,768 to 32,767
0 to 65,535
Long
-2,147,483,648 to 2,147,483,647
4 bytes
0 to 4,294,967,295
Floating-Point Types
Following table gives you details about standard floating-point types with storage sizes and
value ranges and their precision:
Type
Storage size
Value range
Precision
Float
4 byte
1.2E-38 to 3.4E+38
6 decimal places
Double
8 byte
2.3E-308 to 1.7E+308
15 decimal places
long double
10 byte
3.4E-4932 to 1.1E+4932
19 decimal places
A variable declaration provides assurance to the compiler that there is one variable existing
with the given type and name. Variable determines how much space it occupies in storage.
The type of a Variable Declaration in C:
Type
Description
Char
Int
Float
Double
Void
Example
#include<stdio.h>
int main()
{
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0 / 3.0;
printf("value of f : %f \n", f);
ge0tchar();
return 0;
}
2.8.2 Lvalues and Rvalues
There are two kinds of expressions in C. An expression that is an lvalue may appear as either
the left-hand or right-hand side of an assignment. An expression that is an rvalue may appear
on the right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric
literals are rvalues and so may not be assigned and cannot appear on the left-hand side.
Following is a valid statement:
Example
a = 10; // Valid
10 = 20; //Not Valid
2.8.3 Constants and Literals
The constants refer to fixed values that the program may not alter during its execution. These
fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal.
Integer literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base
or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Examples
212
/* Legal */
215u
/* Legal */
0xFeeL
078
032UU
/* Legal */
/* Illegal: 8 is not an octal digit */
/* Illegal: cannot repeat a suffix */
85
/* decimal */
0213
/* octal */
0x4b
/* hexadecimal */
30
/* int */
30u
/* unsigned int */
30l
/* long */
30ul
/* unsigned long */
Floating-point literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent
part. You can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent, or
both and while representing using exponential form, you must include the integer part, the
fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals:
3.14159
/* Legal */
314159E-5L /* Legal */
510E
210f
.e55
2.8.5 Operators
Arithmetic Operators
Following table shows all the arithmetic operators supported by C language. Assume
variable A holds 10 and variable B holds 20 then:
Examples
Operato
Description
r
Example
A + B will give
30
A - B will give
-10
A * B will give
200
B / A will give
2
B % A will give
0
++
--
#include<stdio.h>
main()
{
int a = 10;
int b = 20;
int c;
c = a + b;
printf("Line 1 - Value of c is %d\n", c);
c = a - b;
printf("Line 2 - Value of c is %d\n", c);
c = a * b;
printf("Line 3 - Value of c is %d\n", c);
c = a / b;
printf("Line 4 - Value of c is %d\n", c);
c = a % b;
printf("Line 5 - Value of c is %d\n", c);
c = a++;
printf("Line 6 - Value of c is %d\n", c);
c = a--;
printf("Line 7 - Value of c is %d\n", c);
}
Bitwise Operators
The Bitwise operators supported by C language are listed in the following table. Assume
variable A holds 60 and variable B holds 13 then:
Examples
Operator Description
&
Example
(A & B) will give 12 which is 0000
1100
<<
>>
#include<stdio.h>
main()
{
unsignedint a = 60;
/* 60 = 0011 1100 */
unsignedint b = 13;
/* 13 = 0000 1101 */
int c = 0;
c = a & b;
/* 12 = 0000 1100 */
/* 61 = 0011 1101 */
/* 49 = 0011 0001 */
/* 15 = 0000 1111 */
Examples
Operato
Description
r
Example
+=
-=
*=
/=
%=
<<=
>>=
&=
^=
C ^= 2 is same as C = C ^ 2
|=
C |= 2 is same as C = C | 2
#include<stdio.h>
main()
{
int a = 21;
int c;
c = a;
C -= A is equivalent to C = C - A
Operato
Description
r
Example
sizeof()
&
Pointer to a variable.
?:
Conditional Expression
#include<stdio.h>
main()
{
int a = 4;
short b;
double c;
int* ptr;
/* example of sizeof operator */
printf("Line 1 - Size of variable a = %d\n", sizeof(a));
printf("Line 2 - Size of variable b = %d\n", sizeof(b));
printf("Line 3 - Size of variable c= %d\n", sizeof(c));
/* example of & and * operators */
ptr = &a; /* 'ptr' now contains the address of 'a'*/
printf("value of a is %d\n", a);
printf("*ptr is %d.\n", *ptr);
/* example of ternary operator */
a = 10;
b = (a == 1) ? 20 : 30;
printf("Value of b is %d\n", b);
b = (a == 10) ? 20 : 30;
printf("Value of b is %d\n", b);
}
Relational Operators
Following table shows all the relational operators supported by C language. Assume
variable A holds 10 and variable B holds 20, then:
Examples
Operato
Description
r
Example
==
Checks if the values of two operands are equal or not, if yes then
(A == B) is not true.
condition becomes true.
!=
(A != B) is true.
>
<
Checks if the value of left operand is less than the value of right
(A < B) is true.
operand, if yes then condition becomes true.
>=
<=
#include<stdio.h>
main()
{
int a = 10;
int b = 20;
int c;
if (a == b)
{
printf("Line 1 - a is equal to b\n");
}
else
(A <= B) is true.
{
printf("Line 1 - a is not equal to b\n");
}
if (a < b)
{
printf("Line 2 - a is less than b\n");
}
else
{
printf("Line 2 - a is not less than b\n");
}
if (a > b)
{
printf("Line 3 - a is greater than b\n");
}
else
{
printf("Line 3 - a is not greater than b\n");
}
/* Lets change value of a and b */
a = 5;
b = 20;
if (a <= b)
{
printf("Line 4 - a is either less than or equal to b\n");
}
if (b >= a)
{
printf("Line 5 - b is either greater than or equal to b\n");
}
}
Operators Precedence
Here operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Examples
Category
Operator
Associativity
Postfix
() [] -> . ++ - -
Left to right
Unary
Right to left
Multiplicative
*/%
Left to right
Additive
+-
Left to right
Shift
<< >>
Left to right
Relational
Left to right
Equality
== !=
Left to right
Bitwise AND
&
Left to right
Bitwise XOR
Left to right
Bitwise OR
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
Right to left
Comma
Left to right
#include<stdio.h>
main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d;
// ( 30 * 15 ) / 5
// (30 * 15 ) / 5
// 20 + (150/5)
Examples
Operator Description
Example
&&
(A && B) is
false.
||
Called Logical NOT Operator. Use to reverses the logical state of its
!(A && B) is
operand. If a condition is true then Logical NOT operator will make
true.
false.
#include<stdio.h>
main()
{
int a = 5;
int b = 20;
int c;
if (a && b)
{
printf("Line 1 - Condition is true\n");
}
if (a || b)
{
printf("Line 2 - Condition is true\n");
}
/* lets change the value of a and b */
a = 0;
b = 10;
if (a && b)
{
printf("Line 3 - Condition is true\n");
}
else
{
printf("Line 3 - Condition is not true\n");
}
if (!(a && b))
{
printf("Line 4 - Condition is true\n");
}
}
2.9.1 Decision Making
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Statement
Description
if statement
if...else statement
switch statement
if statement Example
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if (a < 20)
{
/* if condition is true then print the following */
printf("a is less than 20\n");
}
printf("value of a is : %d\n", a);
Description
while loop
for loop
do...while loop
while loop example int main() { /* local variable definition */ int a = 10; /* while loop
execution */ while (a < 20) { printf("value of a: %d\n", a); a++; } return 0; } "
v:shapes="Text_x0020_Box_x0020_24">
for loop example
int main() { /* for loop execution */ for (int a = 2; a < 10; a++) { printf("value of a: %d\n", a);
} return 0; } " v:shapes="Text_x0020_Box_x0020_26">
int main() { /* local variable definition */ int a = 10; /* do loop execution */ do
{ printf("value of a: %d\n", a); a = a + 1; } while (a < 20); return 0; } "
v:shapes="Text_x0020_Box_x0020_29">do...while loop example
2.9.3 Loop Control Statements:
Loop control statements change execution from its normal sequence.
Control Statement
Description
break statement
continue statement
goto statement
int main() { /* local variable definition */ int a = 10; /* while loop execution */ while (a < 20)
{ printf("value of a: %d\n", a); a++; if (a > 15) { /* terminate the loop using break statement
*/ break; } } return 0; } " v:shapes="Text_x0020_Box_x0020_31">break statement example
int main() { /* local variable definition */ int a = 10; /* do loop execution */ do { if (a == 15)
{ /* skip the iteration */ a = a + 1; continue; } printf("value of a: %d\n", a); a++; } while (a <
20); return 0; " v:shapes="Text_x0020_Box_x0020_33">continue statement example
2.10.1
Functions
A function is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional
functions. Functions can be logically division so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and
parameters.
A function definition provides the actual body of the function. The function definition
consists of a function header and a function body.
Return Type: A return_type is the data type of the value the function returns.
Function Name: The function name and the parameter list together constitute the
function signature.
Parameters: A parameter is like a placeholder. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
Function Body: The function body contains a collection of statements that define
what the function does.
Example:
#include<stdio.h>
/* function declaration */
int max(int num1, int num2);
int main()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
Math Functions
Although addition, subtraction, multiplication, and division are easily accomplished using C's
arithmetic operators, no such operators exist for raising a number to a power, finding the
square root of a number, or determining trigonometric values. To facilitate the calculation of
powers, square roots, trigonometric, logarithmic, and other mathematical calculations
frequently required in scientific and engineering programs, C provides standard
preprogrammed functions that can be included in a program.
See table for more details
Square root example
3.0 * sqrt (5 * 33 - 13. 71) / 5
Step
Result
3.0* sqrt(151.290000) / 5
3.0* 12.300000/ 5
36.900000/ 5
7.380000
2.10.2
Scope Rules
A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable cannot be accessed. There are three places where variables
can be declared in C programming language:
1. Inside a function or a block which is called local variables,
2. Outside of all functions which is called global variables.
3. In the definition of function parameters which is called formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables. They can be
used only by statements that are inside that function or block of code. Local variables are not
known to functions outside their own. Following is the example using local variables.
Global Variables
Global variables are defined outside of a function, usually on top of the program. The global
variables will hold their value throughout the lifetime of your program and they can be
accessed inside any of the functions defined for the program.
Formal Parameters
Formal parameters, are treated as local variables within that function and they will take
preference over the global variable.
2.10.3
Arrays
An array is used to store a collection of data, but it is often more useful to think of an array as
a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by
an index.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater
than zero and type can be any valid C data type. For example, to declare a 10-element array
called balance of type double, use this statement:
double balance[10];
Now, balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize array in C either one by one or using a single statement as follows:
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that
we declare for the array between square brackets [ ]. Following is an example to assign a
single element of the array:
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write:
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th
index will be 5th ie. last element because all arrays have 0 as the index of their first element
which is also called base index. Following is the pictorial representation of the same array we
discussed above:
int main()
{
return 0;
}
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
2.10.4
Pointers
A pointer is a variable, whose value is the address of another variable, i.e., direct address of
the memory location. Like any variable or constant, you must declare a pointer before you
can use it to store any variable address. The general form of a pointer variable declaration is:
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name
of the pointer variable. The asterisk * you used to declare a pointer is the same asterisk that
you use for multiplication. However, in this statement the asterisk is being used to designate a
variable as a pointer. Following are the valid pointer declaration:
int
/* pointer to a float */
char *ch
/* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address. The
only difference between pointers of different data types is the data type of the variable or
constant that the pointer points to.
How to use Pointers?
There are few important operations, which we will do with the help of pointers very
frequently. (a) we define a pointer variable (b) assign the address of a variable to a pointer
and (c) finally access the value at the address available in the pointer variable. This is done by
using unary operator * that returns the value of the variable located at the address specified
by its operand. Following example makes use of these operations:
#include <stdio.h>
int main()
{
int var = 20; /* actual variable declaration */
int *ip;
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
2.10.5 Strings
The string in C programming language is actually a one-dimensional array of characters
which is terminated by a null character '\0'. Thus a null-terminated string contains the
characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To
hold the null character at the end of the array, the size of the character array containing the
string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as
follows:
char greeting[] = "Hello";
Following is the memory presentation of above-defined string in C/C++:
The C compiler automatically places the '\0' at the end of the string when it initializes the
array. Let us try to print above mentioned string:
#include <stdio.h>
int main()
{
char greeting[6] = { 'H', 'e', 'l', 'l', 'o', '\0' };
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Greeting message: Hello