0% found this document useful (0 votes)
4 views86 pages

4. Basic Programming Structures

The document provides an overview of the C programming language, covering fundamental concepts such as the structure of a C program, data types, variables, and input/output operations. It emphasizes the importance of C for building programming skills and understanding computer operations, while also discussing programming language hierarchies and type conversions. Additionally, it outlines rules for identifiers and keywords, as well as the advantages and disadvantages of type conversions in C.
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)
4 views86 pages

4. Basic Programming Structures

The document provides an overview of the C programming language, covering fundamental concepts such as the structure of a C program, data types, variables, and input/output operations. It emphasizes the importance of C for building programming skills and understanding computer operations, while also discussing programming language hierarchies and type conversions. Additionally, it outlines rules for identifiers and keywords, as well as the advantages and disadvantages of type conversions in C.
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

CSE-291

Course Title: Computer Programming

1
Contents

❑ Basic Body of C Program

❑ Data types and their memory allocation

❑ Operators

❑ Basic Input/ Output

2
What is programming?
A set of instructions
followed sequentially
to automate
a task that is redundant, repetitive, tedious, has patterns
to complete it efficiently.

3
What will we learn?

4
5

C and C++
Why C programming
language?

6
7

C programming language

❑ Builds strong programming fundamentals

❑ Helps you understand how computers work

❑ Base of many modern languages


8

All Programming Languages


are basically the same
9

Programming is like playing


chess.

The rules may seem simple, but it


takes practice to truly master it
and play around with it.
Programming Language Hierarchy

Wake Up at 8 AM Human Natural Language Greater the language


English, Bangla abstraction, more easier
If(time == 0800) for humans to
High Level Language understand.
Programming { print(“wake up”); }
language C, C++, Python, Java
JMP 4H Low Level Language
OUT WRD ... Assembly
But less
0011 0100 Machine Language understandable to
1001 0110 ..... Binary computers.

Presence or Computer Hardware


absence of voltage Electric Current Flow
10
Programming Language Hierarchy

❑ Human languages are broad and do not follow a specific syntax


or way of writing.
❑ Computers thus do not understand human language.
❑ Thus computer programming languages need to be written in a
specific way understandable to them.

11
Programming Language Hierarchy

▪ High level languages are more understandable by humans.


▪ High level languages require a compiler.
▪ Compiler translates the high level language to low level
language or binary.
▪ Low level languages can be converted to machine code (binary)
without a compiler.

12
Structured Programming Language
A structured programming language is one that uses control
structures in order to make the program easier to understand, read,
and maintain.
Control structures can be- A
• A sequential set of tasks.
For eg, Execute the instruction A,B,C in this specific order. B
C ?
• A selective set of conditions.
For eg, Either execute instruction A or instruction B based on a condition.
A B
• A repetitive loop. A
For eg, Repeatedly execute instructions A,B,C 50 times. B x50

C 13
Basic Body of C Program

#include<stdio.h>

int main(){
/// Your Code Here
}

14
Basic Body of C Program

15
Basic Body of C Program

#include<stdio.h>
.
.
.
int main(){
printf(“Hello World”);
}
Console/Terminal/Output Window
16
printf Statement

printf ( “Hello BME Department” );

17
printf With Newline

18
Other Special Characters

19
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.

20
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.

21
Identifier Naming Rules
▪ 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. Two Identifiers with same name are not
allowed.
▪ 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 22
Identifier Examples

_BME
BME11
11BME
BME_11
(BME11)
1234
BME+11

23
Identifier Examples

➢ _BME - Correct
➢ BME11 - Correct
➢ 11BME - Incorrect
➢ BME_11 - Correct
➢ (BME11) - Incorrect
➢ 1234 - Incorrect
➢ BME+11 - Incorrect

24
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


25
Variables - Declaration Syntax

26
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;

27
Variable Declaration and Assignment

28
Variable Declaration and Assignment
Common Mistakes

29
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.

30
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?

31
Data Types

32
Data Types Different Types
Data Type Characteristic Size Format
Values Range Examples
Keywords s (bytes) Specifiers

