Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views95 pages

01a Introduction

The document provides an introduction to a course on Programming and Data Structures (PDS) using the C programming language. It covers the basics of writing programs, the structure of C programs, data representation in binary, and fundamental concepts such as variables, constants, and flowcharts for problem-solving. Additionally, it discusses the history of C, its applications, and the importance of understanding the C character set and tokens.

Uploaded by

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

01a Introduction

The document provides an introduction to a course on Programming and Data Structures (PDS) using the C programming language. It covers the basics of writing programs, the structure of C programs, data representation in binary, and fundamental concepts such as variables, constants, and flowcharts for problem-solving. Additionally, it discusses the history of C, its applications, and the importance of understanding the C character set and tokens.

Uploaded by

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

INTRODUCTION

C PROGRAMMING AND DATA STRUCTURES


What is this course?
PDS: Programming and Data structure
• Basically we will learn how to write programs
• Programs? Set of instructions written for a computer. Tell it what to
do
What is this course?
PDS: Programming and Data structure
• Basically we will learn how to write programs
• Programs? Set of instructions written for a computer. Tell it what to
do
What is this course?
PDS: Programming and Data structure
• Basically we will learn how to write programs
• Programs? Set of instructions written for a computer. Tell it what to
do
Super powers of computer

• This machine can do some tasks blazingly


fast, tirelessly
• Thousands of complex mathematical
operations in a second

• But…
• You need to speak its language
• Tell computers exactly what operations to
do, step by step
• Programming…
Three steps in writing programs
Step 1: Write the program in a high-level language (HLL - in your
case, C) Step 2: Compile the program using a C compiler
Step 3: Run / execute the program (ask the computer to execute it)

HLL
program Executable
Compiler code
But, you can use instructions written by others: Libraries

Libraries: Pre-written instructions for complicated tasks


You can include these library names in your program and use their
functionalities Don’t need to write those instructions yourself
Executable
HLL program
code
with
Compiler Object code Linker
Library
name
Library

gcc compiler will be used in the lab classes


This executable code is in binary
Computer understands only numbers, in binary
(0 and 1)
Binary Representation

The decimal number system we use is base 10


• 10 digits, from 0 to 9, Positional weights 100, 101, 102,…from right to left for
integers
• Example: 723 = 3x100 + 2x101 + 7x102

Numbers are represented inside computers in the base-2 system (Binary Numbers)
• Only two symbols/digits 0 and 1
• Positional weights of digits: 20, 21, 22,…from right to left for integers
• Example: 1101 in binary = (1 x 20) + (0 x 21) + (1 x 22) + (1 x 23) = 13 in
decimal
Bits and Bytes
• Bit – a single 1 or 0

• Byte – 8 consecutive bits


•2 bytes = 16 bits
• 4 bytes = 32 bits

• Maximum integer that can represented


• in 1 byte = 255 (=11111111)
• In 4 bytes = 4294967295 (= 32 1’s)

• Number of integers that can be represented in 1 byte = 256 (the integers 0, 1, 2, 3,


….255)
Problem Solving
(the thought
process)
Problem solving: typical flow

Step 1:
•Clearly specify the problem to be
solved. Step 2:
•Draw flowchart or write algorithm (represent the sequence of operations
needed). Step 3:
•Convert flowchart (algorithm) into program
code. Step 4:
•Compile the program to get executable
code. Step 5:
• Execute the program on a computer.
Flowchart: represent the sequence of operations as a
diagram
Computation

Input / Output

Decision Box

Start / Stop

Flow of control

Connector
Flowchart: Example 1: adding three numbers

START

READ A, B,
C

S=A+B+C

OUTPUT S

STOP
Flowchart: Example 2: find larger of two numbers

START

READ X, Y

YES IS
NO
X>Y?

OUTPUT X OUTPUT Y

STOP STOP
Flowchart: Example 3: sum first N integers

START

READ N

SUM = 0
COUNT = 1

SUM = SUM + COUNT

COUNT = COUNT + 1

NO IS YES
COUNT > N? OUTPUT SUM

