0% found this document useful (0 votes)
25 views59 pages

Introductory Theory

Here are the key data types in C and their characteristics: - char: Used for single characters like letters, symbols or digits. Takes 8 bits and ranges from -128 to 127. - int: Used for positive and negative whole numbers. Takes 32 bits and ranges from -2147483648 to 2147483647. - float: Used for decimal numbers. Takes 32 bits and ranges from approximately 3.4e-38 to 3.4e+38. - double: Used for decimal numbers with higher precision than float. Takes 64 bits and ranges from approximately 1.7e-308 to 1.7e+308.

Uploaded by

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

Introductory Theory

Here are the key data types in C and their characteristics: - char: Used for single characters like letters, symbols or digits. Takes 8 bits and ranges from -128 to 127. - int: Used for positive and negative whole numbers. Takes 32 bits and ranges from -2147483648 to 2147483647. - float: Used for decimal numbers. Takes 32 bits and ranges from approximately 3.4e-38 to 3.4e+38. - double: Used for decimal numbers with higher precision than float. Takes 64 bits and ranges from approximately 1.7e-308 to 1.7e+308.

Uploaded by

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

Introduction!

CSE 1111: Structured Programming Language


Charles Aunkan Gomes
Lecturer
Dept of CSE, UIU

1
Computer Programs
Computer programming is the process that professionals use to write code that
instructs how a computer, application or software program performs. At its most
basic, computer programming is a set of instructions to facilitate specific actions.

So, it -

● Tells the computer how to do/solve a specific task


● Gives Detailed step by step instructions to computers
● These instructions are easily understandable to computers.
● Just Like human languages, there are many programming languages, each
better suited for a particular type of task.
● Written (mostly) by humans.
So how do we make a computer ‘smart’?

We write in Compiler translates it


Computer
Programming to machine
executes it!
Languages executable language

IDE + C/C++ compiler


So how do we make a computer ‘smart’?

Transformed into
Our ‘logical’ step Problem to be
programming
by step solution solved
techniques!

We write in Compiler translates it


Computer
Programming to machine
executes it!
Languages executable language
So how do we make a computer ‘smart’?

Transformed into
Our ‘logical’ step Problem to be
programming
by step solution solved
techniques!

Step 2 Step 1
Use Variables, If-else, We’ll use just “steps” or Flow Charts, Pseudocodes, algorithms
loops, arrays, pointers,
functions, structures,
classes etc. Step 3

We write in
Programming
Languages
What is Computer Programming?

 Series of instructions to a computer to accomplish a task


 Instructions must be written in a way the computer can understand
 Programming languages are used to write programs
Computer Languages
 Human languages are known as
natural languages. Unfortunately,
computers do not understand natural
languages, as a result we must
communicate with computers using
computer languages.
 These languages are –
1. High Level Languages
2. Low Level Languages (Assembly
Languages)
3. Machine Language
Machine Language
 Machine code or machine language is a system of instructions and
data executed directly by a computer's CPU, The lowest-level
programming language that can only be understood by computers.
 This type of language can be executed without the need for
translation by a compiler or an assembler.
 Machine Language example – “01001110101010”
 Consists of only binary digits
 Difficult for human usage
Low Level Language
 A low-level programming language is a programming
language that provides little or no abstraction from a
computer's instruction set architecture.
 Assembly language is the best example of low level language, this is
in between machine language and high-level language.
 Low-level languages can be converted to machine code without
a compiler or interpreter
 A program written in a low-level language can be made run very
quickly
High Level Language
 A high-level programming language is a programming
language that provides strong abstractionfrom a
computer's instruction set architecture
 A programming language which is closer to human languages is
considered high-level language
 High level language must use interpreter or compiler to convert
human understandable program to computer readable code
(machine code).
 Example: C, C++, java, Pascal
Program Code Converters
 Interpreter - Interpreter converts a source code , usually on a
step-by-step, line-by-line and unit-by-unit basis into machine
code.
 Compiler - Compiler is basically a translator. It is a program that
compiles(translates) source code into executable
instructions(machine language) that a computer can understand.
 Assembler - Assembler normally converts assembly language’s
source code into machine language.
Compiler in Detail
 High Level language or
the source code is fed
into a compiler
 Compiler translates the
