SlideShare a Scribd company logo
Introduction to Computer
Programming
By:
Dr. Abhishek Singh
Outline of Topics
• Hardware/Software interface
– Layers of the Machine
– Kinds of Software
• Computer Languages
• Syntax, Semantics, Grammars
• What happens to your program?
– Compilation, Linking, Execution
– Program errors
• Compilation vs. Interpretation etc.
Software Categories
• System SW
–Programs written for computer systems
• Compilers, operating systems, …
• Application SW
–Programs written for computer users
• Word-processors, spreadsheets, & other
application packages
A Layered View of the Computer
Machine with all its
hardware
System Software
Compilers,
Interpreters,Preprocessors, etc.
Operating System, Device Drivers
Application Programs
Word-Processors, Spreadsheets,
Database Software, IDEs,
etc…
Operating System (OS)
 Provides several essential services:
– Loading & running application programs
– Allocating memory & processor time
– Providing input & output facilities
– Managing files of information
Programs
• Programs are written in programming languages
– PL = programming language
– Pieces of the same program can be written in
different PLs
• Languages closer to the machine can be more efficient
• As long as they agree on how to communicate
• A PL is
– A special purpose and limited language
– A set of rules and symbols used to construct a
computer program
– A language used to interact with the computer
Computer Languages
– Machine Language
• Uses binary code
• Machine-dependent
• Not portable
• Assembly Language
– Uses mnemonics
– Machine-dependent
– Not usually portable
• High-Level Language (HLL)
– Uses English-like language
– Machine independent
– Portable (but must be compiled for different platforms)
– Examples: Pascal, C, C++, Java, Fortran, . . .
Machine Language
• The representation of a computer program which is
actually read and understood by the computer.
– A program in machine code consists of a sequence of machine
instructions.
• Instructions:
– Machine instructions are in binary code
– Instructions specify operations and memory cells involved in the
operation
Example: Operation Address
0010 0000 0000 0100
0100 0000 0000 0101
0011 0000 0000 0110
Assembly Language
• A symbolic representation of the machine language of a specific processor.
• Is converted to machine code by an assembler.
• Usually, each line of assembly code produces one machine instruction (One-to-one
correspondence).
• Programming in assembly language is slow and error-prone but is more efficient in terms of
hardware performance.
• Mnemonic representation of the instructions and data
• Example:
Load Price
Add Tax
Store Cost
Sample
Assembly
code for
Printing
Hello World
High-level language
• A programming language which use statements
consisting of English-like keywords such as "FOR",
"PRINT" or “IF“, ... etc.
• Each statement corresponds to several machine
language instructions (one-to-many correspondence).
• Much easier to program than in assembly language.
• Data are referenced using descriptive names
• Operations can be described using familiar symbols
• Example:
Cost := Price + Tax
Syntax & Semantics
• Syntax:
– The structure of strings in some language. A
language's syntax is described by a grammar.
– Examples:
• Binary number
<binary_number> = <bit> | <bit> <binary_number>
<bit> = 0 | 1
• Identifier
<identifier> = <letter> {<letter> | <digit> }
<letter> = a | b | . . . | z
<digit = 0 | 1 | . . . | 9
• Semantics:
– The meaning of the language
Syntax & Grammars
• Syntax descriptions for a PL are
themselves written in a formal language.
– E.g. Backus-Naur Form (BNF)
• The formal language is not a PL but it can
be implemented by a compiler to enforce
grammar restrictions.
• Some PLs look more like grammar
descriptions than like instructions.
Compilers & Programs
• Compiler
– A program that converts another program from
some source language (or high-level
programming language / HLL) to machine
language (object code).
– Some compilers output assembly language
which is then converted to machine language by
a separate assembler.
– Is distinguished from an assembler by the fact
that each input statement, in general,
correspond to more than one machine
instruction.
Compilation into Assembly L
Compiler
Assembler
Source
Program
Assembly
Language
Assembly
Language
Machine
Language
Compilers & Programs
• Source program
– The form in which a computer program,
written in some formal programming
language, is written by the programmer.
– Can be compiled automatically into object
code or machine code or executed by an
interpreter.
– Pascal source programs have extension
‘.pas’
Compilers & Programs
• Object program
– Output from the compiler
– Equivalent machine language translation of the
source program
– Files usually have extension ‘.obj’
• Executable program
– Output from linker/loader
– Machine language program linked with necessary
libraries & other files
– Files usually have extension ‘.exe’
What is a Linker?
• A program that pulls other programs together so
that they can run.
• Most programs are very large and consist of
several modules.
• Even small programs use existing code provided
by the programming environment called libraries.
• The linker pulls everything together, makes sure
that references to other parts of the program
(code) are resolved.
Running Programs
Memory
Input Data
Program Output
Machine language
program
(executable file)
Data entered
during execution
Computed results
C P U
• Steps that the computer goes through to run a
program:
Program Execution
• Steps taken by the CPU to run a program
(instructions are in machine language):
1. Fetch an instruction
2. Decode (interpret) the instruction
3. Retrieve data, if needed
4. Execute (perform) actual processing
5. Store the results, if needed
Program Errors
• Syntax Errors:
– Errors in grammar of the language
• Runtime error:
– When there are no syntax errors, but the program
can’t complete execution
• Divide by zero
• Invalid input data
• Logical errors:
– The program completes execution, but delivers
incorrect results
– Incorrect usage of parentheses
Compilation
Compiler
Target Program
Source
Program
Target
Program
Input Output
• Compiler translates source into target (a machine
language program)
• Compiler goes away at execution time
• Compiler is itself a machine language program,
presumably created by compiling some other high-level
program
• Machine language, when written in a format understood
by the OS is object code
Interpretation
Interpreter
Source
Program
Input
Output
• The interpreter stays around during execution
• It reads and executes statements one at a time
Compilation vs. Interpretation
• Compilation:
– Syntax errors caught before running the program
– Better performance
– Decisions made once, at compile time
• Interpretation:
– Better diagnostics (error messages)
– More flexibility
– Supports late binding (delaying decisions about
program implementation until runtime)
• Can better cope with PLs where type and size of
variables depend on input
– Supports creation/modification of program code on
the fly (e.g. Lisp, Prolog)
Mixture of C & I
Translator
Source
Program
Intermediate
Program
VM
Intermediate
Program
Input
Output
• Many programming languages implement this
• Interpreter implements a Virtual Machine (VM).
JAVA
Compiler
Interpreter
Java
bytecode
ML
For flexibility: Just In Time (JIT) compiler translates
bytecode into ML just before execution
For portability:
Introduction to C programming
Introduction to C programming
Introduction to C programming
Compilation Process
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Operator Precedence Chart
Operator Precedence Chart
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Introduction to C for Btech 1st year.ppt
Sample questions
1. Which is true about conditional compilation?
a)It is taken care by the compiler.
b)It is setting the compiler option conditionally.
c)It is compiling a program based on a condition
d)It is taken care of by the pre-processor.
2. What is the minimum number of temporary variables required to swap the values of two
variables?
a)1 b) 2 c) 3 d) 0
3. C is a
a.High level language
b.Low level language
c.High level language with some low level features
d.Low level language with some high level features
4.If integer needs two bytes of starage, then max value of an unsigned integer is:
5.What will be happen with the following code fragment:
print(“%d”, printf(“TIM”));
Basics of ‘C’
By:
Dr. Abhishek Singh
General Aspect of ‘C’
• Originally developed in the 1970s, by Dennis Ritchie at Bell
Telephone Laboratories, Inc.
• High level, general–purpose, structured programming
language.
• Instructions of C consists of terms that are very closely same
to algebraic expressions, consisting of certain English
keywords such as if, else, for ,do and while
• C contains certain additional features that allows it to be used
at a lower level , acting as bridge between machine language
and the high level languages. This allows C to be used for
system programming as well as for applications programming
Structured Programming
•Structured Programming is a type of programming that generally converts large
or complex programs into more manageable and small pieces of code.
•These small pieces of codes are usually known as functions or modules or sub-
programs of large complex programs.
•It is known as modular programming and minimizes the chances of function
affecting another.
•Example: Click me
The Character set of ‘C’
• C language consist of some characters set, numbers and
some special symbols. The character set of C consist of all
the alphabets of English language.
Alphabets a to z, A to Z
Numeric 0,1 to 9
Special Symbols {,},[,],?,+,-,*,/,%,!,;,and more
• The words formed from the character set are building blocks
of C and are sometimes known as tokens.
• Tokens represent the individual entity of language. The
following different types of token are used in C
1) Identifiers 2)Keywords 3)Constants
4) Operators 5)Punctuation Symbols
Identifiers
• A 'C' program consist of two types of elements , user defined
and system defined. Idetifiers is nothing but a name given to
these elements.
• An identifier is a word used by a programmer to name a
variable , function, or label.
• identifiers consist of letters and digits, in any order, except that
the first charecter or lable.
• Identifiers consist of letters and digits if any order,except that
the first charecter must be letter.
• Both Upper and lowercase letters can be used
Keywords
• Keywords are nothing but
system defined identifiers.
• Keywords are reserved words
of the language.
• They have specific meaning in
the language and cannot be
used by the programmer as
variable or constant names
• C is case senitive, it means
these must be used as it is
• 32 Keywords in C Programming
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Variables
• A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
• The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive. There are following basic variable
types −
Type Description
• char Typically a single octet(one byte). This is an integer type.
• int The most natural size of integer for the machine.
• float A single-precision floating point value.
• double A double-precision floating point value.
• void Represents the absence of type.
Constants
• A constant is a value or an identifier whose value cannot be altered
in a program. For example: 1, 2.5,
• As mentioned, an identifier also can be defined as a constant. eg.
const double PI = 3.14
• Here, PI is a constant. Basically what it means is that, PI and 3.14 is
same for this program.
Integer constants
• A integer constant is a numeric constant (associated with number)
without any fractional or exponential part. There are three types of
integer constants in C programming:
• decimal constant(base 10)
• octal constant(base 8)
• hexadecimal constant(base 16)
Constants
Floating-point constants
• A floating point constant is a numeric constant that has either
a fractional form or an exponent form. For example:
2.0,0.0000234,-0.22E-5
Character constants
• A character constant is a constant which uses single quotation
around characters. For example: 'a', 'l', 'm', 'F'
String constants
• String constants are the constants which are enclosed in a pair
of double-quote marks. For example: "good" ,"x","Earth is
roundn"
Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has special
meaning in C programming. For example: newline(enter), tab, question mark etc. In
order to use these characters, escape sequence is used.
• For example: n is used for newline. The backslash (  ) causes "escape" from the
normal way the characters are interpreted by the compiler.Escape
Sequences Character
• b Backspace
• f Form feed
• n Newline
• r Return
• t Horizontal tab
• v Vertical tab
•  Backslash
• ' Single quotation mark
• " Double quotation mark
• ? Question mark
• 0 Null character
We will see and evaluate
these escape sequences
throughout the syllabus
Operators in C:An operator is a symbol which operates on a value or a
variable. For example: + is an operator to perform addition.
C programming has wide range of operators to perform various
operations. For better understanding of operators, these
operators can be classified as:
• Arithmetic Operators
• Increment and Decrement Operators
• Assignment Operators
• Relational Operators
• Logical Operators
• Conditional Operators
• Bitwise Operators
• Special Operators
Arithmetic Operator
• Operator Meaning of Operator
• + addition or unary plus
• - subtraction or unary minus
• * multiplication
• / division
• % remainder after
division( modulo division)
Increment and Decrement Operators
1. C programming has two operators increment ++
and decrement -- to change the value of an
operand (constant or variable) by 1.
2. Increment ++ increases the value by 1 whereas
decrement -- decreases the value by 1.
3. These two operators are unary operators,
meaning they only operate on a single operand.
eg. int a=10, b=100
++a = 11
--b = 99
C Assignment Operators
• An assignment operator is used for assigning a value
to a variable. The most common assignment operator
is =
• Operator Example Same as
• = a = b a = b
• += a += b a = a+b
• -= a -= b a = a-b
• *= a *= b a = a*b
• /= a /= b a = a/b
• %= a %= b a = a%b
C Relational Operators
• A relational operator checks the relationship between two
operands. If the relation is true, it returns 1; if the relation is
false, it returns value 0.
• Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
• == Equal to 5 == 3 returns 0
• > Greater than 5 > 3 returns 1
• < Less than 5 < 3 returns 0
• != Not equal to 5 != 3 returns 1
• >= Greater than or equal to 5 >= 3 returns 1
• <= Less than or equal to 5 <= 3 return 0
The First C program
• The statements in a program must appear in the
same order in which we wish to execute them
unless of course the problem demands a deliberate
‘jump’ or transfer of control to a statement, which
may be out of sequence.
• Blank spaces must be inserted between two words.
• All statements are inserted in small letters.
• C has no specific rules for the position at which a
statement will be written. That’s why it is often
called a free-form language.
The First C program
// Calculation of Simple Interest
/*
Calculation of Simple Interest
*/
#include<stdio.h>
void main()
{
int p, n;
float r, si;
p = 1000;
n = 3;
r = 8.5;
//formula for simple interest
si = p*n*r/100;
printf("Simple Interest is: n%f", si);
}
C preprocessors (Click to know more)
https://www.geeksforgeeks.org/cc-preprocessors/
Receiving Inputs
// Calculation of Simple Interest with user inputs
#include<stdio.h>
void main()
{
int p, n;
float r, si;
printf(“Enter the Value of p, n, r:n”);
scanf(“%d %d %f”, &p, &n, &r);
// p = 1000;
//n = 3;
//r = 8.5;
//formula for simple interest
si = p*n*r/100;
printf("Simple Interest is: n%f", si);
}
Type declarations
instructions
Arithmetic
Instructions
Objectives of these slides:
Objectives of these slides:
 to introduce the main kinds of C contr