STOP
Flowchart: Example 4: compute factorial of a number

START

READ N

PROD = 1
COUNT = 1

PROD = PROD * COUNT

COUNT = COUNT + 1

NO IS YES
OUTPUT PROD
COUNT > N?

STOP
Fundamentals of
C
Why do we use C?

C language is used to create applications or


software.

Initially, C was developed to create an


operating system called UNIX.

The popular software like Linux OS, PHP &


MySQL are created using C language.
2
Why do we use C?

Generally C Language is used to create the


following…
Operating Systems
Language
Compilers
Assemblers
Interpreters
Text Editors
Network Drivers 3
History of C Language?
Let’s see the programming languages that were developed
before C language…

CPL – Common Programming Language


invented by Martin Richards in 1960’s
BCPL – Basic Combined Programming Ken Thompson
Language by Martin Richards in 1966
B Language – by Ken Thompson & Dennis
Ritchie in 1969
Traditional C – by Dennis Ritchie in 1972
K&R C – by Kernighan & Dennis Ritchie in
Dennis Ritchie
1978
ANSI C – by ANSI Committee in 1989
ANSI/ISO C – by ISO Committee in 1990
4
C99 – by Standardization Committee in
History of C Language?
C Language was developed by Dennis Ritchie
in the year of 1972.
Born – September 9, 1941
Profession – Computer Scientist
Place – Bell Labs, US
Known As – Father of C & UNIX
Awards – Turing Award(1983)
National Medal of Technology(1998)
IEEE Medal(1990)
Dennis Ritchie
Computer Pioneer Award(1994)
Computer History Museum Fellow(1997)
Harold Pender Award(2003)
Died – October 12, 2011
4
First C program – print on screen

#include <stdio.h>
int main()
Outpu
{ t
Hello, World!
printf ("Hello, World! \n") ;
return 0;
}
Basic Structure of C Program
Structure of C Program

Documentation Section:
This section includes comments (/* ... */ for multi-line or // for single-line) that
explain the program's purpose, author, date, and any other relevant
information. The compiler ignores these comments.

Preprocessor Directives/Link Section:


This section contains instructions for the preprocessor, such as #include directives
to link system library functions (e.g., <stdio.h> for standard input/output)
and #define directives for defining constants or macros.

Definition Section:
This section is used for defining user-defined data types (like structures
using struct), enumerations (enum), or global constants using #define if not already
handled in the preprocessor directives.
Global Declaration Section:
This section declares global variables and functions that are accessible throughout
the entire program.

main() Function Section:


This is the entry point of every C program. Execution begins here. It typically
contains:
Declaration Part: Local variables used within the main() function are declared.
Execution Part: Contains the statements and expressions that perform the
program's operations.

Subprogram/Functions Section:
This section contains user-defined functions (subprograms) that are called from
the main() function or other functions within the program. These functions perform
specific tasks and can accept arguments and return values.
A Simple C program
#include <stdio.h>
int main()
When you run the
{ program
int x, y, sum, max;
scanf(“%d%d”, &x, &y);
sum = x + y;
if (x > y) max = x;
else Output after you type 15 and
20
printf (“Sum = %d\n”, sum); 15 20
max = y; Sum = 35
printf (“Larger = %d\n”, max);
Larger = 20
return 0;
}
Things you will see in a C
program (we will look at all these
one by one)
• Variables
• Constants
• Expressions (Arithmetic, Logical, Assignment)
• Statements (Declaration, Assignment, Control (Conditional/Branching,
Looping))
• Arrays
• Functions
• Structures
• Pointers
The C Character Set
The C language alphabet
• Uppercase letters ‘A’ to
‘Z’
• Lowercase letters ‘a’ to
‘z’
• Digits ‘0’ to ‘9’
!
• Certain special # % ^ & * ( )
characters:– _ + = ~ [ ] \
| ; : ‘ “ { } ,
. < > / ?
whitespace characters (space, tab,
…)

A C program should not contain anything else


C TOKENS:

The smallest individual units are known as tokens. C has six types of tokens.

1. Identifier
2. Keywords
3. Constants
4. Strings
5. Special Symbols
6. Operators
Identifiers:
Identifiers refer to the names of variables, constants, functions and arrays. These are user-defined
names is called Identifiers. These identifier are defined against a set of rules.
Rules for an Identifier
1.An Identifier can only have alphanumeric characters( a-z , A-Z , 0-9 ) and underscore( _ ).
2. The first character of an identifier can only contain alphabet( a-z , A-Z ) or underscore ( _ ).
3. Identifiers are also case sensitive in C. For example name and Name are two different identifier in C.
4. Keywords are not allowed to be used as Identifiers.
5. No special characters, such as semicolon, period, whitespaces, slash or comma are permitted to
be used in or as Identifier.
6. C‟ compiler recognizes only the first 31 characters of an identifiers.
Example
Keywords:
A keyword is a reserved word.
Keywords serve as basic building blocks for program statements.
All keywords must be written in lowercase.
A list of 32 keywords in c language is given below:
Constants

Constants refer to fixed values that do not change during the execution of a
program.
TYPES OF C CONSTANT:

1. Integer constants
2. Real or Floating point constants
3. Character constants
4. String constants
5. Backslash character constants
Integer constants:

An 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)
1: Decimal Integer : the rules for represent decimal
integer.