high level language to low
level language or machine
language
Standard Structure of a C Program
 Header File //must #include<stdio.h>
 Function 1 //optional .
 Function 2 //optional .
…………………… .
 Main Function{ //must int main(){
Main function statements printf(“Hello World”);
}
}
Main function indicates
the beginning point of
each program
Standard Structure of a C Program
#include<stdio.h>  Header File - “stdio.h” is a header file that contains
basic input/output functions. “#include” is the command
. to paste the code from the header file when necessary.
. There are other types of header files also.

.  main() is a special function used by the C system to tell the


computer where the program starts
int main(){  Every program must have exactly one main function
printf(“Hello World”); If more than one main function is used, compiler will not
understand which main function is the beginning of the program
}

printf( ) is a library function to display output which only


works if #include<stdio.h>is included at the beginning.
Simple C Program
#include<stdio.h>
 Output of the program???

int main()
{
printf(“Hello World”);
}
Simple C Program
 Output of the program???
#include<stdio.h>

int main(){
printf(“Hello World”);
 How to solve this??
printf(“Hello IPE 06”);
 We can use “\n” to print a
} new line.
Simple C Program
 Output of the program???
#include<stdio.h>

int main(){
printf(“Hello World”);
printf(“\n”);
printf(“Hello IPE 06”);
}
An Alternative of the Previous Program
 Output of the program???
#include<stdio.h>

int main(){
printf(“Hello World\n”);
printf(“Hello IPE 05”);
}
Task
1. Print “Hello World” using printf () function.
2. Print a number using printf () function.
3. Print your details in separate lines using printf() function. Your details should
contain :
i. Your name
i. Your department name
ii. Your student id
iv. your level
Keywords

 Linguistically Keyword is a word which has greater significance


 From this, we can conclude, Keywords in C are words which has some
special significant meaning (which can not be changed) in C programming.
 There are 32 keywords in C. Each of them serve a special purpose.
Identifiers
 Identifier refers to the name of variable, functions and arrays.
 It is a user defined name
 Identifier is a series of characters consisting of letters, digits and underscore
that does not begins with digits.
 Both uppercase and lowercase are permitted.
Rules for Identifiers
 An Identifier can only have alphanumeric characters(a-z , A-Z , 0-9) and
underscore(_).
 The first character of an identifier can only contain alphabet(a-z , A-Z) or
underscore (_).
 Identifiers are also case sensitive in C. For example name and Name are two
different identifiers in C.
 Keywords are not allowed to be used as Identifiers.
 No special characters, such as semicolon, whitespaces, slash or comma are
permitted to be used in or as Identifier
 Should contain maximum 31 characters
Example of Identifiers

(CSE)_
CSE_
20CSE_
CSE_KUET_
CSE KUET_
123_
CSE20_
Example of Identifiers

(CSE)_ invalid
CSE_ valid
20CSE_ invalid
CSE_MIST_ valid
CSE MIST_ invalid
123_ invalid
CSE20_ valid
Data Types
In programming everything we deal with is “Data”
There are various types of data. Like character, decimal
numbers, natural numbers etc.
There are different data types for these.
Data Types
 To visualize the need for different data types we can see an
example:
 Suppose you have 3 material : sand, water, oxygen gas and 3
containers: 1 paper box, 1 bowl and 1 cylinder. You can put one
material in one container. What will you put in which container?
Data Types
Data Types
Data type Characteristics Size (bit) Range of values Example
char Letter, 8 -128 to 127 A, $,%
symbols, digit
int Positive and 32 -2147483648 to 0, 5,-5
negative 2147483647
whole
numbers
float Dec 32 3.4e-38 to 3.4e+38 1.3

double Dec 64 1.7e- 3.1416


308to1.7e+308
Variables
 A variable is data name that may be used to store a data value.
─Variable names correspond to locations in the computer's
memory
─Every variable has a name, a type, a size and a value
─Whenever a new value is placed into a variable, it replaces (and
destroys) the previous value
─Variable must be declared before it is used
– Variable declaration Format:
i. data_type variable_name;
ii. data_type variable1_name, variable2_name, variable3_name;
Variables
 Initializing to variables : initializing variables means assigning a