to introduce the main kinds of C contr
ol flow
ol flow
Control
Statements
Programming
Programming In C
In C
Control Structures
Control Structures
 There may be situations where the
There may be situations where the
programmer requires to alter normal flow of
programmer requires to alter normal flow of
execution of program or to perform the
execution of program or to perform the
same operation a no. of times.
same operation a no. of times.
 Various control statements supported by c
Various control statements supported by c
are-
are-
 Decision control statements
Decision control statements
 Loop control statements
Loop control statements
Decision Control Statements
Decision Control Statements
 Decision control statements alter the normal
Decision control statements alter the normal
sequential execution of the statements of the
sequential execution of the statements of the
program depending upon the test condition to be
program depending upon the test condition to be
carried out at a particular point in program.
carried out at a particular point in program.
 Decision control statements supported by c are:-
Decision control statements supported by c are:-
 if statement
if statement
 if-else statement
if-else statement
 Else if Ladder
Else if Ladder
 Nested If
Nested If
 switch statement
switch statement
Decision Control Statements
Decision Control Statements
 if statement
if statement
 Most simple and powerful decision control statement.
Most simple and powerful decision control statement.
 It executes a statement or block of statements only if the
It executes a statement or block of statements only if the
condition is true.
condition is true.
 Syntax: if (condition)
Syntax: if (condition) if (condition)
if (condition)
{
{ OR
OR {
{
statement (s);
statement (s); statement 1;
statement 1;
}
} statement 2;
statement 2;
Next statement;
Next statement; }
}
statement 3;
statement 3;
 In above syntax : if condition is true only then the
In above syntax : if condition is true only then the
statements within the block are executed otherwise next
statements within the block are executed otherwise next
statement in sequence is executed.
statement in sequence is executed.
 Flowchart
Flowchart
Condition
STOP
False
True
Block of if
Next statement
/* Program to check whether a no. is even */
# include<stdio.h>
# include<conio.h>
void main()
{
int num;
clrscr();
printf(“enter the number”);
scanf(“%d”,&num)
if(num%2==0)
{
printf(“n Number is even”);
}
printf(“ End of program”);
getch();
}
if – else statement
if – else statement
 In case of if statement, the block of statements is executed only when
In case of if statement, the block of statements is executed only when
the condition is true otherwise the control is transferred to the next
the condition is true otherwise the control is transferred to the next
statement following if block.
statement following if block.
 But if specific statements are to be executed in both cases (either
But if specific statements are to be executed in both cases (either
condition is true or false) then if – else statement is used.
condition is true or false) then if – else statement is used.
 In if – else statement a block of statements are executed if the condition
In if – else statement a block of statements are executed if the condition
is true but a different block of statements is executed when the condition
is true but a different block of statements is executed when the condition
is false.
is false.
 Syntax: if (condition)
Syntax: if (condition)
{
{
statement 1;
statement 1;
statement 2;
statement 2;
}
}
else
else
{
{
statement 3;
statement 3;
}
}
Test
Condition
Block of if Block of else
Next statement
STOP
False
True
Exercise: WAP to check whether a given no. is even or
Exercise: WAP to check whether a given no. is even or
odd?
odd?
Nested if – else statement
Nested if – else statement
 When an entire if-else is enclosed within the body of if
When an entire if-else is enclosed within the body of if
statement or/and in the body of else statement, it is known
statement or/and in the body of else statement, it is known
as nested if-else statement.
as nested if-else statement.
 The ways of representing nested if –else are-
The ways of representing nested if –else are-
if (condition1)
{
if (condition2)
statement 1;
else
statement 2;
}
else
statement 3;
if (condition1)
{
if (condition2)
statement 1;
else
statement 2;
}
else
{
if (condition 3)
statement 3;
else
statement 4;
}
if (condition1)
statement 1;
else
{
if (condition2)
statement 2;
else
statement 3;
}
If- else- if ladder
If- else- if ladder
 In a program involving multiple conditions, the nested if else
In a program involving multiple conditions, the nested if else
statements makes the program very difficult to write and
statements makes the program very difficult to write and
understand if nested more deeply.
understand if nested more deeply.
 For this ,we use if-else-if ladder.