a) Decimal Integer value which consist of digits from 0-9.


b) Decimal Integer value with base 10.
c) Decimal Integer should not prefix with 0.
d) It allows only sign (+,-).
e) No special character allowed in this integer.
2 : Octal : These rules are :

An integer constants with base 8 is called octal.


a) it consist of digits from 0 to 7.
b) It should prefix with 0.
c) It allows sign (+,-).
d) No special character is allowed.
3 : Hexadecimal : rules are

An integer constant with base value 16 is called Hexadecimal.


a) It consist of digits from 0-9,a-f(capital letters & small letters.
Ex : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
b) it should prefix with 0X or 0x.
c) it allows sign (+,-).
d) No special character is allowed.
EX : OX1a, ox2f
Floating point/Real 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
Real constant is base 10 number, which is represented in decimal 0r
scientific/exponential notation.
Real Notation : The real notation is represented by an integer followed by a
decimal point and the fractional(decimal) part. It is possible to omit digits before
or after the decimal point.
Ex : 15.25 .75 30 -9.52 -92 +.94
Scientific/Exponential Notation: The general form of Scientific/Exponential
notation is
mantissa e exponent
The mantissa is either a real/floating point number expressed in decimal
notation or an integer and the exponent is an integer number with an optional
sign. The character e separating the mantissa and the exponent can be written
in either lowercase or uppercase.
Ex : 1.5E-2 100e+3 -2.05e2
Valid or Invalid?
Character Constant:
Single Character Constant : A character constant is either a single
alphabet, a single digit, a single special symbol enclosed within single
inverted commas.
a) it is value represent in ‘ ‘ (single quote).
b) The maximum length of a character constant can be 1 character.
EX : VALID ‘a’ ‘A’ ‘5’ ‘:’ ‘ ‘
INVALID “12” “ab‟

String constant : A string constant is a sequence of characters enclosed in


double quote, the characters may be letters, numbers, special characters and
blank space etc
"good“ //string constant
“" //null string constant
“ “ //string constant of six white space
"x" //string constant having single character.
"Earth is round\n“ //prints string with newline
Escape characters or backslash characters:
Two ways to define constant in C
1. const keyword 2. #define preprocessor

1) const keyword
The const keyword is used to define constant in C programming.
1. const float PI=3.14;

2) #define preprocessor
The #define preprocessor directive is used to define constant or
micro substitution. It can use any basic data type.
Syntax:
#define token value
Variables
• Very important concept for programming
• Can store any temporary result while executing a program
• Can have only one value assigned to it at any given time
• The value of a variable can be changed during the execution of the
program
• Variables are stored in the computer’s memory
• Memory is a list of consecutive storage locations,
0
each having a unique address
1
• Four aspects of a variable:
2
• The value stored in the variable
3
• The type of the variable – decides what type of
value can be stored (integer, real, etc.)
• The variable name is used to refer to the value of
the variable
• A variable is stored at a particular location of N–
2
the memory, called its address
N–
1
MEMORY
Example