-2147483648 to
int 4 %d 0, 5, -15
Positive and 2147483647
negative whole 343597383
long long int numbers 8 -(2^63) to (2^63)-1 %lld 68 (i.e.
2^35)
Upto 7 digits after
float 4 %f 1.25
Decimal/Fractio radical point
nal numbers Upto 15-16 digits
double 8 %lf 3.1416….
after radical point

Letters, ASCII Chart ‘A’, ‘b’, ‘9’


char 1 %c 33
symbols, digits Characters etc.
ASCII Chart American Standard Code for Information Interchange

34
ASCII Chart - An interesting detail

The difference between numbers assigned to the small case


and the large case of the same letter in the ASCII chart is 32.
Example:

35
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
36
Outputting Variable Syntax
and Format Specifiers….

declaring the variable

This is where the value in the variable giving the variable


gets pasted - a format specifier to printf
37
Outputting Variable Syntax

Notice the single quotation ‘

38
Outputting Variable Syntax

39
Effect of using incorrect format specifiers

#include<stdio.h>
int main()
{ ▪ Output:
char var;
var= ‘A’;
printf(“\n%c”, var); A
printf(“\n%d”, var); 65
}

40
Effect of using incorrect format specifiers

#include<stdio.h> ▪ Output:
int main()
{
int var;
var= 1.3; 1
printf(“\n%d”, var);
}

This is implicit typecasting

41
Type Conversion in C

● Type conversion in C is the process of converting one data type to another.


● The type conversion is only performed to those data types where conversion is
possible.
● Type conversion is performed by a compiler. In type conversion, the destination
data type can’t be smaller than the source data type.
● Type conversion is done at compile time and it is also called widening conversion
because the destination data type can’t be smaller than the source data type.
● There are two types of Conversion:
○ 1. Implicit Type Conversion
○ 2. Explicit Type Conversion

42
1. Implicit Type Conversion (1/2)

• Also known as ‘automatic type conversion’.


• Done by the compiler on its own, without
any external trigger from the user.
• Generally takes place when in an expression
more than one data type is present. In such
conditions type conversion (type
promotion) takes place to avoid loss of data.

43
1. Implicit Type Conversion (2/2)

● All the data types of the variables are upgraded to the data type of the variable
with the largest data type.

● It is possible for implicit conversions to lose information, signs can be lost


(when signed is implicitly converted to unsigned), and overflow can occur
(when long long is implicitly converted to float).

44
Occurrences of Implicit Type Conversion in C

● Implicit type conversion is also called automatic type conversion.


● Some of its few occurrences are mentioned below:
○ Conversion Rank
○ Conversions in Assignment Expressions
○ Conversion in other Binary Expressions
○ Promotion
○ Demotion

