You are on page 1of 37

Problem Solving Using C Programming

ECE/ECM
Arrays and Multi Dimensional

U n i t - 11
Multidimensional
Arrays
C++ also allows an array to have more than one dimension.

For example, a two-dimensional array consists of a certain number of rows and


columns:

const int NUMROWS = 3;


const int NUMCOLS = 7;
int Array[NUMROWS][NUMCOLS]; 0 1 2 3 4 5 6
0 4 18 9 3 -4 6 0
1 12 45 74 15 0 98 0
2 84 87 75 67 81 85 79

Array[2][5] 3rd value in 6th column


Array[0][4] 1st value in 5th column

The declaration must specify the number of rows and the number of columns, and
both must be constants.
Processing a 2-D
Array
A one-dimensional array is usually processed via a for loop. Similarly, a two-
dimensional array may be processed with a nested for loop:

for (int Row = 0; Row < NUMROWS; Row++) {


for (int Col = 0; Col < NUMCOLS; Col++) {
Array[Row][Col] = 0;
}
}

Each pass through the inner for loop will initialize all the elements of the current row to 0.

The outer for loop drives the inner loop to process each of the array's rows.
Initializing in
Declarations
int Array1[2][3] = { {1, 2, 3} , {4, 5, 6} };
int Array2[2][3] = { 1, 2, 3, 4, 5 };
int Array3[2][3] = { {1, 2} , {4 } };

If we printed these arrays by rows, we would find the following


initializations
had taken place:
for (int row = 0; row < 2; row++) {
Rows of Array1: for (int col = 0; col < 3; col++) {
1 2 3
cout << setw(3)
4 5 6
<< Array1[row][col];
Rows of Array2: }
1 2 3
cout << endl;
4 5 0
}
Rows of Array3:
1 2 0
4 0 0
Higher-
Dimensional
Arrays
An array can be declared with multiple dimensions.

2 Dimensional 3 Dimensional

double Coord[100][100][100];

Multiple dimensions get difficult to visualize graphically.


2-D Arrays as
Parameters
When passing a two-dimensional array as a parameter, the base address is passed,
as is the case with one-dimensional arrays.

But now the number of columns in the array parameter must be specified. This is
because arrays are stored in row-major order, and the number of columns must be
known in order to calculate the location at which each row begins in memory:

address of element (r, c) = base address of array


+ r*(number of elements in a row)*(size of an element)
+ c*(size of an element)

void Initialize(int TwoD[][NUMCOLS], const int NUMROWS) {


for (int i = 0; i < NUMROWS; i++) {
for (int j = 0; j < NUMCOLS; j++)
TwoD[i][j] = -1;
}
}
Data
Types
data type: a collection of values and the definition of one or more operations that
can be performed on those values

C++ includes a variety of built-in or base data types:


short, int, long, float, double, char, etc.
The values are ordered and atomic.

C++ supports several mechanisms for aggregate data types: arrays, structures, classes.
These allow complex combinations of other types as single entities.

C++ also supports other mechanisms that allow programmers to define their own
custom data types: enum types and typedefs.
Enumerate
dAn enumerated
Typestype is defined by giving a name for the type and then giving a list of
labels, which are the only values that a variable of that type is allowed to have.
Enumerated types allow the creation of specialized types that support the use of meaningful
labels within a program. They promote code readability with very little overhead in
memory or runtime cost.
enum Month {JAN, FEB, MAR, APR, MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC};
enum Season {WINTER, SPRING, SUMMER, FALL};
enum Hemisphere {NORTH, SOUTH, EAST, WEST};
Month Mon;
Season Period;
Hemisphere Region;
. . .
if (Mon == JAN && Hemisphere == NORTH)
Period = WINTER;

An enumerated type is allowed to have up to 256 values and a variable of an enumerated


type will occupy one byte of memory.
It is an error for the same label to be listed as a value for two different enumerated types.
Designing with Enumerated
Types
Enumerated types provide a mechanism for the abstraction of real world entities.