#include <stdio.h>
int main( )
{
int x;
int y;
The = sign in a C program does NOT denote
equality
x=1;
y=3; We are actually assigning a value to a
variable, i.e., storing a particular value into
printf("x = %d, y= %d\n",
thex, y);
variable

return 0;
}
Variables in Memory

Instruction sequence Memory


int X
X=
10 (may contain
X ? whatever value at the
X=
20 beginning)

X = X +1

X = X*5

A variable can have only one value assigned


to it at any given time during the execution
of the program
Variables in Memory

Instruction sequence Memory

X=
after executing X =
10 10
X 10
X=
20

X = X +1

X = X*5

A variable can have only one value assigned


to it at any given time during the execution
of the program
Variables in Memory

Instruction sequence Memory

X=
10
uting X = 20 X 20
ec
X= after ex
20

X=X
+1

X=
X*5 A variable can have only one value assigned
to it at
any given time during the execution of the
Variables in Memory

Instruction sequence Memory

X=
10
X 21
X= X +1
X=
20 i
ecut
ng
r ex
afte
X=X+
1

X=X*
5 A variable can have only one value assigned
to it at
any given time during the execution of the
Variables in Memory

Instruction sequence Memory

X=
10
X 105
X=
20 *
= X
X
X=X+ uting
exec
1 r
afte
5

X=X*
5 A variable can have only one value assigned
to it at
any given time during the execution of the
Variables in Memory

Instruction sequence Memory

X=
20
? (may contain
X whatever value at the
Y=
15 beginning)

? (may contain
X=Y+ Y whatever value at the
3 beginning)

Y=X/
6
Variables in Memory

Instruction sequence Memory

X=
after executing X =
20 20
X 20
Y=
15

X=Y+ Y ?
3

Y=X/
6
Variables in Memory

Instruction sequence Memory

X=
20
X 20
Y=
15 after execu
ting Y = 15

X=Y+ Y 15
3

Y=X/
6
Variables in Memory

Instruction sequence Memory

X=
20
X 18
Y=
15
3
X=Y+ fter executing X = Y + Y 15
a
3

Y=X/6

Note: Y does not change, only X changes


after execution of this instruction
Variables in Memory

Instruction sequence Memory

X=
20
X 18
Y=
15

X=Y+ Y 3
= X/6
3 tn
i gY
cu
ter exe
af
Y=X/
6
Rules and good practices

• First rule of variable use: Must declare a variable (specify its type and name) before
using it anywhere in your program

• All variable declarations should ideally be at the beginning of the main( ) or


other functions
• There are exceptions, we will see later

• A value can also be assigned to a variable at the time the variable is


declared.
int speed =
Initialization of a
30; char variable
flag = ‘y’;
Declaration of Variables :
Syntax : data_type variable-1,variable-2,------, variable-n;
Variables are separated by commas and declaration statement ends with a
semicolon.
Ex : int x,y,z;
float a,b;
char m,n;
Assigning values to variables : values can be assigned to variables
using the assignment operator (=).
Syntax : variable = constant;
Ex : x=100;
a= 12.25;
m=‟f‟;
Assign a value to a variable at the time of the variable declaration:
Syntax : data_type variable = constant;
Ex ; int x=100;
float a=12.25;
char m=‟f‟;
Types of Variables in C

1. local variable
2. global variable
3. static variable
Variable Names
• Sequence of letters and digits
• First character must be a letter or ‘_’
• No special characters other than ‘_’
• No blank in between
• Names are case-sensitive (max and Max are two different
names)
• Examples of valid names:
i rank1 MAX class_ran _Average
max Min k

• Examples of invalid
a’s fact names:
rec 2sqroot
class,rank
More Valid and Invalid Names (Identifiers)

Valid identifiers Invalid


X identifiers
abc
10abc
simple_interest
my-name
a123
“hello”
LIST simple
stud_name interest
Empl_1 (area)
Empl_2 %rate
_avg_empl_s
alary
Data Types