For this ,we use if-else-if ladder.
 Syntax: if (condition1)
Syntax: if (condition1)
statement1;
statement1;
else if(condition2)
else if(condition2)
statement2;
statement2;
else if(condition3)
else if(condition3)
statement 3;
statement 3;
else
else
default statement;
default statement;
condition 1
condition 2
condition 3
Statement 1
Statement 2
Statement 3
Default statement
Next statement
false
true
false
true
false
true
Switch statement
Switch statement
 Switch is a multi-way decision making statement which selects
Switch is a multi-way decision making statement which selects
one of the several alternatives based on the value of single
one of the several alternatives based on the value of single
variable or expression.
variable or expression.
 It is mainly used to replace multiple if-else-if statement.
It is mainly used to replace multiple if-else-if statement.
 The if-else-if statement causes performance degradation as
The if-else-if statement causes performance degradation as
several conditions need to be evaluated before a particular
several conditions need to be evaluated before a particular
condition is satisfied.
condition is satisfied.
 Syntax:
Syntax: switch (expression)
switch (expression)
{
{
case constant1 : statement (s); [break;]
case constant1 : statement (s); [break;]
case constant2 : statement (s); [break;]
case constant2 : statement (s); [break;]
……………………………………
…………………………………….
.
default: statement (s)
default: statement (s)
}
}
Break statement
Break statement
 Break statement terminates the execution of
Break statement terminates the execution of
the loop in which it is defined.
the loop in which it is defined.
 The control is transferred immediately to
The control is transferred immediately to
the next executable statement after the loop.
the next executable statement after the loop.
 It is mostly used to exit early from the loop
It is mostly used to exit early from the loop
by skipping the remaining statements of
by skipping the remaining statements of
loop or switch control structures.
loop or switch control structures.
 Syntax: break;
Syntax: break;
Looping Structures
Looping Structures
 When we want to repeat a group of statements a no.
When we want to repeat a group of statements a no.
of times, loops are used.
of times, loops are used.
 These loops are executed until the condition is true.
These loops are executed until the condition is true.
 When condition becomes false, control terminates
When condition becomes false, control terminates
the loop and moves on to next instruction
the loop and moves on to next instruction
immediately after the loop.
immediately after the loop.
 Various looping structures are-
Various looping structures are-
 while
while
 do – while
do – while
 for
for
LOOPING STATEMENTS
LOOPING STATEMENTS
 Loop is divided into two parts:
Loop is divided into two parts:
 Body of the loop
Body of the loop
 Control of loop
Control of loop
 Mainly control of loop is divided into two
Mainly control of loop is divided into two
parts:
parts:
 Entry Control loop (while, for)
Entry Control loop (while, for)
 Exit Control loop (do-while)
Exit Control loop (do-while)
while statement
while statement
 While loop is used to execute set of statements as long as
While loop is used to execute set of statements as long as
condition evaluates to true.
condition evaluates to true.
 It is mostly used in those cases where the programmer
It is mostly used in those cases where the programmer
doesn’t know in advance how many times the loop will be
doesn’t know in advance how many times the loop will be
executed.
executed.
 Syntax: while (condition)
Syntax: while (condition)
{
{
Statement 1 ;
Statement 1 ;
Statement 2 ;
Statement 2 ;
}
}
condition statement
Statement after while loop
true
do- while
do- while
 do-while is similar to while except that its test
do-while is similar to while except that its test
condition is evaluated at the end of the loop instead
condition is evaluated at the end of the loop instead
at the beginning as in case of while loop.
at the beginning as in case of while loop.
 So, in do-while the body of the loop always executes
So, in do-while the body of the loop always executes
at least once even if the test condition evaluates to
at least once even if the test condition evaluates to
false during the first iteration.
false during the first iteration.
 Syntax: do
Syntax: do
{
{
statement 1;
statement 1;
statement 2;
statement 2;
}while (condition);
}while (condition);
statement;
statement;
Body of loop
Test condition
Next statement
true
false
for loop
for loop
 Most versatile and popular of three loop structures.
Most versatile and popular of three loop structures.
 Is used in those situations when a programmer
Is used in those situations when a programmer
knows in advance the number of times a statement
knows in advance the number of times a statement
or block will be executed.
or block will be executed.
 It contains loop control elements all at one place
It contains loop control elements all at one place
while in other loops they are scattered over the
while in other loops they are scattered over the
program and are difficult to understand.
program and are difficult to understand.
 Syntax:-
Syntax:-
for (initialization; condition; increment/decrement)
for (initialization; condition; increment/decrement)
{
{
Statement( s);
Statement( s);
}
}
The
The for
for is a sort of
is a sort of while
while
for (expr1; expr2; expr3)
for (expr1; expr2; expr3)
statement;
statement;
is equivalent to:
is equivalent to:
expr1;
expr1;
while (expr2) {
while (expr2) {
statement;
statement;
expr3;
expr3;
}
}
Various other ways of writing same for loops
Various other ways of writing same for loops
i = 1
i = 1
for (; i<=15;i ++)
for (; i<=15;i ++)
{
{
……
……..
..
}
}
for (i=1; ;i++)
{
………
if (i>15)
break;
……
}
for (i=1;i<=15;)
{
………….
i++;
}
Some Examples
Some Examples
for(i = 7; i <=77; i += 7)
for(i = 7; i <=77; i += 7)
statement;
statement;
for(i = 20; i >= 2; i -= 2)
for(i = 20; i >= 2; i -= 2)
statement;
statement;
for(j = 10; j > 20; j++)
for(j = 10; j > 20; j++)
statement;
statement;
for(j = 10; j > 0; j--)
for(j = 10; j > 0; j--)
statement;
statement;
Incrementing
Incrementing
 Add 1 to c by writing:
Add 1 to c by writing:
c = c + 1;
c = c + 1;
Also:
Also: c += 1;
c += 1;
Also:
Also: c++;
c++;
Also:
Also: ++c;
++c;
Incrementing and Decrementing
Incrementing and Decrementing
/* Preincrementing and
/* Preincrementing and po
postincrementing */
stincrementing */
#include <stdio.h>
#include <stdio.h>
int main()
int main()
{
{
int c;
int c;
c = 5;
c = 5;
printf("%dn", c);
printf("%dn", c);
printf("%dn",c++);
printf("%dn",c++); /*post
/*post increment*/
increment*/
printf("%dnn", c);
printf("%dnn", c);
:
:
continued
c = 5;
c = 5;
printf("%dn", c);
printf("%dn", c);
printf("%dn",++c); /*pre-increme
printf("%dn",++c); /*pre-increme
nt*/
nt*/
printf("%dn", c);
printf("%dn", c);
return 0;
return 0;
}
}
Output:
Output:
5
5
5
5
6
6
5
5
6
6
6
6
Decrementing
Decrementing
 Take 1 from c by writing:
Take 1 from c by writing:
c = c - 1;
c = c - 1;
Also:
Also: c -= 1;
c -= 1;
Also:
Also: c--;
c--;
Also:
Also: --c;
--c;
Continue statement
Continue statement
 Like break ,continue statement also skips the remaining
Like break ,continue statement also skips the remaining
statements of the body of the loop where it is defined but
statements of the body of the loop where it is defined but
instead of terminating the loop, the control is transferred to
instead of terminating the loop, the control is transferred to
the beginning of the loop for next iteration.
the beginning of the loop for next iteration.
 The loop continues until the test condition of the loop become
The loop continues until the test condition of the loop become
false.
false.
 Syntax: continue;
Syntax: continue;

E.g.
E.g. for (m=1;m<=3;m++)
for (m=1;m<=3;m++)
{
{
for (n=1;n<=2;n++)
for (n=1;n<=2;n++)
{
{
if (m==n)
if (m==n)
continue;
continue;
printf(“ m=%d n=%d”);
printf(“ m=%d n=%d”);
}
}
}
}
Output:
1 2
2 1
3 1
3 2
goto Statement
goto Statement
 An unconditional control statement that causes the control to
An unconditional control statement that causes the control to
jump to a different location in the program without checking
jump to a different location in the program without checking
any condition.
any condition.
 It is normally used to alter the normal sequence of program
It is normally used to alter the normal sequence of program
execution by transferring control to some other part of the
execution by transferring control to some other part of the
program.
program.
 So it is also called jump statement.
So it is also called jump statement.
 Syntax: goto label;
Syntax: goto label;
 Label represents an identifier which is used to label the
Label represents an identifier which is used to label the
destination statement to which the control should be
destination statement to which the control should be
transferred.
transferred.
label : statement;
label : statement;
 The goto statement causes the control to be shifted either in
The goto statement causes the control to be shifted either in
forward direction or in a backward direction .
forward direction or in a backward direction .
exit() function
exit() function
 C provides a run time library function exit() which
C provides a run time library function exit() which
when encountered in a program causes the program to
when encountered in a program causes the program to
terminating without executing any statement
terminating without executing any statement
following it.
following it.
 Syntax:
Syntax: exit(status);
exit(status);
Status is an integer variable or constant.
Status is an integer variable or constant.
 If the status is 0,then program normally terminates
If the status is 0,then program normally terminates
without any errors.
without any errors.
 A non-zero status indicates abnormal termination of
A non-zero status indicates abnormal termination of
the program.
the program.
 The exit() function is defined in the process.h header
The exit() function is defined in the process.h header
file.
file.
Difference b/w exit() & break
Difference b/w exit() & break
 Exit()
Exit() is used to transfer the control
is used to transfer the control
completely out of the program whereas
completely out of the program whereas
break
break is used to transfer the control out
is used to transfer the control out
of the loop or switch statement.
of the loop or switch statement.
ARRAYS
ARRAYS
C ARRAYS
-a collection of same type data, 1D, 2D-
3D
94/25
ARRAYS
2/25
 An array is a collection of elements of the same type that
are referenced by a common name.
 Compared to the basic data type (int, float & char) it
is an aggregate or derived data type.
 All the elements of an array occupy a set of contiguous
memory locations.
 Why need to use array type?
 Consider the following issue:
"We have a list of 1000 students' marks of an
integer type. If using the basic data type (int),
we will declare something like the following…"
int studMark0, studMark1, studMark2, ..., studMark999;
ARRAYS
3/25
 Can you imagine how long we have to write
the declaration part by using normal variable
declaration?
int main(void)
{
int studMark1, studMark2, studMark3,
studMark4, …, …, studMark998, stuMark999,
studMark1000;
…
…
return 0;
}
ARRAYS
4/25
 By using an array, we just declare like this,
int studMark[1000];
 This will reserve 1000 contiguous memory locations for storing the
students’ marks.
 Graphically, this can be depicted as in the following figure.
ARRAYS
5/25
 This absolutely has simplified our declaration of the
variables.
 We can use index or subscript to identify each
element or location in the memory.
 Hence, if we have an index of jIndex,
studMark[jIndex] would refer to the jIndexth
element in the array of studMark.
 For example, studMark[0] will refer to the first
element of the array.
 Thus by changing the value of jIndex, we could refer
to any element in the array.
 So, array has simplified our declaration and of course,
manipulation of the data.
ARRAYS
6/25
One Dimensional Array: Declaration
 Dimension refers to the array's size, which is how big the
array is.
 A single or one dimensional array declaration has the
following form,
array_element_data_type array_name[array_size];
 Here, array_element_data_type define the base type of the
array, which is the type of each element in the array.
 array_name is any valid C / C++ identifier name that obeys
the same rule for the identifier naming.
 array_size defines how many elements the array will hold.
ARRAYS
7/25
 For example, to declare an array of 30 characters, that
construct a people name, we could declare,
char cName[30];
 Which can be depicted as follows,
 In this statement, the array character can store
up to 30 characters with the first character
occupying location cName[0] and the last
character occupying cName[29].
 Note that the index runs from 0 to 29. In C, an
index always starts from 0 and ends with array's
(size-1).
 So, take note the difference between the array
size and subscript/index terms.
ARRAYS
8/25
 Examples of the one-dimensional array declarations,
int xNum[20], yNum[50];
float fPrice[10], fYield;
char chLetter[70];
 The first example declares two arrays named xNum and yNum of type
int. Array xNum can store up to 20 integer numbers while yNum can
store up to 50 numbers.
 The second line declares the array fPrice of type float. It can
store up to 10 floating-point values.
 fYield is basic variable which shows array type can be declared
together with basic type provided the type is similar.
 The third line declares the array chLetter of type char. It can store a
string up to 69 characters.
 Why 69 instead of 70? Remember, a string has a null terminating
character (0) at the end, so we must reserve for it.
ARRAYS
9/25
Array Initialization
 An array may be initialized at the time of declaration.
 Giving initial values to an array.
 Initialization of an array may take the following form,
type array_name[size] = {a_list_of_value};
 For example:
int idNum[7] = {1, 2, 3, 4, 5, 6, 7};
float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1};
char chVowel[6] = {'a', 'e', 'i', 'o', 'u', '0'};
 The first line declares an integer array idNum and it immediately
assigns the values 1, 2, 3, ..., 7 to idNum[0], idNum[1],
idNum[2],..., idNum[6] respectively.
 The second line assigns the values 5.6 to fFloatNum[0], 5.7 to
fFloatNum[1], and so on.
 Similarly the third line assigns the characters 'a' to chVowel[0], 'e' to
chVowel[1], and so on. Note again, for characters we must use the
single apostrophe/quote (') to enclose them.
 Also, the last character in chVowel is NULL character ('0').
ARRAYS
103/25
 Initialization of an array of type char for holding strings may take the following
form,
char array_name[size] = "string_lateral_constant";
 For example, the array chVowel in the previous example could have been
written more compactly as follows,
char chVowel[6] = "aeiou";
 When the value assigned to a character array is a string (which must be
enclosed in double quotes), the compiler automatically supplies the NULL
character but we still have to reserve one extra place for the NULL.
 For unsized array (variable sized), we can declare as follow,
char chName[ ] = "Mr. Dracula";
 C compiler automatically creates an array which is big enough to hold all the
initializer.
ARRAYS
104/25
 Arrays allow programmers to group related items of the same
data type in one variable.
 However, when referring to an array, one has to specify not only
the array or variable name but also the index number of interest.
 Program example 1: Sum of array’s element.
 Notice the array's element which is not initialized is set to 0
automatically.
ARRAYS
105/25
 Program example 2: Searching the smallest value.
 Finding the smallest element in the array named fSmallest.
 First, it assumes that the smallest value is in fSmallest[0] and
assigns it to the variable nSmall.
 Then it compares nSmall with the rest of the values in fSmallest,
one at a time.
 When an element is smaller than the current value contained in
nSmall, it is assigned to nSmall. The process finally places the
smallest array element in nSmall.
ARRAYS
106/25
 Program example 3: Searching the biggest
value. By modifying the previous example we
can search the biggest value.
ARRAYS
107/25
 Program example 4: Searching the location for
the given value in an array
ARRAYS
108/25
 Program example 5: Storing and reading
a string
ARRAYS
109/25
 Program example 6: Storing and reading array
content and its index
ARRAYS
110/25
Two Dimensional/2D Arrays
 A two dimensional array has two subscripts/indexes.
 The first subscript refers to the row, and the second, to the column.
 Its declaration has the following form,
data_type array_name[1st
dimension size][2nd
dimension size];
 For examples,
int xInteger[3][4];
float matrixNum[20][25];
 The first line declares xInteger as an integer array with 3 rows and
4 columns.
 Second line declares a matrixNum as a floating-point array with 20
rows and 25 columns.
ARRAYS
111/25
 If we assign initial string values for the 2D array it will look
something like the following,
char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole",
"Kidman", "Arnold", "Jodie"};
 Here, we can initialize the array with 6 strings, each with
maximum 9 characters long.
 If depicted in rows and columns it will look something like the
following and can be considered as contiguous arrangement in
the memory.
ARRAYS
112/25
 Take note that for strings the null character (0) still needed.
 From the shaded square area of the figure we can determine the size of the
array.
 For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the
number of the colored square. In general, for
array_name[x][y];
 The array size is = First index x second index = xy.
 This also true for other array dimension, for example three dimensional
array,
array_name[x][y][z]; => First index x second index x third index = xyz
 For example,
ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.
 And if you want to illustrate the 3D array, it could be a cube with wide, long
and height dimensions.
ARRAYS
20/25
 Program example 7: Storing and reading
array content and its index
ARRAYS
114/25
 Program example 8: Swapping iIndex
(iRow) with jIndex (iColumn) in the
previous program example
ARRAYS
22/25
1. Program example 9: Strings are read in by the rows.
2. Each row will have one string. Enter the following data:
“you”, “are”, “cat” for the following example.
3. Remember that after each string, a null character is
added.
4. We are reading in strings but printing out only characters.
ARRAYS
23/25
 The contents of the array in memory after the three
strings are read in the array.
 Re-run the program, enter the following data:
“you”, “my”. Illustrates the content as done
previously.
ARRAYS
24/25
1. Does your output agree?
2. How is the null character, '0' printed?
3. Is there a garbage character in a[1][3]? If so,
why?
a) The output matched, except the garbage.
b) Just an empty space.
c) Yes. This slot has been reserved but not
filled so whatever the previous data that
has been stored here would be displayed
(if possible).
End-of-C-arrays
25/25

More Related Content

Similar to Introduction to C for Btech 1st year.ppt (20)

PPTX
Compilers.pptx
MohammedMohammed578197
 
PPTX
Computer Science guide to C Unit-I Translator.pptx
NomthandazoNgwenya1
 
PPTX
Introduction to Compilers
Akhil Kaushik
 
PPTX
Embedded c c++ programming fundamentals master
Hossam Hassan
 
PPTX
4_5802928814682016556.pptx
AshenafiGirma5
 
