[go: up one dir, main page]

0% found this document useful (0 votes)
14 views92 pages

Introduction To C

The document provides an introduction to computer programming, covering topics such as hardware/software interfaces, computer languages, and the compilation process. It explains different types of software, programming languages, and the structure of programs, including syntax and semantics. Additionally, it discusses the execution of programs, common errors, and the specifics of the C programming language, including its character set, variables, constants, and operators.

Uploaded by

Usha Rani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views92 pages

Introduction To C

The document provides an introduction to computer programming, covering topics such as hardware/software interfaces, computer languages, and the compilation process. It explains different types of software, programming languages, and the structure of programs, including syntax and semantics. Additionally, it discusses the execution of programs, common errors, and the specifics of the C programming language, including its character set, variables, constants, and operators.

Uploaded by

Usha Rani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 92

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

Application Programs
Word-Processors, Spreadsheets,

Database Software, IDEs,


etc…
System Software
Compilers,
Interpreters,Preprocessors, etc.
Operating System, Device Drivers
Machine with all its
hardware
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

Source Assembly
Program Compiler Language

Assembly Assembler Machine


Language 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
• Steps that the computer goes through to run a
program:
Memory

Machine language
program
(executable file)
Input Data Data entered CPU
during execution

Computed results
Program Output
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
Source Target
Program Compiler Program

Input Target Program 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
Source
Program

Interpreter Output

Input

• 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
Source Intermediate
Program Translator Program

Intermediate
Program
VM Output
Input

• Many programming languages implement this

• Interpreter implements a Virtual Machine (VM).


JAVA
For portability:

Java Compiler

bytecode

ML Interpreter

For flexibility: Just In Time (JIT) compiler translates


bytecode into ML just before execution
Introduction to C programming
Introduction to C programming
Introduction to C programming
Compilation Process
Operator Precedence Chart
Operator Precedence Chart
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.
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

• 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
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 auto double int struct
system defined identifiers.
• Keywords are reserved words break else long switch
of the language.
case enum register typedef
• They have specific meaning in
the language and cannot be char extern return union
used by the programmer as
variable or constant names const float short unsigned
• C is case senitive, it means
these must be used as it is continue for signed void
• 32 Keywords in C Programming
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
round\n"
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 We will see and evaluate
• \t Horizontal tab these escape sequences
• \v Vertical tab throughout the syllabus
• \\ Backslash
• \' Single quotation mark
• \" Double quotation mark
• \? Question mark
• \0 Null character
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> C preprocessors (Click to know more)
https://www.geeksforgeeks.org/cc-preprocessors/
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);
}
Receiving Inputs
// Calculation of Simple Interest with user inputs
#include<stdio.h>
void main()
{
int p, n; Type declarations
float r, si; instructions
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 Arithmetic
si = p*n*r/100; Instructions
printf("Simple Interest is: \n%f", si);
}
Programming In C
Control
Statements

Objectives of these slides:


 to introduce the main kinds
of C control flow
Control Structures
 There may be situations where
the programmer requires to alter
normal flow of execution of
program or to perform the same
operation a no. of times.
 Various control statements
supported by c are-
 Decision control statements
 Loop control statements
Decision Control
 Statements
Decision control statements alter the normal
sequential execution of the statements of the
program depending upon the test condition
to be carried out at a particular point in
program.
 Decision control statements supported by c
are:-
 if statement
 if-else statement
 Else if Ladder
 Nested If
 switch statement
Decision Control Statements
 if statement
 Most simple and powerful decision control
statement.
 It executes a statement or block of statements
only if the condition is true.
 Syntax: if (condition) if (condition)
{ OR {
statement (s); statement
1;
} statement 2;
Next statement; }
statement 3;
 In above syntax : if condition is true only then
the statements within the block are executed
otherwise next statement in sequence is
executed.
/* Program to check whether a no. is even */
 Flowchart # include<stdio.h>
# include<conio.h>
void main()
False
Condition {
int num;
True
clrscr();
Block of printf(“enter the number”);
if
scanf(“%d”,&num)
Next if(num%2==0)
statement
{
STOP
printf(“\n Number is even”);
}
printf(“ End of program”);
getch();
}
if – else statement
 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 statement following if
block.
 But if specific statements are to be executed in both
cases (either condition is true or false) then if – else
statement is used.
 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 conditionFalseis false.
Test
 Syntax: if (condition) Condition
{
statement 1; True
statement 2; Block of if Block of else
}
else Next statement
{
statement 3; STOP
}
Exercise: WAP to check whether a given
no. is even or odd?
Nested if – else statement
 When an entire if-else is enclosed within the
body of if statement or/and in the body of
else statement, it is known as nested if-else
statement.
 The ways of