• Each variable has a type, indicates what type of values the variable can
hold

• Four common data types in C (there are others)


• int -can store integers (usually 4 bytes)
• float - can store single-precision floating point numbers (usually 4
bytes)
• double - can store double-precision floating point numbers (usually 8
bytes)
• char - can store a character (1 byte)
Data Types/Types:

A datatype is a keyword/predefined instruction used for allocating memory for data.


A data type specifies the type of data that a variable can store such as integer, floating, character
etc.
It used for declaring/defining variables or functions of different types before to use in a program.
Size and Range of Data types:
With Control String:
User-Defined Type Declaration
1. Type Definition – Allows users to define an identifier to represent existing
dsta type. Syntax:

Ex.

2. Enumerated data type: Syntax

Ex : Note: compiler
automatically assigns
integer digits
beginning with 0.
can also be overridden by
Input / Output (I/O) Functions :

Two types of Input/Output functions


All input and output operations are carried out through function
calls
Functions are collectively known as the standard i/o library.
Input: In any programming language input means to feed some data
into program. This can be given in the form of file or from command
line.
Output: In any programming language output means to display
some data on screen, printer or in any file.
The Standard Files
C programming treats all the devices as files.
following three files are automatically opened when a program executes to
provide access to the keyboard and screen.
I/O Functions
Formated I/O Functions :
refers to the ability to control how data is entered and displayed in a structured way.
Input (reading from standard input, e.g., keyboard):

scanf(“control_string", &variable1, &variable2, ...);


Each variable name (argument) must be preceeded by an ampersand (&). The
(&) symbol gives the meaning “address of “ the variable

Output (writing to standard output, e.g., console):

printf(“control_string", variable1, variable2, ...);

it prints all the character given in doublequotes (“ “) except formatting


specifier
Ex : printf(“ hello “);-> hello
printf(“a”); -> a
printf(“%d”, a); -> a value
Unformatted I/O functions:
a) character I/O:
1. getchar(): Used to read a character from the standard input
2. putchar(): Used to display a character to standard output
3. getch() and getche(): these are used to take the any alpha numeric
characters from the standard input
getche() read and display the character
getch() only read the single character but not display
4. putch(): Used to display any alpha numeric characters to standard output

a) String I/O:
1. gets(): Used for accepting any string from the standard input(stdin)
eg:gets()
2. puts(): Used to display a string or character array Eg:puts()
3. Cgets():read a string from the console eg; cgets(char *st)
4. Cputs():display the string to the console eg; cputs(char *st)
Example 1
#include <stdio.h>
int main()
{
int x, y,
sum; Three integer type variables
declared
scanf (“%d%d”, &x, &y);
sum = x + y;
Values assigned

printf( “%d plus %d is


%d\n”, 15 23
x, y, 15 plus 23 is 38
sum );
return 0;
}
Example
2
#include <stdio.h>
int main()
{
float x, y; /* Two floating point variables declared */
int d1, d2 = 10; /* Integer variable d2 is initialized to 10
*/

scanf(“%f%f%d”,&x, &y, &d1);


printf( “%f plus %f is %f\n”, x, y, x + y);
printf( “%d minus %d is %d\n”, d1, d2, d1 – d2);
return 0;
}
Input: scanf function
• Performs input from keyboard
• It requires a format string and a list of variables into which the value received
from the keyboard will be stored
• format string = individual groups of characters (usually ‘%’ sign, followed by a
conversion character), with one character group for each variable in the list

int a, Commonly used conversion


characters
c. for char type variable
b; float
c; Variable list (note the &
d. for int type variable
before each variable name)
f for float type variable
scanf( “%d%d%f”, &a, &b, &c); lf for double type
Format string variable
Examples
scanf ("%d", &size) ;
• Reads one integer from keyboard into an int type variable named size

scanf ("%c", &nextchar) ;


• Reads one character from keyboard into a char type variable named nextchar

scanf ("%f", &length) ;


• Readsone floating point (real) number from keyboard into a float type variable
named length