PPTX
Cd ch1 - introduction
mengistu23
 
PPTX
CD - CH1 - Introduction to compiler design.pptx
ZiyadMohammed17
 
PDF
sege.pdf
SegezzBrian
 
PDF
Introduction to computer programming
VanessaBuensalida
 
PDF
X-CS-8.0 Programming in C Language 2022-2023.pdf
Alefya1
 
PPTX
programming.pptx
DarianElmyra
 
PPTX
Python-unit -I.pptx
crAmth
 
PPTX
Python Programming-Skill Course - unit-i.pptx
KavithaDonepudi
 
PPT
Compiler Design Basics
Akhil Kaushik
 
PPT
Compiler Design Basics
Akhil Kaushik
 
PPTX
Agro informatics centre up State of Lec 6.pptx
muddydevil2003
 
PDF
Week 08_Basics of Compiler Construction.pdf
AnonymousQ3EMYoWNS
 
PPTX
Introduction_to_Programming.pptx
PmarkNorcio
 
PDF
Module4.pdf ,...................................
chetanreddy2212
 
Compilers.pptx
MohammedMohammed578197
 
Computer Science guide to C Unit-I Translator.pptx
NomthandazoNgwenya1
 
Introduction to Compilers
Akhil Kaushik
 
Embedded c c++ programming fundamentals master
Hossam Hassan
 
4_5802928814682016556.pptx
AshenafiGirma5
 
Cd ch1 - introduction
mengistu23
 
CD - CH1 - Introduction to compiler design.pptx
ZiyadMohammed17
 
sege.pdf
SegezzBrian
 
Introduction to computer programming
VanessaBuensalida
 
X-CS-8.0 Programming in C Language 2022-2023.pdf
Alefya1
 
programming.pptx
DarianElmyra
 
Python-unit -I.pptx
crAmth
 
Python Programming-Skill Course - unit-i.pptx
KavithaDonepudi
 
Compiler Design Basics
Akhil Kaushik
 
Compiler Design Basics
Akhil Kaushik
 
Agro informatics centre up State of Lec 6.pptx
muddydevil2003
 
Week 08_Basics of Compiler Construction.pdf
AnonymousQ3EMYoWNS
 
Introduction_to_Programming.pptx
PmarkNorcio
 
Module4.pdf ,...................................
chetanreddy2212
 

Recently uploaded (20)

PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
Ad