value to the variable.
Syntax: data_type variable_name=constant/literal/expression;
or
variable_name=constant/literal/expression;
Example: int a = 5; [the variable a hold the value 5]
double a= 5.5;
Format Specifiers in C
 The format specifier is used during taking input from
an user and showing output.
 It is a way to tell the compiler what type of data is in a
variable during taking input using scanf() or printing
using printf().
Data Type Format Specifier Use
int %d To input/output integer value
float %f To input/output fractional value
double %lf To input/output fractional value
char %c To input/output character
Example: Printing Integer Value
#include<stdio.h>
 Output:
int main()

{
15
int var;
Result is 15.
var = 7 + 8;
printf(“%d”, var);
printf(“\nResult is %d.”, var);
}
Example: Printing float Value
#include<stdio.h>
int main()  Output:
{
float operand1, operand2, result;
Result of the addition operation is 5.2
operand1 = 2.1;
operand2 = 3.1;
result = operand1 + operand2;
printf(“\nResult of the addition
operation is %f”, result );
}
Example: Printing char Value
#include<stdio.h>
int main()  Output:
{
char var;
A
var= ‘A’;
printf(“\n%c”, var);
}
ASCII Table
Example: Printing char Value
#include<stdio.h>
int main()  Output:
{
char var;
A
var= ‘A’;
printf(“\n%c”, var); 65
printf(“\n%d”, var);
}
Example: Taking Input and Printing float Value
#include<stdio.h>
int main() {  Ampersand sign = &
float operand1, operand2, result;
scanf(“%f”,&operand1 ); An alternative can be:
scanf(“%f%f”,&operand1 , &operand2 );
scanf(“%f”,&operand2 );
result = operand1 + operand2;
printf(“\nResult of the addition of %f and %f is %f”, operand1, operand2,result );

}
Why ampersand is used in scanf() function but not
in printf() function?
#include<st
dio.h> int
main() {  Ampersand sign = &
float operand1, operand2, result;
scanf(“%f”,&operand1 );  The scanf function expects to receive in the
scanf(“%f”,&operand2 ); address of our variable. It can
result = operand1 + then store the value into our variable. & sign
operand2; indicates the address of the variable
printf(“\nResult of the addition
 The printf function directly prints the value stored in
of
the variable. It does not need to print value from
%f and %f is %f”, result );
the variables address
}
More with Format Specifier
#include<stdio.h>
int main() {  Output:
float var=1.3143547; 1.3143547
printf(“\n%f”, var);
1.31
printf(“\n%.2f”, var);

}
Prints upto 2 decimal point
More with Format Specifier
#include<stdio.h>
int main() {  Output:
float var=1.3153547; 1.3153547
printf(“\n%f”, var);
1.32
printf(“\n%.2f”, var);

}
Prints upto 2 decimal point
More with Format Specifier
#include<stdio.h>
int main() {  Output?
float var=1.3153547; 1.3153547
printf(“\n%f”, var);
1.315
printf(“\n%.3f”, var);

}
Rounds the value and Prints upto 3
decimal point
Task
 Take input of an integer number and print it
 Take input of 3 integer numbers and print the sum of them
Take input of 2 integer numbers and calculate the sum,
subtraction, multiplication of them. Print each of them in new
lines.
 Take input of 1 integer and 1 float number. Print the sum of them
Take input of 5 integer numbers , calculate their average and
print the average result
 Take a character input and print its corresponding ASCII value.
71
Example 1- A Simple Conversation
Let’s write a program (a chatbot) to have a simple conversation
with the user. In time, we’ll make more of a ‘intelligent’ chatbot!

Check out the solution in Hello_IPE.c


What we learnt
1. W riting a simple program in c.
2. What header files are (stdio.h in our program)
3. How to use printf().
4. How to use scanf().
5. Some basic idea on how to store an input and show it.
6. Making a little chatbot program in C!
Example 2 - Age Calculator
Make a Age Calculator that takes the birth year as input from
the user and tells them how old they’ll be in a particular year!

Input (To be taken from users) Output

Enter The year you were born: 1999 You’ll be 56 years old in 2055.
Enter the year to calculate your age in: 2055

Check out the solution in age_calculator.c


Example 2 - Age Calculator

Here’s what the output should look like:


Example 2 - Age Calculator

Let’s try out the steps for writing programs!

Step 1 Step 2