if representing
else nested if –else are-
if (condition1)
if
(condition1) (condition1) {
statement 1;
if (condition 3)
{ {
statement 3; else
if if else
{
(condition2) (condition2) statement 4;
} if (condition2)
statement
statement 1; 1; statement 2;

else else else


statement statement 3;
statement 2; 2;
}
If- else- if ladder
 In a program involving multiple conditions,
the nested if else statements makes the
program very difficult to write and understand
if nested more deeply.
 For this ,we use if-else-if ladder.
false
condition 1
 Syntax: if (condition1)
false
statement1; condition 2
true
else if(condition2) false
Statement 1 true condition 3
statement2;
else if(condition3) Statement 2 true

statement 3; Statement 3
else
Default statemen
default statement;
Next statement
Switch statement
 Switch is a multi-way decision making statement
which selects one of the several alternatives based
on the value of single variable or expression.
 It is mainly used to replace multiple if-else-if
statement.
 The if-else-if statement causes performance
degradation as several conditions need to be
evaluated before a particular condition is satisfied.
 Syntax: switch (expression)
{
case constant1 : statement (s); [break;]
case constant2 : statement (s); [break;]
…………………………………….
default: statement (s)
}
Break statement
 Break statement terminates the
execution of the loop in which it is
defined.
 The control is transferred
immediately to the next executable
statement after the loop.
 It is mostly used to exit early from
the loop by skipping the remaining
statements of loop or switch control
structures.
 Syntax: break;
Looping Structures
 When we want to repeat a group of
statements a no. of times, loops are used.
 These loops are executed until the
condition is true.
 When condition becomes false, control
terminates the loop and moves on to next
instruction immediately after the loop.
 Various looping structures are-
 while
 do – while
 for
LOOPING STATEMENTS
 Loop is divided into two parts:
 Body of the loop
 Control of loop

 Mainly control of loop is divided


into two parts:
 Entry Control loop (while, for)
 Exit Control loop (do-while)
while statement
 While loop is used to execute set of
statements as long as condition evaluates to
true.
 It is mostly used in those cases where the
programmer doesn’t know in advance how
many times the loop will be executed.
 Syntax: while (condition)
{ condition true statement
Statement 1 ;
Statement 2 ;
}
Statement after while loop
do- while
 do-while is similar to while except that its
test condition is evaluated at the end of the
loop instead at the beginning as in case of
while loop.
 So, in do-while the body of the loop always
executes at least once even if the test
condition evaluates to false during the first
iteration. Body of loop
 Syntax: do
true
{ Test condition
statement 1;
statement 2; false

}while (condition); Next statement


for loop
 Most versatile and popular of three loop
structures.
 Is used in those situations when a programmer

knows in advance the number of times a


statement or block will be executed.
 It contains loop control elements all at one

place while in other loops they are scattered


over the program and are difficult to
understand.
 Syntax:-

for (initialization; condition;


increment/decrement)
{
Statement( s);
}
The for is a sort of while
for (expr1; expr2; expr3)
statement;

is equivalent to:

expr1;
while (expr2) {
statement;
expr3;
}
Various other ways of writing same
for loops

i=1 for (i=1; ;i+ for


+)
for (; i<=15;i ++) (i=1;i<=15;)
{ { {
……..
……… ………….
}
if (i>15) i++;
break; }
……
}
Some Examples
for(i = 7; i <=77; i += 7)
statement;
for(i = 20; i >= 2; i -= 2)
statement;

for(j = 10; j > 20; j++)


statement;
for(j = 10; j > 0; j--)
statement;
Incrementing and Decrementing
Incrementing
 Add 1 to c by writing:
c = c + 1;

Also: c += 1;
Also: c++;
Also: ++c;
/* Preincrementing and postincrementing */

#include <stdio.h>

int main()
{
int c;

c = 5;
printf("%d\n", c);
printf("%d\n",c++); /*post increment*/
printf("%d\n\n", c);
:

continued
c = 5;
printf("%d\n", c);
printf("%d\n",++c); /*pre-increme
nt*/
printf("%d\n", c);
return 0;
}
Output:
5
5
6
5
6
6
Decrementing
 Take 1 from c by writing:
c = c - 1;

Also: c -= 1;
Also: c--;
Also: --c;
Continue statement
 Like break ,continue statement also skips the
remaining statements of the body of the loop
where it is defined but instead of terminating
the loop, the control is transferred to the
beginning of the loop for next iteration.
 The loop continues until the test condition of
the loop become false.
 Syntax: continue;

E.g. for (m=1;m<=3;m++)
{ Output:
for (n=1;n<=2;n++) 1 2
{ 2 1
if (m==n) 3 1
continue; 3 2
printf(“ m=%d n=%d”);
}
}
goto Statement
 An unconditional control statement that causes
the control to jump to a different location in the
program without checking any condition.
 It is normally used to alter the normal sequence
of program execution by transferring control to
some other part of the program.
 So it is also called jump statement.
 Syntax: goto label;
 Label represents an identifier which is used to
label the destination statement to which the
control should be transferred.
label : statement;
 The goto statement causes the control to be
shifted either in forward direction or in a
backward direction .
exit() function
 C provides a run time library function
exit() which when encountered in a
program causes the program to
terminating without executing any
statement following it.
 Syntax: exit(status);
Status is an integer variable or
constant.
 If the status is 0,then program normally
terminates without any errors.
 A non-zero status indicates abnormal
termination of the program.
 The exit() function is defined in the
process.h header file.
Difference b/w exit() & break

 Exit() is used to transfer the


control completely out of the
program whereas break is used
to transfer the control out of
the loop or switch statement.

You might also like