Introduction to C for Btech 1st year.ppt

  • 2. Outline of Topics • Hardware/Software interface – Layers of the Machine – Kinds of Software • Computer Languages • Syntax, Semantics, Grammars • What happens to your program? – Compilation, Linking, Execution – Program errors • Compilation vs. Interpretation etc.
  • 3. Software Categories • System SW –Programs written for computer systems • Compilers, operating systems, … • Application SW –Programs written for computer users • Word-processors, spreadsheets, & other application packages
  • 4. A Layered View of the Computer Machine with all its hardware System Software Compilers, Interpreters,Preprocessors, etc. Operating System, Device Drivers Application Programs Word-Processors, Spreadsheets, Database Software, IDEs, etc…
  • 5. Operating System (OS)  Provides several essential services: – Loading & running application programs – Allocating memory & processor time – Providing input & output facilities – Managing files of information
  • 6. Programs • Programs are written in programming languages – PL = programming language – Pieces of the same program can be written in different PLs • Languages closer to the machine can be more efficient • As long as they agree on how to communicate • A PL is – A special purpose and limited language – A set of rules and symbols used to construct a computer program – A language used to interact with the computer
  • 7. Computer Languages – Machine Language • Uses binary code • Machine-dependent • Not portable • Assembly Language – Uses mnemonics – Machine-dependent – Not usually portable • High-Level Language (HLL) – Uses English-like language – Machine independent – Portable (but must be compiled for different platforms) – Examples: Pascal, C, C++, Java, Fortran, . . .
  • 8. Machine Language • The representation of a computer program which is actually read and understood by the computer. – A program in machine code consists of a sequence of machine instructions. • Instructions: – Machine instructions are in binary code – Instructions specify operations and memory cells involved in the operation Example: Operation Address 0010 0000 0000 0100 0100 0000 0000 0101 0011 0000 0000 0110
  • 9. Assembly Language • A symbolic representation of the machine language of a specific processor. • Is converted to machine code by an assembler. • Usually, each line of assembly code produces one machine instruction (One-to-one correspondence). • Programming in assembly language is slow and error-prone but is more efficient in terms of hardware performance. • Mnemonic representation of the instructions and data • Example: Load Price Add Tax Store Cost Sample Assembly code for Printing Hello World
  • 10. High-level language • A programming language which use statements consisting of English-like keywords such as "FOR", "PRINT" or “IF“, ... etc. • Each statement corresponds to several machine language instructions (one-to-many correspondence). • Much easier to program than in assembly language. • Data are referenced using descriptive names • Operations can be described using familiar symbols • Example: Cost := Price + Tax
  • 11. Syntax & Semantics • Syntax: – The structure of strings in some language. A language's syntax is described by a grammar. – Examples: • Binary number <binary_number> = <bit> | <bit> <binary_number> <bit> = 0 | 1 • Identifier <identifier> = <letter> {<letter> | <digit> } <letter> = a | b | . . . | z <digit = 0 | 1 | . . . | 9 • Semantics: – The meaning of the language
  • 12. Syntax & Grammars • Syntax descriptions for a PL are themselves written in a formal language. – E.g. Backus-Naur Form (BNF) • The formal language is not a PL but it can be implemented by a compiler to enforce grammar restrictions. • Some PLs look more like grammar descriptions than like instructions.
  • 13. Compilers & Programs • Compiler – A program that converts another program from some source language (or high-level programming language / HLL) to machine language (object code). – Some compilers output assembly language which is then converted to machine language by a separate assembler. – Is distinguished from an assembler by the fact that each input statement, in general, correspond to more than one machine instruction.
  • 14. Compilation into Assembly L Compiler Assembler Source Program Assembly Language Assembly Language Machine Language
  • 15. Compilers & Programs • Source program – The form in which a computer program, written in some formal programming language, is written by the programmer. – Can be compiled automatically into object code or machine code or executed by an interpreter. – Pascal source programs have extension ‘.pas’
  • 16. Compilers & Programs • Object program – Output from the compiler – Equivalent machine language translation of the source program – Files usually have extension ‘.obj’ • Executable program – Output from linker/loader – Machine language program linked with necessary libraries & other files – Files usually have extension ‘.exe’
  • 17. What is a Linker? • A program that pulls other programs together so that they can run. • Most programs are very large and consist of several modules. • Even small programs use existing code provided by the programming environment called libraries. • The linker pulls everything together, makes sure that references to other parts of the program (code) are resolved.
  • 18. Running Programs Memory Input Data Program Output Machine language program (executable file) Data entered during execution Computed results C P U • Steps that the computer goes through to run a program:
  • 19. Program Execution • Steps taken by the CPU to run a program (instructions are in machine language): 1. Fetch an instruction 2. Decode (interpret) the instruction 3. Retrieve data, if needed 4. Execute (perform) actual processing 5. Store the results, if needed
  • 20. Program Errors • Syntax Errors: – Errors in grammar of the language • Runtime error: – When there are no syntax errors, but the program can’t complete execution • Divide by zero • Invalid input data • Logical errors: – The program completes execution, but delivers incorrect results – Incorrect usage of parentheses
  • 21. Compilation Compiler Target Program Source Program Target Program Input Output • Compiler translates source into target (a machine language program) • Compiler goes away at execution time • Compiler is itself a machine language program, presumably created by compiling some other high-level program • Machine language, when written in a format understood by the OS is object code
  • 22. Interpretation Interpreter Source Program Input Output • The interpreter stays around during execution • It reads and executes statements one at a time
  • 23. Compilation vs. Interpretation • Compilation: – Syntax errors caught before running the program – Better performance – Decisions made once, at compile time • Interpretation: – Better diagnostics (error messages) – More flexibility – Supports late binding (delaying decisions about program implementation until runtime) • Can better cope with PLs where type and size of variables depend on input – Supports creation/modification of program code on the fly (e.g. Lisp, Prolog)
  • 24. Mixture of C & I Translator Source Program Intermediate Program VM Intermediate Program Input Output • Many programming languages implement this • Interpreter implements a Virtual Machine (VM).
  • 25. JAVA Compiler Interpreter Java bytecode ML For flexibility: Just In Time (JIT) compiler translates bytecode into ML just before execution For portability:
  • 26. Introduction to C programming
  • 27. Introduction to C programming
  • 28. Introduction to C programming
  • 49. Sample questions 1. Which is true about conditional compilation? a)It is taken care by the compiler. b)It is setting the compiler option conditionally. c)It is compiling a program based on a condition d)It is taken care of by the pre-processor. 2. What is the minimum number of temporary variables required to swap the values of two variables? a)1 b) 2 c) 3 d) 0 3. C is a a.High level language b.Low level language c.High level language with some low level features d.Low level language with some high level features 4.If integer needs two bytes of starage, then max value of an unsigned integer is: 5.What will be happen with the following code fragment: print(“%d”, printf(“TIM”));
  • 50. Basics of ‘C’ By: Dr. Abhishek Singh
  • 51. General Aspect of ‘C’ • Originally developed in the 1970s, by Dennis Ritchie at Bell Telephone Laboratories, Inc. • High level, general–purpose, structured programming language. • Instructions of C consists of terms that are very closely same to algebraic expressions, consisting of certain English keywords such as if, else, for ,do and while • C contains certain additional features that allows it to be used at a lower level , acting as bridge between machine language and the high level languages. This allows C to be used for system programming as well as for applications programming Structured Programming •Structured Programming is a type of programming that generally converts large or complex programs into more manageable and small pieces of code. •These small pieces of codes are usually known as functions or modules or sub- programs of large complex programs. •It is known as modular programming and minimizes the chances of function affecting another. •Example: Click me
  • 52. The Character set of ‘C’ • C language consist of some characters set, numbers and some special symbols. The character set of C consist of all the alphabets of English language. Alphabets a to z, A to Z Numeric 0,1 to 9 Special Symbols {,},[,],?,+,-,*,/,%,!,;,and more • The words formed from the character set are building blocks of C and are sometimes known as tokens. • Tokens represent the individual entity of language. The following different types of token are used in C 1) Identifiers 2)Keywords 3)Constants 4) Operators 5)Punctuation Symbols
  • 53. Identifiers • A 'C' program consist of two types of elements , user defined and system defined. Idetifiers is nothing but a name given to these elements. • An identifier is a word used by a programmer to name a variable , function, or label. • identifiers consist of letters and digits, in any order, except that the first charecter or lable. • Identifiers consist of letters and digits if any order,except that the first charecter must be letter. • Both Upper and lowercase letters can be used
  • 54. Keywords • Keywords are nothing but system defined identifiers. • Keywords are reserved words of the language. • They have specific meaning in the language and cannot be used by the programmer as variable or constant names • C is case senitive, it means these must be used as it is • 32 Keywords in C Programming auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while
  • 55. Variables • A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. • The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. There are following basic variable types − Type Description • char Typically a single octet(one byte). This is an integer type. • int The most natural size of integer for the machine. • float A single-precision floating point value. • double A double-precision floating point value. • void Represents the absence of type.
  • 56. Constants • A constant is a value or an identifier whose value cannot be altered in a program. For example: 1, 2.5, • As mentioned, an identifier also can be defined as a constant. eg. const double PI = 3.14 • Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program. Integer constants • A integer constant is a numeric constant (associated with number) without any fractional or exponential part. There are three types of integer constants in C programming: • decimal constant(base 10) • octal constant(base 8) • hexadecimal constant(base 16)
  • 57. Constants Floating-point constants • A floating point constant is a numeric constant that has either a fractional form or an exponent form. For example: 2.0,0.0000234,-0.22E-5 Character constants • A character constant is a constant which uses single quotation around characters. For example: 'a', 'l', 'm', 'F' String constants • String constants are the constants which are enclosed in a pair of double-quote marks. For example: "good" ,"x","Earth is roundn"
  • 58. Escape Sequences Sometimes, it is necessary to use characters which cannot be typed or has special meaning in C programming. For example: newline(enter), tab, question mark etc. In order to use these characters, escape sequence is used. • For example: n is used for newline. The backslash ( ) causes "escape" from the normal way the characters are interpreted by the compiler.Escape Sequences Character • b Backspace • f Form feed • n Newline • r Return • t Horizontal tab • v Vertical tab • Backslash • ' Single quotation mark • " Double quotation mark • ? Question mark • 0 Null character We will see and evaluate these escape sequences throughout the syllabus
  • 59. Operators in C:An operator is a symbol which operates on a value or a variable. For example: + is an operator to perform addition. C programming has wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as: • Arithmetic Operators • Increment and Decrement Operators • Assignment Operators • Relational Operators • Logical Operators • Conditional Operators • Bitwise Operators • Special Operators
  • 60. Arithmetic Operator • Operator Meaning of Operator • + addition or unary plus • - subtraction or unary minus • * multiplication • / division • % remainder after division( modulo division)
  • 61. Increment and Decrement Operators 1. C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1. 2. Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. 3. These two operators are unary operators, meaning they only operate on a single operand. eg. int a=10, b=100 ++a = 11 --b = 99
  • 62. C Assignment Operators • An assignment operator is used for assigning a value to a variable. The most common assignment operator is = • Operator Example Same as • = a = b a = b • += a += b a = a+b • -= a -= b a = a-b • *= a *= b a = a*b • /= a /= b a = a/b • %= a %= b a = a%b
  • 63. C Relational Operators • A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0. • Relational operators are used in decision making and loops. Operator Meaning of Operator Example • == Equal to 5 == 3 returns 0 • > Greater than 5 > 3 returns 1 • < Less than 5 < 3 returns 0 • != Not equal to 5 != 3 returns 1 • >= Greater than or equal to 5 >= 3 returns 1 • <= Less than or equal to 5 <= 3 return 0
  • 64. The First C program • The statements in a program must appear in the same order in which we wish to execute them unless of course the problem demands a deliberate ‘jump’ or transfer of control to a statement, which may be out of sequence. • Blank spaces must be inserted between two words. • All statements are inserted in small letters. • C has no specific rules for the position at which a statement will be written. That’s why it is often called a free-form language.
  • 65. The First C program // Calculation of Simple Interest /* Calculation of Simple Interest */ #include<stdio.h> void main() { int p, n; float r, si; p = 1000; n = 3; r = 8.5; //formula for simple interest si = p*n*r/100; printf("Simple Interest is: n%f", si); } C preprocessors (Click to know more) https://www.geeksforgeeks.org/cc-preprocessors/
  • 66. Receiving Inputs // Calculation of Simple Interest with user inputs #include<stdio.h> void main() { int p, n; float r, si; printf(“Enter the Value of p, n, r:n”); scanf(“%d %d %f”, &p, &n, &r); // p = 1000; //n = 3; //r = 8.5; //formula for simple interest si = p*n*r/100; printf("Simple Interest is: n%f", si); } Type declarations instructions Arithmetic Instructions
  • 67. Objectives of these slides: Objectives of these slides:  to introduce the main kinds of C contr to introduce the main kinds of C contr ol flow ol flow Control Statements Programming Programming In C In C
  • 68. Control Structures Control Structures  There may be situations where the There may be situations where the programmer requires to alter normal flow of programmer requires to alter normal flow of execution of program or to perform the execution of program or to perform the same operation a no. of times. same operation a no. of times.  Various control statements supported by c Various control statements supported by c are- are-  Decision control statements Decision control statements  Loop control statements Loop control statements
  • 69. Decision Control Statements Decision Control Statements  Decision control statements alter the normal Decision control statements alter the normal sequential execution of the statements of the sequential execution of the statements of the program depending upon the test condition to be program depending upon the test condition to be carried out at a particular point in program. carried out at a particular point in program.  Decision control statements supported by c are:- Decision control statements supported by c are:-  if statement if statement  if-else statement if-else statement  Else if Ladder Else if Ladder  Nested If Nested If  switch statement switch statement
  • 70. Decision Control Statements Decision Control Statements  if statement if statement  Most simple and powerful decision control statement. Most simple and powerful decision control statement.  It executes a statement or block of statements only if the It executes a statement or block of statements only if the condition is true. condition is true.  Syntax: if (condition) Syntax: if (condition) if (condition) if (condition) { { OR OR { { statement (s); statement (s); statement 1; statement 1; } } statement 2; statement 2; Next statement; Next statement; } } statement 3; statement 3;  In above syntax : if condition is true only then the In above syntax : if condition is true only then the statements within the block are executed otherwise next statements within the block are executed otherwise next statement in sequence is executed. statement in sequence is executed.
  • 71.  Flowchart Flowchart Condition STOP False True Block of if Next statement /* Program to check whether a no. is even */ # include<stdio.h> # include<conio.h> void main() { int num; clrscr(); printf(“enter the number”); scanf(“%d”,&num) if(num%2==0) { printf(“n Number is even”); } printf(“ End of program”); getch(); }
  • 72. if – else statement if – else statement  In case of if statement, the block of statements is executed only when In case of if statement, the block of statements is executed only when the condition is true otherwise the control is transferred to the next the condition is true otherwise the control is transferred to the next statement following if block. statement following if block.  But if specific statements are to be executed in both cases (either But if specific statements are to be executed in both cases (either condition is true or false) then if – else statement is used. condition is true or false) then if – else statement is used.  In if – else statement a block of statements are executed if the condition In if – else statement a block of statements are executed if the condition is true but a different block of statements is executed when the condition is true but a different block of statements is executed when the condition is false. is false.  Syntax: if (condition) Syntax: if (condition) { { statement 1; statement 1; statement 2; statement 2; } } else else { { statement 3; statement 3; } } Test Condition Block of if Block of else Next statement STOP False True
  • 73. Exercise: WAP to check whether a given no. is even or Exercise: WAP to check whether a given no. is even or odd? odd? Nested if – else statement Nested if – else statement  When an entire if-else is enclosed within the body of if When an entire if-else is enclosed within the body of if statement or/and in the body of else statement, it is known statement or/and in the body of else statement, it is known as nested if-else statement. as nested if-else statement.  The ways of representing nested if –else are- The ways of representing nested if –else are- if (condition1) { if (condition2) statement 1; else statement 2; } else statement 3; if (condition1) { if (condition2) statement 1; else statement 2; } else { if (condition 3) statement 3; else statement 4; } if (condition1) statement 1; else { if (condition2) statement 2; else statement 3; }
  • 74. If- else- if ladder If- else- if ladder  In a program involving multiple conditions, the nested if else In a program involving multiple conditions, the nested if else statements makes the program very difficult to write and statements makes the program very difficult to write and understand if nested more deeply. understand if nested more deeply.  For this ,we use if-else-if ladder. For this ,we use if-else-if ladder.  Syntax: if (condition1) Syntax: if (condition1) statement1; statement1; else if(condition2) else if(condition2) statement2; statement2; else if(condition3) else if(condition3) statement 3; statement 3; else else default statement; default statement; condition 1 condition 2 condition 3 Statement 1 Statement 2 Statement 3 Default statement Next statement false true false true false true
  • 75. Switch statement Switch statement  Switch is a multi-way decision making statement which selects Switch is a multi-way decision making statement which selects one of the several alternatives based on the value of single one of the several alternatives based on the value of single variable or expression. variable or expression.  It is mainly used to replace multiple if-else-if statement. It is mainly used to replace multiple if-else-if statement.  The if-else-if statement causes performance degradation as The if-else-if statement causes performance degradation as several conditions need to be evaluated before a particular several conditions need to be evaluated before a particular condition is satisfied. condition is satisfied.  Syntax: Syntax: switch (expression) switch (expression) { { case constant1 : statement (s); [break;] case constant1 : statement (s); [break;] case constant2 : statement (s); [break;] case constant2 : statement (s); [break;] …………………………………… ……………………………………. . default: statement (s) default: statement (s) } }
  • 76. Break statement Break statement  Break statement terminates the execution of Break statement terminates the execution of the loop in which it is defined. the loop in which it is defined.  The control is transferred immediately to The control is transferred immediately to the next executable statement after the loop. the next executable statement after the loop.  It is mostly used to exit early from the loop It is mostly used to exit early from the loop by skipping the remaining statements of by skipping the remaining statements of loop or switch control structures. loop or switch control structures.  Syntax: break; Syntax: break;
  • 77. Looping Structures Looping Structures  When we want to repeat a group of statements a no. When we want to repeat a group of statements a no. of times, loops are used. of times, loops are used.  These loops are executed until the condition is true. These loops are executed until the condition is true.  When condition becomes false, control terminates When condition becomes false, control terminates the loop and moves on to next instruction the loop and moves on to next instruction immediately after the loop. immediately after the loop.  Various looping structures are- Various looping structures are-  while while  do – while do – while  for for
  • 78. LOOPING STATEMENTS LOOPING STATEMENTS  Loop is divided into two parts: Loop is divided into two parts:  Body of the loop Body of the loop  Control of loop Control of loop  Mainly control of loop is divided into two Mainly control of loop is divided into two parts: parts:  Entry Control loop (while, for) Entry Control loop (while, for)  Exit Control loop (do-while) Exit Control loop (do-while)
  • 79. while statement while statement  While loop is used to execute set of statements as long as While loop is used to execute set of statements as long as condition evaluates to true. condition evaluates to true.  It is mostly used in those cases where the programmer It is mostly used in those cases where the programmer doesn’t know in advance how many times the loop will be doesn’t know in advance how many times the loop will be executed. executed.  Syntax: while (condition) Syntax: while (condition) { { Statement 1 ; Statement 1 ; Statement 2 ; Statement 2 ; } } condition statement Statement after while loop true
  • 80. do- while do- while  do-while is similar to while except that its test do-while is similar to while except that its test condition is evaluated at the end of the loop instead condition is evaluated at the end of the loop instead at the beginning as in case of while loop. at the beginning as in case of while loop.  So, in do-while the body of the loop always executes So, in do-while the body of the loop always executes at least once even if the test condition evaluates to at least once even if the test condition evaluates to false during the first iteration. false during the first iteration.  Syntax: do Syntax: do { { statement 1; statement 1; statement 2; statement 2; }while (condition); }while (condition); statement; statement; Body of loop Test condition Next statement true false
  • 81. for loop for loop  Most versatile and popular of three loop structures. Most versatile and popular of three loop structures.  Is used in those situations when a programmer Is used in those situations when a programmer knows in advance the number of times a statement knows in advance the number of times a statement or block will be executed. or block will be executed.  It contains loop control elements all at one place It contains loop control elements all at one place while in other loops they are scattered over the while in other loops they are scattered over the program and are difficult to understand. program and are difficult to understand.  Syntax:- Syntax:- for (initialization; condition; increment/decrement) for (initialization; condition; increment/decrement) { { Statement( s); Statement( s); } }
  • 82. The The for for is a sort of is a sort of while while for (expr1; expr2; expr3) for (expr1; expr2; expr3) statement; statement; is equivalent to: is equivalent to: expr1; expr1; while (expr2) { while (expr2) { statement; statement; expr3; expr3; } }
  • 83. Various other ways of writing same for loops Various other ways of writing same for loops i = 1 i = 1 for (; i<=15;i ++) for (; i<=15;i ++) { { …… …….. .. } } for (i=1; ;i++) { ……… if (i>15) break; …… } for (i=1;i<=15;) { …………. i++; }
  • 84. Some Examples Some Examples for(i = 7; i <=77; i += 7) for(i = 7; i <=77; i += 7) statement; statement; for(i = 20; i >= 2; i -= 2) for(i = 20; i >= 2; i -= 2) statement; statement; for(j = 10; j > 20; j++) for(j = 10; j > 20; j++) statement; statement; for(j = 10; j > 0; j--) for(j = 10; j > 0; j--) statement; statement;
  • 85. Incrementing Incrementing  Add 1 to c by writing: Add 1 to c by writing: c = c + 1; c = c + 1; Also: Also: c += 1; c += 1; Also: Also: c++; c++; Also: Also: ++c; ++c; Incrementing and Decrementing Incrementing and Decrementing
  • 86. /* Preincrementing and /* Preincrementing and po postincrementing */ stincrementing */ #include <stdio.h> #include <stdio.h> int main() int main() { { int c; int c; c = 5; c = 5; printf("%dn", c); printf("%dn", c); printf("%dn",c++); printf("%dn",c++); /*post /*post increment*/ increment*/ printf("%dnn", c); printf("%dnn", c); : : continued
  • 87. c = 5; c = 5; printf("%dn", c); printf("%dn", c); printf("%dn",++c); /*pre-increme printf("%dn",++c); /*pre-increme nt*/ nt*/ printf("%dn", c); printf("%dn", c); return 0; return 0; } } Output: Output: 5 5 5 5 6 6 5 5 6 6 6 6
  • 88. Decrementing Decrementing  Take 1 from c by writing: Take 1 from c by writing: c = c - 1; c = c - 1; Also: Also: c -= 1; c -= 1; Also: Also: c--; c--; Also: Also: --c; --c;
  • 89. Continue statement Continue statement  Like break ,continue statement also skips the remaining Like break ,continue statement also skips the remaining statements of the body of the loop where it is defined but statements of the body of the loop where it is defined but instead of terminating the loop, the control is transferred to instead of terminating the loop, the control is transferred to the beginning of the loop for next iteration. the beginning of the loop for next iteration.  The loop continues until the test condition of the loop become The loop continues until the test condition of the loop become false. false.  Syntax: continue; Syntax: continue;  E.g. E.g. for (m=1;m<=3;m++) for (m=1;m<=3;m++) { { for (n=1;n<=2;n++) for (n=1;n<=2;n++) { { if (m==n) if (m==n) continue; continue; printf(“ m=%d n=%d”); printf(“ m=%d n=%d”); } } } } Output: 1 2 2 1 3 1 3 2
  • 90. goto Statement goto Statement  An unconditional control statement that causes the control to An unconditional control statement that causes the control to jump to a different location in the program without checking jump to a different location in the program without checking any condition. any condition.  It is normally used to alter the normal sequence of program It is normally used to alter the normal sequence of program execution by transferring control to some other part of the execution by transferring control to some other part of the program. program.  So it is also called jump statement. So it is also called jump statement.  Syntax: goto label; Syntax: goto label;  Label represents an identifier which is used to label the Label represents an identifier which is used to label the destination statement to which the control should be destination statement to which the control should be transferred. transferred. label : statement; label : statement;  The goto statement causes the control to be shifted either in The goto statement causes the control to be shifted either in forward direction or in a backward direction . forward direction or in a backward direction .
  • 91. exit() function exit() function  C provides a run time library function exit() which C provides a run time library function exit() which when encountered in a program causes the program to when encountered in a program causes the program to terminating without executing any statement terminating without executing any statement following it. following it.  Syntax: Syntax: exit(status); exit(status); Status is an integer variable or constant. Status is an integer variable or constant.  If the status is 0,then program normally terminates If the status is 0,then program normally terminates without any errors. without any errors.  A non-zero status indicates abnormal termination of A non-zero status indicates abnormal termination of the program. the program.  The exit() function is defined in the process.h header The exit() function is defined in the process.h header file. file.
  • 92. Difference b/w exit() & break Difference b/w exit() & break  Exit() Exit() is used to transfer the control is used to transfer the control completely out of the program whereas completely out of the program whereas break break is used to transfer the control out is used to transfer the control out of the loop or switch statement. of the loop or switch statement.
  • 94. C ARRAYS -a collection of same type data, 1D, 2D- 3D 94/25
  • 95. ARRAYS 2/25  An array is a collection of elements of the same type that are referenced by a common name.  Compared to the basic data type (int, float & char) it is an aggregate or derived data type.  All the elements of an array occupy a set of contiguous memory locations.  Why need to use array type?  Consider the following issue: "We have a list of 1000 students' marks of an integer type. If using the basic data type (int), we will declare something like the following…" int studMark0, studMark1, studMark2, ..., studMark999;
  • 96. ARRAYS 3/25  Can you imagine how long we have to write the declaration part by using normal variable declaration? int main(void) { int studMark1, studMark2, studMark3, studMark4, …, …, studMark998, stuMark999, studMark1000; … … return 0; }
  • 97. ARRAYS 4/25  By using an array, we just declare like this, int studMark[1000];  This will reserve 1000 contiguous memory locations for storing the students’ marks.  Graphically, this can be depicted as in the following figure.
  • 98. ARRAYS 5/25  This absolutely has simplified our declaration of the variables.  We can use index or subscript to identify each element or location in the memory.  Hence, if we have an index of jIndex, studMark[jIndex] would refer to the jIndexth element in the array of studMark.  For example, studMark[0] will refer to the first element of the array.  Thus by changing the value of jIndex, we could refer to any element in the array.  So, array has simplified our declaration and of course, manipulation of the data.
  • 99. ARRAYS 6/25 One Dimensional Array: Declaration  Dimension refers to the array's size, which is how big the array is.  A single or one dimensional array declaration has the following form, array_element_data_type array_name[array_size];  Here, array_element_data_type define the base type of the array, which is the type of each element in the array.  array_name is any valid C / C++ identifier name that obeys the same rule for the identifier naming.  array_size defines how many elements the array will hold.
  • 100. ARRAYS 7/25  For example, to declare an array of 30 characters, that construct a people name, we could declare, char cName[30];  Which can be depicted as follows,  In this statement, the array character can store up to 30 characters with the first character occupying location cName[0] and the last character occupying cName[29].  Note that the index runs from 0 to 29. In C, an index always starts from 0 and ends with array's (size-1).  So, take note the difference between the array size and subscript/index terms.
  • 101. ARRAYS 8/25  Examples of the one-dimensional array declarations, int xNum[20], yNum[50]; float fPrice[10], fYield; char chLetter[70];  The first example declares two arrays named xNum and yNum of type int. Array xNum can store up to 20 integer numbers while yNum can store up to 50 numbers.  The second line declares the array fPrice of type float. It can store up to 10 floating-point values.  fYield is basic variable which shows array type can be declared together with basic type provided the type is similar.  The third line declares the array chLetter of type char. It can store a string up to 69 characters.  Why 69 instead of 70? Remember, a string has a null terminating character (0) at the end, so we must reserve for it.
  • 102. ARRAYS 9/25 Array Initialization  An array may be initialized at the time of declaration.  Giving initial values to an array.  Initialization of an array may take the following form, type array_name[size] = {a_list_of_value};  For example: int idNum[7] = {1, 2, 3, 4, 5, 6, 7}; float fFloatNum[5] = {5.6, 5.7, 5.8, 5.9, 6.1}; char chVowel[6] = {'a', 'e', 'i', 'o', 'u', '0'};  The first line declares an integer array idNum and it immediately assigns the values 1, 2, 3, ..., 7 to idNum[0], idNum[1], idNum[2],..., idNum[6] respectively.  The second line assigns the values 5.6 to fFloatNum[0], 5.7 to fFloatNum[1], and so on.  Similarly the third line assigns the characters 'a' to chVowel[0], 'e' to chVowel[1], and so on. Note again, for characters we must use the single apostrophe/quote (') to enclose them.  Also, the last character in chVowel is NULL character ('0').
  • 103. ARRAYS 103/25  Initialization of an array of type char for holding strings may take the following form, char array_name[size] = "string_lateral_constant";  For example, the array chVowel in the previous example could have been written more compactly as follows, char chVowel[6] = "aeiou";  When the value assigned to a character array is a string (which must be enclosed in double quotes), the compiler automatically supplies the NULL character but we still have to reserve one extra place for the NULL.  For unsized array (variable sized), we can declare as follow, char chName[ ] = "Mr. Dracula";  C compiler automatically creates an array which is big enough to hold all the initializer.
  • 104. ARRAYS 104/25  Arrays allow programmers to group related items of the same data type in one variable.  However, when referring to an array, one has to specify not only the array or variable name but also the index number of interest.  Program example 1: Sum of array’s element.  Notice the array's element which is not initialized is set to 0 automatically.
  • 105. ARRAYS 105/25  Program example 2: Searching the smallest value.  Finding the smallest element in the array named fSmallest.  First, it assumes that the smallest value is in fSmallest[0] and assigns it to the variable nSmall.  Then it compares nSmall with the rest of the values in fSmallest, one at a time.  When an element is smaller than the current value contained in nSmall, it is assigned to nSmall. The process finally places the smallest array element in nSmall.
  • 106. ARRAYS 106/25  Program example 3: Searching the biggest value. By modifying the previous example we can search the biggest value.
  • 107. ARRAYS 107/25  Program example 4: Searching the location for the given value in an array
  • 108. ARRAYS 108/25  Program example 5: Storing and reading a string
  • 109. ARRAYS 109/25  Program example 6: Storing and reading array content and its index
  • 110. ARRAYS 110/25 Two Dimensional/2D Arrays  A two dimensional array has two subscripts/indexes.  The first subscript refers to the row, and the second, to the column.  Its declaration has the following form, data_type array_name[1st dimension size][2nd dimension size];  For examples, int xInteger[3][4]; float matrixNum[20][25];  The first line declares xInteger as an integer array with 3 rows and 4 columns.  Second line declares a matrixNum as a floating-point array with 20 rows and 25 columns.
  • 111. ARRAYS 111/25  If we assign initial string values for the 2D array it will look something like the following, char Name[6][10] = {"Mr. Bean", "Mr. Bush", "Nicole", "Kidman", "Arnold", "Jodie"};  Here, we can initialize the array with 6 strings, each with maximum 9 characters long.  If depicted in rows and columns it will look something like the following and can be considered as contiguous arrangement in the memory.
  • 112. ARRAYS 112/25  Take note that for strings the null character (0) still needed.  From the shaded square area of the figure we can determine the size of the array.  For an array Name[6][10], the array size is 6 x 10 = 60 and equal to the number of the colored square. In general, for array_name[x][y];  The array size is = First index x second index = xy.  This also true for other array dimension, for example three dimensional array, array_name[x][y][z]; => First index x second index x third index = xyz  For example, ThreeDimArray[2][4][7] = 2 x 4 x 7 = 56.  And if you want to illustrate the 3D array, it could be a cube with wide, long and height dimensions.
  • 113. ARRAYS 20/25  Program example 7: Storing and reading array content and its index
  • 114. ARRAYS 114/25  Program example 8: Swapping iIndex (iRow) with jIndex (iColumn) in the previous program example
  • 115. ARRAYS 22/25 1. Program example 9: Strings are read in by the rows. 2. Each row will have one string. Enter the following data: “you”, “are”, “cat” for the following example. 3. Remember that after each string, a null character is added. 4. We are reading in strings but printing out only characters.
  • 116. ARRAYS 23/25  The contents of the array in memory after the three strings are read in the array.  Re-run the program, enter the following data: “you”, “my”. Illustrates the content as done previously.
  • 117. ARRAYS 24/25 1. Does your output agree? 2. How is the null character, '0' printed? 3. Is there a garbage character in a[1][3]? If so, why? a) The output matched, except the garbage. b) Just an empty space. c) Yes. This slot has been reserved but not filled so whatever the previous data that has been stored here would be displayed (if possible).

Editor's Notes

  • #14: Instead of to ML Facilitates debugging Isolates compiler from changes in format of ML (new OS) Only assembler must be changed!