Ask the user when he/she was born printf()

Store their answer (in birth_year) scanf() + use an int variable

Ask and store the year he/she wants to printf() + scanf() + use an int variable
calculate the age in (in calc_year)

Do calc_year - birth_year to find age Arithmetic operation (-)

Show them the result! printf()


Example 3 - Simple Interest
Make a simple interest calculator for bank accounts that takes
the principal, interest rate and time as input and finds the
interest accordingly.

Check out the solution in simple_interest.c


Example 3 - Simple Interest

Let’s try out the steps for writing programs!

Step 1 Step 2

Ask and store the principal amount printf() + scanf() + use an int variable

Ask and store the interest rate printf() + scanf() + use another int variable

Ask and store the time printf() + scanf() + use an int variable

Do (principal * rate * time) / 100.0 to find Arithmetic operation + store in an int variable
simple interest

Show the result! printf()


Example 4 - Worker’s Salary
Let’s calculate a garment (or any) worker’s salary calculator. Takes in daily rate and days
worked, then calculates monthly salary. Then also takes in overtime hourly rate and hours
worked to find salary with overtime.

Check out the solution in intro_salary.c


Example 4 - Worker’s Salary

Let’s try out the steps for writing programs!

Step 1 Step 2

Ask and store the basic daily salary printf() + scanf() + use a float variable

Ask and store how many days the worker printf() + scanf() + use an int variable
worded last month

Calculate the Basic salary and show Arithmetic operation + printf()

Ask and store overtime hours worked by the printf() + scanf() + use an float variable
worker last month

Ask and store overtime rate per hour printf() + scanf() + store in a float variable

Calculate the OT salary (basic + overtime Arithmetic operation + printf()


salary) and show.
Example 5 - Typecasting
Let’s try to divide one integer number by another (i.e 27/5) and try to
store the result in a float variable. Would we be alright without
typecasting?

Check out the solution in typecasting_example.c


Example 5 - Typecasting

Let’s try out the steps for writing programs!

Step 1 Step 2

Ask and store the num1(dividend) printf() + scanf() + use a int variable

Ask and store the num 2 (divisor) printf() + scanf() + use an int variable

Calculate the quotient Arithmetic operation (a/b)

But we need to convert to float since the Have to Use typecasting!


result of division of two integers may be
decimal!

Show the result of div (quotient) printf()


Example 6 - A Gold Shop!
Let’s make a program that calculates the price of a gold ornament to be purchased by the
customer. It takes input of purchased amount of gold, today’s rate/bhori and discount rate. Then,
Vat (15%) and the entered discount to be given to the customer. Final price should also be “floored”
to the nearest hundredth value. Also, one tk per purchase to be donated.
Example 6 - A Gold Shop!
Step 1 Step 2

Take input of the daily gold rate (per bhori) and printf() + scanf() + use float variables
today’s discount rate

Take input from shopkeeper how much gold bought printf() + scanf() + use a float variable
(in bhori)

Calculate the raw price Arithmetic operation (gold_rate*weight_bought)

Give discount according to rate Arithmetic operation + typecasting

Add 15% VAT, donate 1 tk Arithmetic operation

Show the actual price printf()

Calculate and show the price for the customer Explicit typecasting + Arithmetic operation + printf()
(discard all paisas, floor to nearest 100!)
Escape Sequences for printf()
Escape Sequence What it does

\n Prints a new line. More specifically, moves the cursor to a new line.

\t Moves the cursor one tab to the right.

\r Moves the cursor to the beginning of the current line. Then whatever you write after \r
will overwrite the previous characters. This is called carriage return.

\b moves the cursor back one space. Then whatever you write overwrites what you had in
that space. However, it can’t go back to a previous line.

\a Doesn’t move the cursor. Just makes a “beep” or windows “alert” sound for that line.

\ Put \ before any of the above escape sequences from above if you want to print the
escape sequence itself rather than to move the cursor.

%% However, if you want to print % itself just put another % before that. Putting \ before %
won’t work.

Note: Escape characters take effect within that printf() (that line) only.
A Simple Task For Practice
Calculate the area of geometric shapes (circle, rectangle, square, triangle). Write separate
programs for each shape’s area calculation.

Do yourself for practice. Will solve in class next week

You might also like