scanf (“%d%d”, &a, &b);


• Reads two integers from keyboard, the first one in an int type variable named a
and the second one in an int type variable named b
Important

• scanf( ) will wait for you to type the input from the keyboard

• You must type the same number of inputs as the number of %’s in the format string

• Example: if you have scanf (“%d%d”,…), then you must type two integers (in same
line or different lines), otherwise scanf( ) will just wait and the next statement
will not be executed
Reading a single character

• A single character can be read using scanf with %c

• It can also be read using the getchar() function


char c;

c = getchar();

• Program waits at the getchar() line until a character is typed, and then reads it and
stores it in c
Output: printf function
• Performs output to the standard output device (typically defined to be the
screen)

• It requires a format string in which we can specify:


• The text to be printed out
• Specifications on how to print the
values printf ("The number is %d\n",
num);

• Theformat specification %d causes the value listed after the format string
to be embedded in the output as a decimal number in place of %d

• Output will appear as: The number is 125


General syntax of printf( )
printf (format string, arg1, arg2, …, argn);

• format string refers to a string containing formatting information and data types
of the arguments to be output
• the arguments arg1, arg2, … represent list of variables/expressions whose values are
to be printed
• The conversion characters are the same as in scanf

• Examples:
printf (“Average of %d and %d is %f”, a, b,
avg); printf (“Hello \nGood \nMorning \n”);
printf (“%3d %3d %5d”, a, b,
a*b+2); printf (“%7.2f %5.1f”, x,
y);
• Many more options are available for
More Examples
(Explain the outputs to test if you understood format strings
etc.)
More point

#include <stdio.h> Output


int main()
Hello, World!
Hello World!
{
printf ("Hello, World! ") ;
printf ("Hello \n World! \n") ;
return 0;
}
Some more point

Output
#include <stdio.h>
Hello,
int main() World!
{ Hello
printf ("Hello, World! \n") ; World!
printf ("Hello \n World! \n") ; Hell
printf ("Hell\no \t World! \n") ;
o
World!
return 0;
}
Some more
point Output
Enter values for f1 and f2:
#include <stdio.h>
23.5 14.326
int main() Enter values for x1 and x2:
54 7
{
f1 = 23.500000, f2 = 14.33
float f1, f2; x1 = 54, x2 = 7
int x1, x2;
printf(“Enter values for f1 and f2: \n”); Can you explain why
scanf(“%f%f”, &f1, &f2); 14.326 got printed as
14.33?
printf(“Enter values for x1 and x2: \n”);
scanf(“%d%d”, &x1, &x2);

printf(“f1 = %f, f2 = %5.2f\n”, f1,


f2); printf(“x1 = %d, x2 = %10d\n”, x1,
x2); return 0;
}
Practice Problems
Write C programs to
1. Read two integers and two floating point numbers, each in a separate scanf() statement (so 4
scanf’s) and print them with separate printf statements (4 printf’s) with some nice message

2. Repeat 1, but now read all of them in a single scanf statement and print them in a
single printf statement

3. Repeat 1 and 2 with other data types like double and char

4. Repeat 1 and 2, but now print all real numbers with only 3 digits after the decimal point

5. Read 4 integers in a single scanf statement, and print them (using a single printf statement) in
separate lines such that the last digit of each integer is exactly 10 spaces away from the
beginning of the line it is printed in (the 9 spaces before will be occupied by blanks or other digits
of the integer). Remember that different integers can have different number of digits

6. Repeat 5, but now the first integer of each integer should be exactly 8 spaces away from the
beginning of the line it is printed in.
OPERATORS AND EXPRESSIONS:
Operators : An operator is a Symbol that performs an operation. An
operators acts some variables are called operands to get the desired result.
Ex : a+b;
Where a,b are operands and + is the operator.

Types of Operator :
1) Arithmetic Operators.
2) Relational Operators.
3) Logical Operators.
4) Assignment Operators.
5). Unary Operators.
6) Conditional Operators.
7) Special Operators.
8) Bitwise Operators.
9) Shift Operators.

You might also like