Enumerated type variables do not contain the character string of the value. The internal
representation uses integer values; it is bad practice to rely on those values.

Since the labels are logically constant values it is common to express them using all
capital letters, just as for named constants.

Enumerated type values cannot be read or (usefully) written directly.

Enumerated type variables and values can be used in relational comparisons, in


assignments and in switch statements as selectors and case labels.

Enumerated type variables can be passed as parameters and used as the return value of a
function.

Good use of enumerated data types make the program more readable by providing a
way to incorporate meaningful labels (thus easier to debug) and they help in self-
documenting the program.
s im p l e t y p e s

in t e g r a l f lo a t in g

bool char s h o irt in t lo n g enum f lo a t d o u b le lo n g d o u b le

• enum
• a user-defined data type
• formed by listing identifiers
INTRODUCTION

1. COURSE OBJECTIVES:
The objectives of this course are:
1.       Provide exposure to problem solving through C programming
2.       Explore the structure and syntax of C programming language
3.       illustrate the applications of data types, operators, arrays, and control flow
statements in problem solving.
a.       Demonstrate the usage of procedure-oriented programming.
b.       Provide insight into concepts like pointers, structures, and unions

14
INTRODUCTION

 C is a general purpose language which is very closely associated


with UNIX for which it was developed in Bell Laboratories.
 Most of the programs of UNIX are written and run with the help of 'C'.
 Many of the important ideas of 'c' stem are from BCPL by Martin Richards.
 In 1972, Dennies Ritchie at Bell Laboratories wrote C Language which caused a
revolution in computing world .
 From beginning C was intended to be useful for busy programmers to get things
done easily because C is powerful,dominant and supple language

15
WHY NAME 'C' WAS GIVEN TO THIS
LANGUAGE?

Many of the ideas of C language were derived and taken from 'B' language.
BCPL and CPL are previous versions of 'B' language.
As many features came from B it was named as 'C

16
FEATURES OF C
o C is a structured programming language
o C supports functions that enables easy maintainability of code, by

1.breaking large file into smaller modules


o Comments in C provides easy readability
o C is a powerful language.
o C programs built from
• Variable and type declarations
• Functions
• Statements
• Expressions
17
ALGORITHMS AND FLOWCHARTS
A typical programming task can be divided into two phases:
Problem solving phase
produce an ordered sequence of steps that describe solution of problem
this sequence of steps is called an algorithm

Implementation phase
implement the program in some programming language

18
STEPS IN PROBLEM SOLVING
First produce a general algorithm (one can use pseudo code)

Refine the algorithm successively to get step by step detailed algorithm


that is very close to a computer language.

Pseudo code is an artificial and informal language that helps


programmers develop algorithms. Pseudo code is very similar to
everyday English.

19
PSEUDOCODE & ALGORITHM
o Example 1: Write an algorithm to determine a student’s final grade and indicate whether it is
passing or failing. The final grade is calculated as the average of four marks
Pseudo code:
Input a set of 4 marks

Calculate their average by summing and dividing by 4

if average is below 50 Print “FAIL”


Else
Print “PASS”

20
DETAILED ALGORITHM

1.Step 1: Input M1,M2,M3,M4


2.Step 2:
GRADE (M1+M2+M3+M4)/4
3.Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif

21
THE FLOWCHART
 (Dictionary) A schematic representation of a sequence of operations, as in a manufacturing
process or computer program.

 (Technical) A graphical representation of the sequence of operations in an information system or


program. Information system flowcharts show how data flows from source documents through the
computer to final distribution to users. Program flowcharts show the sequence of instructions in a
single program or subroutine. Different symbols are used to draw each type of flowchart

22
PSEUDOCODE & ALGORITHM
1.A Flowchart
⚫ shows logic of an algorithm

⚫ emphasizes individual steps and their interconnections