45
Example of Type Implicit Conversion
Example no 1
// An example of implicit conversion x = x + y; // x is implicitly converted
#include <stdio.h> to float
float z = x + 1.0;
int main()
{ printf("x = %d, z = %f", x,
z);
int x = 10; // integer x return 0;
char y = 'a'; // character y }

Output
// y implicitly converted to int.
ASCII
// value of 'a' is 97
46
2. Explicit Type Conversion (1/2)

47
2. Explicit Type Conversion (2/2)
● This process is also called type casting and it is user-defined. Here the user can typecast the result to make
it of a particular data type. The syntax in C Programming:

● Type indicated the data type to which the final result is converted.

48
Example no 2
// C program to demonstrate explicit type // Explicit conversion from double to int
casting int sum = (int)x + 1;
#include<stdio.h>
printf("sum = %d", sum);

int main() return 0;


}
{
double x = 1.2;

49
Example no 3

#include <stdio.h>
int main() {
float a = 1.5;
int b = (int)a;
printf("a = %f\n", a);
printf("b = %d\n", b);
return 0;
}

50
Advantages of Type Conversion (1/2)

● Type safety: Type conversions can be used to ensure that data is being stored and
processed in the correct data type, avoiding potential type mismatches and type errors.
● Improved code readability: By explicitly converting data between different types, you
can make the intent of your code clearer and easier to understand.
● Improved performance: In some cases, type conversions can be used to optimize the
performance of your code by converting data to a more efficient data type for
processing.

51
Advantages of Type Conversion (2/2)
● Improved compatibility: Type conversions can be used to convert data between
different types that are not compatible, allowing you to write code that is
compatible with a wider range of APIs and libraries.
● Improved data manipulation: Type conversions can be used to manipulate data
in various ways, such as converting an integer to a string, converting a string to an
integer, or converting a floating-point number to an integer.
● Improved data storage: Type conversions can be used to store data in a more
compact form, such as converting a large integer value to a smaller integer type, or
converting a large floating-point value to a smaller floating-point type.

52
Disadvantages of type conversions in C
programming (1/2)

● Loss of precision: Converting data from a larger data type to a smaller data type
can result in loss of precision, as some of the data may be truncated.
● Overflow or underflow: Converting data from a smaller data type to a larger data
type can result in overflow or underflow, if the value being converted is too large or
too small for the new data type.
● Unexpected behavior: Type conversions can lead to unexpected behavior, such as
when converting between signed and unsigned integer types, or when converting
between floating-point and integer types.

53
Disadvantages of type conversions in C
programming (1/2)

● Confusing syntax: Type conversions can have a confusing syntax, particularly


when using type cast operators or type conversion functions, making the code more
difficult to read and understand.
● Increased complexity: Type conversions can increase the complexity of your code,
making it harder to debug and maintain.
● Slower performance: Type conversions can sometimes result in slower
performance, particularly when converting data between complex data types, such
as between structures and arrays.

54
Explicit Typecasting

55
Type Cast
Example Action
X = (int)3.5 3.5 is converted to integer
(This truncates not rounds so X=3)
X = (int)(a+b) The result of (a+b) is converted to integer
X = (int)a + b a is converted to integer and then added with
b
X = (int)a / (int)b a is converted to int, b is converted to
int, then division operation performed
X = (int)20.5 /(int) 20.5 converted to floor int(20), 4.33
4.33 converted to floor int(4), then
division operation is performed
56
More with Format Specifier
#include<stdio.h>
int main() {
float var=1.3143547; ▪ Output:
printf(“\n%f”, var); 1.3143547
printf(“\n%.2f”, var);
1.31
}
Prints upto 2 decimal point

57
More with Format Specifier

#include<stdio.h>
int main() { ▪ Output:
float var=1.3153547; 1.3143547
printf(“\n%f”, var);
1.32
printf(“\n%.2f”, var);

} Prints upto 2 decimal point and


rounds up

58
More with Format Specifier

#include<stdio.h> ▪ Output?
int main() { 1.3153547
float var=1.3153547;
printf(“\n%f”, var); 1.315
printf(“\n%.3f”, var);

} Rounds the value and Prints


upto 3 decimal point

59
scanf Statement

declaring the variable

Because we are taking an integer input memory address


of the variable

60
Memory Address

▪ Think of it like trying to find a student in a classroom using their


student_id.
▪ If they are arranged randomly, need to check every student from
start to end one by one.
▪ If the student are arranged according to their student_id, it makes
the search alot more efficient.
▪ That’s why computers use addresses. To make searching
information easier.

61
Memory Address

▪ Let’s assume computer memory looks like this 1 2 3 4


after running the following codes:
int a = 5; 1
int b;
2 a=5
▪ Here, address of a is 22, and address of b is 34.
3 b=
▪ These numbers are called memory addresses. gar bage

Actual memory addresses can be huge numbers


value

and so used in Hexadecimal number system. 4

▪ In an actual computer memory, things are a lot


more complex, this is a mere simplified
analogy. 62
What is ‘&’ (ampersand) ?
▪ The scanf function expects to receive in the address of
the variable. It can then store the input value into the
memory address referred by the variable. ‘&’ sign
indicates the address of the variable.
▪ Every variable identifier indicate a value and the address
it stores the value at. Since just the identifier directly
corresponds to the value, an additional symbol (&) was
used along with it to indicate the address.
▪ ‘&’ reads as “address of”.

63
More about scanf format string

 When you add text other than white space in a format string that
you pass as an argument to scanf, the user must type input
exactly as it appears in the format string.

 You are essentially requiring the user to type input in a very


particular way.

64
More about scanf format string

In this given code:

65
More about scanf format string

In this given code,


Another Input & Output:

66
More about scanf format string

 Here the user input had to have a comma (,) between first and
second character inputs exactly as determined by the format
string: " %c, %c %c".
 Run this last program again, but this time, instead of typing the
comma after the 'a', just type the 'a', a blank and the '1'. You will
see that the values of the variables are not correct.
 Although it is possible to include characters other than white
space in the format string, it is generally best not to.
 The more specific the requirements for input, the greater the
chance for errors.
67
Input/Output with multiple variables
Operators
▪ Operator: Operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations.
▪ Based on number of operands C operators can be classified into a
number of categories:
▪ Unary Operators
■ Syntax: operator variable;
▪ Binary Operators
■ Syntax: variable1 operator variable2;
▪ Ternary Operators
■ Syntax: variable1 operator variable2 operator variable3;
70
Operators
▪ Operator: Operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations.
▪ Based on type of operations C operators can be classified into a number of
categories:
▪ Arithmetic operators
▪ Relational operators
▪ Logical operators
▪ Assignment operators
▪ Increment and decrement operators
▪ Bitwise operators
▪ Special operators
71
Arithmetic Operators

Arithmetic C Operation Example Possible


Operator operands

+ Addition 5+6, a+b, a+4 Any number


- Subtraction 6.5-5.0, a-b Any number
* Multiplication 6*5.5, a*b Any number
/ Division 6/2, a/b Any number
% Modulus 14%3 Only Integer number

72
Operators Precedence
● Parentheses: ()

● Multiplication and Division: */%

● Addition and Subtraction: +-

73
Operators Precedence
Goes left to right in the
same precedence

(in the order they are written in the code


not the order they are shown in this slide)

74
Operators Precedence

 The result of int op int is int


 The result of int op float is float
 The result of float op int is float
 The result of float op float is float

75
Operators Example

This is a constant expression

76
Operators Example

Notice how it is the same as


previous expression, except the
numbers were replaced with
variables.
77
Assignment Operator
Operator sign example Meaning in C
Name
Assignment = A = 5+6; Assigns the value of the
A= x+y; right expression or Variable
A = 5; to the left operand
A = x;
A=x=y;

Assignment Chaining
Here x=y executes first
Then A=result of that execution
78
Increment & Decrement Operators
Operator Type example Meaning in C
Name
Increment Prefix A = ++X Increments the value of X by 1
THEN Assigns the value to A
Postfix A = X++ Assigns the current value of X to A
THEN Increment the value of X by 1
Decrement Prefix A = --X Decrements the value of X by 1
THEN Assigns the value to A
Postfix A = X-- Assigns the current value of X to A
THEN Decrement the value of X by 1

79
Increment & Decrement Operators

For Example:

Lets consider,

X=5

1. A= ++X (Pre Increment) // First increment X-> X=6; then assign A-> A=6
2. A= X++(Post Increment) // First Assign to A->A=5; then increment X=6
3. A= --X (Pre decrement) // First decrement X->X=4, then assign A->A=4
4. A= X--(PostDecrement) // First assign to A=5; then decrement X=4

80
Example:
Taking Input and Printing float Value

#include<stdio.h> ▪ Ampersand sign = &


int main() {
float operand1, operand2, result;
scanf(“%f”,&operand1 ); An alternative can be:
scanf(“%f”,&operand2 ); scanf(“%f%f”,&operand1 ,
result = operand1 + operand2; &operand2 );

printf(“\nResult of the addition of %f and %f is %f”, operand1, operand2,result );

81
Special Operator

▪ sizeof operator:
▪ It returns the number of bytes the operand occupies.

i=sizeof(int);

82
Special Operator

83
Comments

84
Practice at home

❑ Take a small case letter as input. Output its corresponding large case
letter.

❑ Take the radius of a circle as input. Calculate its area and output it with
the value rounded up to two decimal places.

❑ Rahim and Karim are two friends who want to hangout but are too busy to
do so. But starting today, Rahim is free every xth day and Karim is free
every yth day. Print on whichth day Rahim and Karim will be able to
hangout?

85
Task

 A circular track field is t metres long. A runner ran around the


track for x metres. Print how many more metres he needed to run
to cover an additional lap.

86
Thank You

87

You might also like