⚫ e.g. control flow from one action to the next

23
FLOWCHART SYMBOLS

Basic
Name Symbol Use in Flowchart

Oval Denotes the beginning or end of the program

Parallelogram Denotes an input operation

Rectangle Denotes a process to be carried out


e.g. addition, subtraction, division etc.

Diamond Denotes a decision (or branch) to be made. The


program should continue along one of two
routes. (e.g. IF/THEN/ELSE)

Hybrid Denotes an output operation

Flow line Denotes the direction of logic flow in the program


STRUCTURE OF “C” PROGRAMS

 Before going and reading the structure of C programs we need to have


a basic knowledge of the following:

1. C's Character Set

2. C's Keywords

3. The General Structure of a 'C' Program

4. How To End A Statement

5. Free Format Language

6. Header Files & Library Functions


25
C'S CHARACTER SET
1. C does not use every character set and key found on
2.modern computers . The only characters that C - Language uses for its programs are
as follows:
 A-Z all alphabets
 a-z all alphabets
 0-9
 # % & ! _ {} [] () $$$$ &&&& |
 space . , : ; ' $ "
1.+ - / * =

26
THE KEYWORDS

 "Keywords" are words that have special meaning to the C compiler.

 Their meaning cannot be changed at any instance.

 Serve as basic building blocks for program statements.

 All keywords are written in only lowercase.

27
Basic Structure Of “C” Programs

#include<stdio.h>
Header Files
#include<conio.h>
Entry Point Of
Program
void main()
Indicates Starting
{ of Program

-- other statements
}
HEADER FILES

 The files that are specified in the include section is called as Header File.

 These are precompiled files that has some functions defined in them.

 We can call those functions in our program by supplying parameters.

 Header file is given an extension .h .

 C Source file is given an extension .c .

29
MAIN FUNCTION

 This is the “Entry Point” of a program.

 When a file is executed, the start point is the main function.

 From main function the flow goes as per the programmers choice.

 There may or may not be other functions written by user in a program.

 Main function is compulsory for any C program.

30
RUNNING A ‘C’ PROGRAM

 Type a program.

 Save it.

 Compile the program – This will generate an .exe file (executable)

 Run the program (Actually the exe created out of compilation will run and not
the .c file)
 In different compiler we have different option for compiling and running.

31
RUNNING A ‘C’ PROGRAM

 Type a program.

 Save it.

 Compile the program – This will generate an .exe file (executable)

 Run the program (Actually the exe created out of compilation will run and not
the .c file)
 In different compiler we have different option for compiling and running.

32
“C” language TOKENS
 The smallest individual units in a C program are known
as tokens. In a C source program, the basic element
recognized by the compiler is the "token." A token is source-
program text that the compiler does not break down into
component elements.
 C has 6 different types of tokens viz.
1. Keywords [e.g. float, int, while]
2.Identifiers [e.g. main, amount] 3.
Constants [e.g. -25.6, 100]
4. Strings [e.g. “SMIT”, “year”] Strin
gs

5. Special Symbols [e.g. {, }, [, ]


]
6.C Operators
 - programs[e.g.
are +, -, *] using these tokens and the general
written
syntax.
Keywords in Ansi “C”

auto double register switch


break else return typedef
case enum short union
char etern signed unsigned
const float sizeof void
continue for static volatile
default goto struct while
do if int long
The Identifiers
 They are programmer-chosen names to represent parts of the
program: variables, functions, etc.
 Cannot use C keywords as identifiers
 Must begin with alpha character or _, followed by alpha,
numeric, or _
 Upper- and lower-case characters are important (case-
sensitive)
 Must consist of only letters, digits or underscore ( _ ).
 Only first 31 characters are significant.
 Must NOT contain spaces ( ).
Icons
Architecture Commerce Legal Studies Arts & Humanities

Performing Arts Management Studies Science & Tech Engineering

You might also like