SlideShare a Scribd company logo
1 of 230
Download to read offline
Computer Programming
CSE 2109
Credit 3.00
C Programming
Md. Hassanul Karim
Roni
Lecturer EEE, BAUST
Md. Hassanul Karim Roni
Lecturer, EEE
Bangladesh Army University of Engineering and Technology
(BAUST)
Present Address: BAUST, Saidpur Cant, Nilphamary
hassanulkarim.roni@gmail.com
Hassanul Karim Roni
Facebook Group: HK Roni, Dept. of EEE
Personal website: hkroni.cloudaccess.host
f
3
Course Contents
• Introduction to digital computers.
• Programming languages, algorithms and flow charts.
• Structured Programming using C.
• Variable and constants,
• operators,
• expressions,
• control statements,
• function,
• arrays,
• pointers,
• structure unions.
• User defined data types.
• Input output and files.
• Object oriented Programming using C++:
• Introduction, classes and objects.
• Polyorphism, function and operator overloading, inheritance.
4
Software
http://www.codeblocks.org/downloads/26
Download the mingw version
codeblocks-17.12mingw-setup.exe
https://code.visualstudio.com/Download
Online Compiler
https://www.tutorialspoint.com/compile_c_online.php
https://www.onlinegdb.com/online_c_compiler
5
Text Book
6
Reference Book
7
Reference Book (Bangla)
8
Reference Book (Bangla)
9
Reference Website
https://www.tutorialspoint.com/cprogramming/
https://www.udemy.com/
https://www.coursera.org/
http://hkroni.cloudaccess.host/academic-courses/
https://www.cprogramming.com/
Online Courses
You will get from this site
• Class Lectures
• Class Resources
• Assignments/ Tests Questions
• Important Links
• Software and Download Links
• Class Test Marks
• Quiz Tests
• My other courses
Basic Computer
Hardware
Section
1
11
Questions
1. Define cache memory.
2. Define primary and secondary memory. Differentiate between RAM and ROM.
3. Draw the block diagram of Von Neumann Computer Architecture.
4. Draw a block diagram to illustrate the basic organization of a computer system
and explain the functions of the various units.
5. Discuss the various storage classes of C.
6. Explain various input and output devices.
12
Types of Components
A digital computer consists of mainly-
• Hardware
• Software
13
Basic Hardware of a Personal Computer
• Monitor
• Motherboard
• CPU (Microprocessor)
• Expansion Card
• Power Supply
• Storage
• Keyboard
• Mouse
• Optical Disc Drive
14
Classification of Hardware
Four Major Classes of Hardware
1. CPU – Central Processing Unit
• Makes decision Makes decisions, performs computations, and delegates input/output
requests
2. Memory
• Stores information
3. Input Devices
• Gets information from the user to the computer
4. Output Devices
• Sends information from computer to the user
15
Input Devices
16
Input Devices
17
Computer Memory
Memory is primarily of three types −
• Cache Memory
• Primary Memory/Main Memory
• Secondary Memory
18
Computer Memory: Cache Memory
• Cache memory is a very high speed semiconductor
memory which can speed up the CPU.
• It acts as a buffer between the CPU and the main memory.
• It is used to hold those parts of data and program which
are most frequently used by the CPU.
• The parts of data and programs are transferred from the
disk to cache memory by the operating system, from
where the CPU can access them.
19
Computer Memory: Primary Memory
• Primary memory holds only those data and instructions
on which the computer is currently working.
• It has a limited capacity and data is lost when power is
switched off.
• It is generally made up of semiconductor device.
• These memories are not as fast as registers. The data
and instruction required to be processed resides in the
main memory.
• It is divided into two subcategories RAM and ROM.
20
Computer Memory: Primary Memory
21
RAM (Random Access Memory)
• It is also called as read write memory or the main memory or the primary
memory.
• The programs and data that the CPU requires during execution of a program are
stored in this memory.
• It is a volatile memory as the data loses when the power is turned off.
• RAM is further classified into two types- SRAM (Static Random Access
Memory)and DRAM (Dynamic Random Access Memory).
22
DRAM vs. SRAM
23
RAM vs. ROM
Definition • RAM is a form of data storage that can be
accessed randomly at any time, in any
order and from any physical location.,
allowing quick access and manipulation.
• Read-only memory or ROM is also a form of
data storage that can not be easily altered or
reprogrammed.
• Stores instructions that are not nesccesary for
re-booting up to make the computer operate
when it is switched off.
• They are hardwired.
Stands for Random Access Memory Read-only memory
Use RAM allows the computer to
read data quickly to run applications. It
allows reading and writing.
ROM stores the program required to initially boot
the computer. It only allows reading.
Volatility RAM is volatile i.e. its contents are lost when
the device is powered off.
It is non-volatile i.e. its contents are retained
even when the device is powered off.
Types The two main types of RAM are static RAM
and dynamic RAM.
The types of ROM include PROM, EPROM and
EEPROM.
24
Computer Memory: Secondary Memory
• This type of memory is also known as external memory or
non-volatile.
• It is slower than the main memory.
• These are used for storing data/information permanently.
• CPU directly does not access these memories, instead they
are accessed via input-output routines.
• The contents of secondary memories are first transferred to
the main memory, and then the CPU can access it.
• For example, disk, CD-ROM, DVD, etc.
25
Test Your Self
• Monitor
• Keyboard
• CPU (The Box)
• Floppy Drive
• CD-ROM
• Printer
• Scanner
• Modem
• Digital Camera
• CD Writer/Burner
• Hard Drive
• LCD Projector
• Laser Pointer
• Network Card
• Bluetooth Card
• Speakers
26
Computer Software
Computer Software
System Software Application Software
27
Operating System
• Controls and manages the computing resources
• Examples
• Windows, Unix, MSDOS,
• Important services that an operating system provides:
• Security: prevent unauthorized users from accessing the system
• Commands to manipulate the file system
• Input and output on a variety of devices
• Window management
28
Application Software
• Application software makes computer popular and easy to use
• Common application software:
• Microsoft Office
• Firefox, Opera, Chrome
• Photo Shop, Photo-Paint
• Media Player, VLC player, KM Player
• Dreamweaver, code block
29
What is a (programming) language?
• A program needs to be written in a language
• There are many programming languages
• Low-level, understandable by a computer
• High-level, needs a translator!
• C is a high level programming language
A sequence of instructions
A program
(in computer language)
An algorthm
(in human language)
30
Levels of programming language
• Machine binary language: unintelligible
• Low-level assembly language
• Mnemonic names for machine operations
• Explicit manipulation of memory addresses
• Machine-dependent
• High-level language
• Readable
• Machine-independent
31
An example of Programs
Machine binary language Low-level assembly High-level
32
Von Neumann Computer Architecture
Learning C Basics
Section
2
34
Questions
1. Define the following: i) High level language ii) Machine Language iii) Mid-Level
Language
2. Define- i) Assembler ii) Compiler iii) Interpreter
3. What are the basic features of C programming?
4. Importance of C Programming.
5. Mention some applications of C programming.
6. What are the steps of executing a C Program? Explain the process of compiling and
running a C program using a suitable flowchart.
7. Why and when do we use #define directive?
8. What is preprocessor directives? Why they are used?
9. Why and when do we use #include directive?
10. Why do we need to use comment in programs?
11. Explain the basic parts of a C program using a C program that finds the average of 3
numbers.
35
Programs used in C
• Assembler
• Compiler
• Interpreter
36
Assembler
• Assembler is a computer program which is used to translate program written in
Assembly Language in to machine language. The translated program is called as
object program. Assembler checks each instruction for its correctness and
generates diagnostic messages, if there are mistakes in the program.
• Various steps of assembling are:
1. Input source program in Assembly Language through an input device.
2. Use Assembler to produce object program in machine language.
3. Execute the program.
37
Compiler
• A compiler is a program that translates a program written in HLL to executable
machine language.
• For example: Turbo C, Code Blocks, Dev C++ etc.
The function of a complier includes the following:
1. To translate HLL source program to machine codes.
2. To trace variables in the program
3. To include linkage for subroutines.
4. To allocate memory for storage of program and variables.
5. To generate error messages, if there are errors in the program.
38
Interpreter
• The basic purpose of interpreter is same as that of complier. In compiler, the
program is translated completely and directly executable version is generated.
Whereas interpreter translates each instruction, executes it and then the next
instruction is translated and this goes on until end of the program. In this case,
object code is not stored and reused.
• Every time the program is executed, the interpreter translates each instruction
freshly. It also has program diagnostic capabilities. However, it has some
disadvantages as below:
1. Instructions repeated in program must be translated each time they are
executed.
2. Because the source program is translated fresh every time it is used, it is slow
process or execution takes more time. Approx. 20 times slower than complier.
39
Features of C
40
Features of C
• It is a robust language with rich set of built-in functions and operators that can be
used to write any complex program.
• The C compiler combines the capabilities of an assembly language with features
of a high-level language.
• Programs Written in C are efficient and fast. This is due to its variety of data type
and powerful operators. It is many time faster than BASIC.
• C is highly portable this means that programs once written can be run on another
machines with little or no modification.
• Another important feature of C program, is its ability to extend itself.
• A C program is basically a collection of functions that are supported by C library.
We can also create our own function and add it to C library.
• C language is the most widely used language in operating systems and embedded
system development today.
41
Why learn C?
• Two Step Learning Process: One should first learn all the language elements very
thoroughly using C language before migrating to C++, C# or Java.
• Basic Programming Skill and introduction to basic programming elements through
C.
• Useful Elements: Though many C++ and Java based programming tools and
frameworks have evolved over the years, yet knowingly or unknowingly while
using these frameworks and tools you would be still required to use the core C
language elements.
• Operating Systems in C: Major parts of popular operating systems like Windows,
UNIX, Linux is still written in C.
42
Why learn C?
• Electronics Devices OS in C: Common consumer devices like microwave oven,
washing machines and digital cameras has an operating system and a program
embedded in this devices. These programs not only have to run fast but also have
to work in limited amount of memory. No wonder that such programs are written
in C.
• Faster Game Experience: Many popular gaming frameworks have been built using
C language. The essence of all such games is speed. This is where C language
scores over other languages.
• At times one is required to very closely interact with the hardware devices. Since
C provides several language elements that make this interaction feasible without
compromising the performance it is the preferred choice of the programmer.
43
Steps in Learning C
In C language characters are grouped into
the following catagories,
1. Letters (all alphabets a to z & A to Z).
2. Digits (all digits 0 to 9).
3. Special characters, (such as colon :,
semicolon ; , period ., underscore _ ,
ampersand & etc).
4. White spaces.
44
First C Program and its Structure
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
Hello World
Different parts of C program
• Pre-processor
• Header file
• Function
• Variables
• Statements & expressions
• Comments
45
Important to Remember
• C is a case sensitive language so all C instructions must be written in lower case
letter.
• All C statement must end with a semicolon.
• Whitespace is used in C to describe blanks and tabs.
• Whitespace is required between keywords and identifiers.
46
Questions
1. Write short notes on: C Tokens, Keywords, Identifiers , Constants, Variables
2. What are the rules to name an Identifier?
3. Define variable. Mention the rules of naming a variable in C language.
4. Define- local variable, global variable and static variable and Register variable.
5. Define constant. Mention the rules of naming a constant in C language
6. Mention the names of various types of C token with examples.
7. What are the white spaces used in C programming?
8. What are the basic data type associated with C? Explain with examples.
9. What are the rules to construct real constant?
10. What are the rules for constructing a variable?
11. What are the different control instruction in C language?
12. What is typecasting in C programming?
47
Questions
1. Find valid and invalid variable names. If invalid mention the proper reason-
• First_tag
• char
• Price$
• Group one
• Int_type
• _Team1
• Mark-1
• 1_team
2. Describe the basic data types in C? How can you extend the range of values they
represent?
3. Compare ‘x’ and “x” for their types, the storage they occupy and comment if they are
same?
4. What is the difference between the constants 7, ‘7’, “7”?
5. Is it possible to store 32768 in an int data type variable? If possible, explain how.
48
Constants
• A constant is an entity that doesn’t change whereas a variable is an entity that
may change.
49
Variable
• An entity that may vary during program execution is called a variable.
Rules for Constructing Variable Names
• A variable name is any combination of 1 to 31 alphabets, digits or underscores.
• The first character in the variable name must be an alphabet or underscore.
• No commas or blanks are allowed within a variable name.
• No special symbol other than an underscore (as in gross_sal) can be used in a
variable name.
• Keywords are not allowed to be used as variable name.
50
Types of Variables: Local Variable
Local Variables: The variables which are declared inside the function, compound statement (or block)
are called Local variables.
• They are available only inside the function in which they are defined.
• The same variable names can be used in a different function and they will not conflict with each
other
void function_1()
{
int a = 1, b = 2;
}
void function_2()
{
int a = 10, b = 20;
}
51
Types of Variables: Global Variable
• The variables declared outside any function are
called global variables.
• They are not limited to any function. Any function
can access and modify global variables.
• Global variables are automatically initialized to 0 at
the time of declaration.
• Global variables are generally written before main()
function.
• Unlike local variables, global variables are not
destroyed as soon as the function ends. They are
available to any function until the program is
executing.
#include<stdio.h>
void func_1();
void func_2();
int a, b = 10; // declaring and initializing global variables
int main()
{
printf("Global a = %dn", a);
printf("Global b = %dnn", b);
func_1();
func_2();
return 0;
}
void func_1()
{
printf("From func_1() Global a = %dn", a);
printf("From func_1() Global b = %dnn", b);
}
void func_2()
{
int a = 5;
printf("Inside func_2() a = %dn", a);
}
52
Types of Variables: Static Variable
• A Static variable is able to retain its value between
different function calls.
• The static variable is only initialized once, if it is not
initialized, then it is automatically initialized to 0.
#include<stdio.h>
void func_1();
int a, b = 10;
int main()
{
func_1();
func_1();
func_1();
return 0;
}
void func_1()
{
int a = 1;
static int b = 100;
printf("a = %dn", a);
printf("b = %dnn", b);
a++;
b++;
}
53
Difference between local and global variables
Basis for
Comparison
Local Variable Global Variable
Declaration
Variables are declared inside a
function.
Variables are declared outside any
Scope
Within a function, inside which they
are
declared.
Throughout the program.
Access
Accessed only by the statements,
inside a
function in which they are declared.
Accessed by any statement in the entire
program.
Life
Created when the function block is
entered
and destroyed upon exit.
Remain in existence for the entire time
your program is executing.
Storage
Local variables are stored on the
stack,
unless specified.
Stored on a fixed location decided by a
compiler
54
Keywords in C
• Keywords are preserved words that have special meaning in C language.
• The meaning of C language keywords has already been described to the C
compiler. These meaning cannot be changed.
• keywords cannot be used as variable names because that would try to change the
existing meaning of the keyword, which is not allowed.
• There are total 32 keywords in C language.
auto double int struct
break else long switch
case enum register typedef
const extern return union
char float short unsigned
continue for signed volatile
default goto sizeof void
auto double int struct
55
Identifiers
• In C language identifiers are the names given to variables, constants,
functions and user-define data.
• 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 identifiers 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.
56
Data types in C Language
• Data types specify how we enter data
into our programs and what type of data
we enter.
• C language supports 2 different type of
data types:
1. Primary data types: integer(int),
floating point(float), character(char)
and void.
2. Derived data types: array, structure,
union and pointer.
57
Modifiers in C
There are 5 modifiers available in C programming language as follows.
• Short
• Long
• Signed
• Unsigned
• long long
58
Integer type
Type Size(bytes) Range
int or signed int 2= 216bits -32,768 to 32767
unsigned int 2= 216
bits 0 to 65535
short int or signed short int 1= 28
bits -128 to 127
unsigned short int 1= 28bits 0 to 255
long int or signed long int 4= 232bits -2,147,483,648 to 2,147,483,647
unsigned long int 4= 232
bits 0 to 4,294,967,295
59
Difference between signed and unsigned data type
• Signed variables, such as signed integers will allow you to represent numbers both
in the positive and negative ranges.
• Unsigned variables, such as unsigned integers, will only allow you to represent
numbers in the positive.
• Unsigned and signed variables of the same type (such as int and byte) both have
the same range (range of 65,536 and 256 numbers, respectively), but unsigned
can represent a larger magnitude number than the corresponding signed variable.
• For example, an unsigned byte can represent values from 0 to 255 (numeric value
0 to 65,536) while signed byte can represent -128 to 127 (numeric value -32768 to
32767).
60
Is that possible to store 32768 in an int data type
variable?
• int data type only capable of storing values between – 32768 to 32767.
• To store 32768 a modifier needs to use with int data type.
• Long int can use and also if there is no any negative values unsigned int is also
possible to use.
Practice
printf()+ scanf()
Section
2.1
62
Key Points To Remember In C Printf() And Scanf():
• printf() is used to display the output and scanf() is used to read the inputs.
• printf() and scanf() functions are declared in “stdio.h” header file in C library.
• All syntax in C language including printf() and scanf() functions are case sensitive.
63
Print a number
int age=20;
printf("My age is %d",age);
int price=1.99;
printf("Age:%f",price);
printf("'%4.3f'", 10.345642);
64
Print multiple Values
char name[]="poftut";
int age=2;
char city[]="ankara";
printf("Name:%s , Age:%d , City:%s", name, age, city);
65
Print Special Symbol
• printf("% is percent sign.");
or
• printf("%% is percent sign.");
66
Printf Special Characters
a audible alert
n newline, or linefeed
t tab
v vertical tab
 backslash
67
Scanf()
• In C programming language, scanf() function is used to read character, string,
numeric data from keyboard
The scanf() function uses the same placeholders as printf:
• int uses %d
• float uses %f
• char uses %c
• character strings use %s
68
Example
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter the first value:");
scanf("%d", &a);
printf("Enter the second value:");
scanf("%d", &b);
c = a + b;
printf("%d + %d = %dn", a, b, c);
return 0;
}
69
#include<stdio.h>
void main(){
char name[10];
fgets(name,10,stdin);
if(strcmp(name,"roni"){
printf(“You are %s",name);
}
else{
printf(“You are not %s",name);
}
}
Operators in C
Language
Section
3
71
Questions
1. What are the different operators used in C?
2. Briefly explain arithmetic and bitwise operators.
3. Differentiate between ++m and m++ using suitable example.
4. What does the && operator do in a C program? Explain with an example.
5. What is the difference between the expression “++a” and “a++”?
6. Differentiate between increment and decrement operators
7. Differentiate between bitwise AND (&) and logical AND (&&) operator in C
language using proper example.
8. Using conditional operator statement (?: operator) write a C program to find
whether the given number is even or odd.
9. Describe the difference between ‘=’ and ‘= =’ symbols in C programming?
72
C operators
C operators can be classified into following types:
• Arithmetic operators
• Relational operators
• Logical operators
• Bitwise operators
• Assignment operators
• Conditional operators
• Special operators
A + B * C
Operators
Operands
According to the number of
operands
• Unary operator (a++, a--)
• Binary operator (a+b)
• Ternary operator (?:)
( condition? Statement if true :
statement if false)
73
Arithmetic Operator
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denominator
% remainder of division
++ Increment operator - increases integer value by one
-- Decrement operator - decreases integer value by one
int a=10;
printf(‘%d’, a++);
int b=10;
printf(‘%d’, ++b);
int c=10; int d=3;
printf(‘%d’,c%d);
?
Arithmetic Operator
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denominator
% remainder of division
++ Increment operator - increases integer value by one
-- Decrement operator - decreases integer value by one
74
Assignment Operator
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
75
Relational Operator
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
76
Logical operators
Operator Description Example
&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false
77
Bitwise operators
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
a = 0001000
b = 2
a << b = 0100000
a >> b = 0000010
78
Bitwise operators: AND
79
Bitwise operators: OR
80
Bitwise operators: XOR
81
Bitwise operators: Atmega32
82
Conditional operator
The conditional operators in C language are known by two more names
• Ternary Operator
• ? : Operator
conditionalExpression ? expression1 : expression2
83
C Input and Output
• The standard input-output header file, named stdio.h contains the definition of
the functions printf() and scanf()
#include<stdio.h>
void main()
{
int i; // defining a variable
printf("Please enter a value...");
scanf("%d", &i); // Take user input
// Display out the value
printf("nYou entered: %d", i);
}
84
Format String Meaning
%d Scan or print an integer as signed decimal number
%f Scan or print a floating point number
%c To scan or print a character
%s To scan or print a character string. The scanning ends at whitespace.
85
getchar() & putchar() functions
• The getchar() function reads a character from the terminal and returns it as an
integer. This function reads only single character at a time.
• The putchar() function displays the character passed to it on the screen and
returns the same character. This function too displays only a single character at a
time.
• In case you want to display more than one characters, use putchar() method in a
loop.
86
Find the printed Value
• Find the printed values-
I. int a=2, b=3, c=(a+b)%a; printf(“%d”, c);
II. int x=3, y=6, z=x&y; printf(“%d”, y/x);
III. int m=5, n=7, z=m^n; printf(“%d”,z+2);
IV. int a=5, b=0, c=2; printf(“%d”, (a&&b) |c);
Decision Making in C
Section
4
88
Decision making in C
C language handles decision-making by supporting the following statements,
• if statement
• switch statement
• conditional operator statement (? : operator)
• goto statement
89
Decision making with if statement
• The different forms are,
• Simple if statement
• if....else statement
• Nested if....else statement
• Using else if statement
90
Simple if
if(expression)
{
statement
inside;
}
Example:
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
}
91
if...else statement
if...else statement
The general form of a simple if...else
statement is,
if(expression)
{
statement block1;
}
else
{
statement block2;
}
Example:
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
92
Nested if....else statement
if( expression )
{
if( expression1 )
{
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block3;
}
#include <stdio.h>
void main( )
{
int a, b, c;
printf("Enter 3 numbers..."); scanf("%d%d%d",&a, &b, &c);
if(a > b)
{
if(a > c)
{ printf("a is the greatest");
}
else
{ printf("c is the greatest");
}
}
else
{if(b > c)
{ printf("b is the greatest");
}
else
{ printf("c is the greatest");
}
}
}
93
else if ladder
if(expression1)
{
statement block1;
}
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;
#include <stdio.h>
void main( )
{
int a;
printf("Enter a number...");
scanf("%d", &a);
if(a%5 == 0 && a%8 == 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{
printf("Divisible by 8");
}
else if(a%5 == 0)
{
printf("Divisible by 5");
}
else
{
printf("Divisible by none");
}
}
94
switch statement
#include<stdio.h>
void main( )
{
int a, b, c, choice;
while(choice != 3)
{
/* Printing the available options */
printf("n 1. Press 1 for addition");
printf("n 2. Press 2 for subtraction");
printf("n Enter your choice"); scanf("%d", &choice); // Taking users input
switch(choice)
{
case 1:
printf("Enter 2 numbers"); scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers"); scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("n press any key to continue");
}
}
}
Rules for using switch statement
1. The expression (after switch keyword) must yield
an integer value i.e the expression should be an
integer or a variable or an expression that evaluates
to an integer.
2. The case label values must be unique.
3. The case label must end with a colon(:)
4. The next line, after the case statement, can be
any valid C statement.
95
Go To Statement
• Goto statements is used to transfer the normal flow of a program to the specified
label in program.
• Syntax for goto
{
….
go to label;
Label:
statements;
}
Loopping
Section
5
97
Questions
1. What is a nested loop?
2. Give the basic difference between the following-
• While and do while
• Break and continue
3. Create an infinite loop using C program.
4. Write a program to find the sum and average of the following series-
(i) 1+2+3+…+100
(ii) 2+4+6+…+100
(iii) 1+3+5+…+100
(iv) 3+6+9+…+99
(v) 1 +
1
2
+
1
3
+ ⋯ . +
1
100
(vi) (2+4+6+…+100)+ (3+6+9+…+99)
98
Looping
• There are 4 types of loop statement-
1. While Loop
2. Do Loop
3. For Loop
4. Nested For Loop
99
Loop
for loop
for(initialization; condition; increment/ decrement)
{
statement;
}
While loop
Initialization;
while(condition)
{
statement;
increment/ decrement
}
100
Loop
Do While loop
do
{
statement;
increment/ decrement
} while(condition)
Arrays
Section
6
102
Questions
1. Define array. Write down the advantages and limitations of array.
2. Define array. Mention its importance. How can we access the values within an
array?
3. Write a C program to add 5 elements of an integer array.
103
Arrays in C
In C language, arrays are referred to as structured data types.
An array is defined as finite ordered collection of homogenous data, stored in contiguous
memory locations.
Here the words,
• finite means data range must be defined.
• ordered means data must be stored in continuous memory addresses.
• homogenous means data must be of similar data type.
Example where arrays are used,
• to store list of Employee or Student names,
• to store marks of students,
• or to store list of numbers or characters etc.
104
Arrays in C
• An array is a collection of a fixed number of
values of a single type.
For example: if you want to store 100 integers in
sequence, you can create an array for it.
int data[100];
• The size and type of arrays cannot be changed
after its declaration.
Arrays are of two types:
• One-dimensional arrays
• Multidimensional arrays
105
Properties of Array
• Each element of an array is of same data type and carries the same size,
i.e., int = 4 bytes.
• Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
• Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size of
the data element.
106
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code
only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we
can't exceed the limit. So, it doesn't grow the size dynamically like Linked List which
we will learn later.
107
Declaring an Array
• Like any other variable, arrays must be declared before they are used. General
form of array declaration is,
data-type variable-name[size];
/* Example of array declaration */
int arr[10];
 Here int is the data type, arr is the name of the array and 10 is the size of array.
It means array arr can only contain 10 elements of int type.
 Index of an array starts from 0 to (size-1)
i.e first element of arr array will be stored at arr[0] address and the last element will occupy arr[9].
108
Initialization of an Array
• After an array is declared it must be initialized.
• Otherwise, it will contain garbage value(any random value).
• An array can be initialized at either compile time or at runtime.
109
Compile time Array initialization
• Compile time initialization of array elements is same as ordinary variable
initialization.
• The general form of initialization of array is,
data-type array-name[size] = { list of values };
/* Here are a few examples */
int marks[4]={ 67, 87, 56, 77 }; // integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization
int marks[4]={ 67, 87, 56, 77, 59 }; // Compile time error
110
Initialize an array
• Another method to initialize array during declaration:
int mark[] = {19, 10, 8, 17, 9};
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
111
Runtime Array initialization
• An array can also be initialized at
runtime using scanf() function.
• This approach is usually used for
initializing large arrays, or to
initialize arrays with user specified
values.
Example->
#include<stdio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i = 0; i < 4; i++)
{
scanf("%d", &arr[i]); //Run time array initialization
}
for(j = 0; j < 4; j++)
{
printf("%dn", arr[j]);
}
}
112
Insert and print array elements
int mark[5] = {19, 10, 8, 17, 9}
// insert different value to third element
mark[3] = 9;
// take input from the user and insert in third element
scanf("%d", &mark[2]);
// take input from the user and insert in (i+1)th element
scanf("%d", &mark[i]);
// print first element of an array
printf("%d", mark[0]);
// print ith element of an array
printf("%d", mark[i-1]);
113
Program to find the average of n (n < 10) numbers using
arrays
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
printf("Average = %d", average);
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
114
Display Largest Element of an array
#include <stdio.h>
int main()
{
int i, n;
float arr[100];
printf("Enter total number of elements(1 to 100): ");
scanf("%d", &n);
printf("n");
// Stores number entered by the user
for(i = 0; i < n; ++i)
{
printf("Enter Number %d: ", i+1);
scanf("%f", &arr[i]);
}
// Loop to store largest number to arr[0]
for(i = 1; i < n; ++i)
{
// Change < to > if you want to find the
smallest element
if(arr[0] < arr[i])
arr[0] = arr[i];
}
printf("Largest element = %.2f", arr[0]);
return 0;
}
115
Two dimensional Arrays
• C language supports multidimensional arrays also. The simplest form of a multidimensional array
is the two-dimensional array. Both the row's and column's index begins from 0.
• Two-dimensional arrays are declared as follows,
data-type array-name[row-size][column-size]
/* Example */
int a[3][4];
An array can also be declared and initialized together.
For example,
int arr[][3] = {
{0,0,0},
{1,1,1}
};
116
Runtime initialization of a two dimensional Array
#include<stdio.h>
void main()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{ printf("%d", arr[i][j]);
}
}
}
117
Sorting an Array
#include<stdio.h>
void main ()
{
int i, j,temp;
int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
for(i = 0; i<10; i++)
{
for(j = i+1; j<10; j++)
{
if(a[j] > a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Printing Sorted Element List ...n");
for(i = 0; i<10; i++)
{
printf("%d n",a[i]);
}
}
118
Program to print the largest and second largest element of the
array
#include<stdio.h>
void main ()
{
int arr[100],i,n,largest,sec_largest;
printf("Enter the size of the array?");
scanf("%d",&n);
printf("Enter the elements of the array?");
for(i = 0; i<n; i++)
{
scanf("%d",&arr[i]);
}
largest = arr[0];
sec_largest = arr[1];
for(i=0;i<n;i++)
{
if(arr[i]>largest)
{
sec_largest = largest;
largest = arr[i];
}
else if (arr[i]>sec_largest && arr[i]!=largest)
{
sec_largest=arr[i];
}
}
printf("largest = %d, second largest = %d",largest,sec_largest);
}
Function
Section
7
120
Questions
1. What is the difference between actual and formal parameters?
2. Differentiate among: getch(), getche() and getchar();
3. What is user defined function? Why do we need it?
4. Differentiate between user defined and library function. Explain with example.
5. What is the difference between Call by Value and Call by Reference?
6. What is recursion? Write a program in C to calculate the factorial of a number
using recursive function.
121
Questions
1. Briefly discuss the function of the following functions-
• printf()
• scanf()
• getch(), getche(), getchar(), gets()
• add(), sub()
• sizeof() p-72
• fopen(), fprintf(), fscanf(), fclose(),
• atoi(), atof()
• toupper(),strcat(), strcpy(),tolower()
122
Functions
• Functions is basically a set of statements that takes inputs, perform some
computation and produces output.
• Syntax:
returntype functionName(type1 parameter1, type2 parameter2,...);
• C functions can be classified into two categories,
• Library functions
• User-defined functions
123
How function works in C
Syntax of function definition
returnType functionName(type1 argument1,
type2 argument2, ...)
{
//body of the function
}
124
Types of Function
• Library functions are those functions which are already defined in C library,
example printf(), scanf(), strcat() etc. You just need to include appropriate header
files to use these functions. These are already declared and defined in C libraries.
• A User-defined functions on the other hand, are those functions which are
defined by the user at the time of writing program. These functions are made for
code reusability and for saving time and space.
125
Benefits of Using Functions
• It provides modularity to your program's structure.
• It makes your code reusable. You just have to call the function by its name to use
it, wherever required.
• In case of large programs with thousands of code lines, debugging and editing
becomes easier if you use functions.
• It makes the program more readable and easy to understand.
126
Advantages of user-defined function
• The program will be easier to understand,
maintain and debug.
• Reusable codes that can be used in other
programs
• A large program can be divided into
smaller modules. Hence, a large project
can be divided among many
programmers.
Example: User-defined function
Here is an example to add two integers. To perform this task, an
user-defined function addNumbers() is defined.
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: "); scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a,int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
127
Example: Multiplication
#include<stdio.h>
int multiply(int a, int b); // function declaration
int main()
{
int i, j, result;
printf("Please enter 2 numbers you want to multiply...");
scanf("%d%d", &i, &j);
result = multiply(i, j); // function call
printf("The result of muliplication is: %d", result);
return 0;
}
int multiply(int a, int b)
{
return (a*b); // function defintion, this can be done in
one line
}
128
Calling a function
• When a function is called, control of the program gets transferred to the function.
functionName(argument1, argument2,...);
• Passing Arguments to a function: Arguments are the values specified during the function call, for
which the formal parameters are declared while defining the function.
129
Returning a value from function
130
Recall
• Actual Parameters: The parameters passed to a function
• Formal Parameters: The parameters received by a function
131
Call by Value
• Here values of actual parameters will be copied to formal parameters and these
two different parameters store values in different locations.
132
Call by Reference
• The call by reference method of passing arguments to a function copies the
address of an argument into the formal parameter.
#include <stdio.h>
void swap(int *x, int *y);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
printf("Before swap, value of a : %dn", a );
printf("Before swap, value of b : %dn", b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %dn", a );
printf("After swap, value of b : %dn", b );
return 0;
}
/* function definition to swap the values */
void swap(int *x, int *y) {
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
133
Recursion
• Recursion is a process in which a function calls itself directly
or indirectly.
• A function that calls itself is called a recursive function.
• in a recursive function, there must be a terminating condition
to stop the recursion. This condition is known as the base
condition.
• Often recursion can be used where loops can be used.
Generally, recursive solutions are elegant but less efficient
than loop solutions.
int main()
{
callme();
}
void callme()
{
if(base_condition)
{
// terminating condition
}
statement 1;
...
callme();
}
134
Example
• Find the printed value
135
Example
• Find the printed value
String Operation
Section
8
137
Questions
1. What are strings? Discuss some basic functions of “string.h” header file.
2. Explain with example:
I. strlen(), strcat(), strcmp(), strcpy(),
II. tolower(), toupper()
138
String in C
• String is a sequence of characters that is treated
as a single data item and terminated by null
character '0'.
• A string is actually one-dimensional array of
characters in C language.
Function Work of Function
strlen() Calculates the length of string
strcpy() Copies a string to another string
strcat() Concatenates(joins) two strings
strcmp() Compares two string
strlwr() Converts string to lowercase
strupr() Converts string to uppercase
139
String Manipulation Functions
140
Declaring and Initializing a string variables
There are different ways to initialize a character array variable.
• char name[13] = "StudyTonight"; // valid character array initialization
• char name[10] = {'L','e','s','s','o','n','s', '0' }; // valid initialization
Remember that when you initialize a character array by listing all of its characters separately then you
must supply the '0'character explicitly.
Error Test:
1. char ch[3] = "hell"; // Illegal
2. char str[4]; str = "hell"; // Illegal
141
String Input and Output
• Input function scanf() can be used with %s format specifier to read a string
input from the terminal.
• Read a string
char text[20];
gets(text);
printf("%s", text);
142
String Operation
strcat() function
• strcat("hello", "world");
• strcat() function will add the string "world" to "hello" i.e it will ouput helloworld
strlen() function
• strlen() function will return the length of the string passed to it.
int j;
j = strlen("studytonight");
printf("%d",j);
143
String Operation
strcmp() function
• strcmp() function will return the ASCII difference between first unmatching
character of two strings.
int j;
j = strcmp("study", "tonight");
printf("%d",j);
144
String Operation
strcpy() function
It copies the second string argument to the first string
argument.
#include<stdio.h>
#include<string.h>
int main()
{
char s1[50];
char s2[50];
strcpy(s1, "StudyTonight"); //copies "studytonight" to
string s1
strcpy(s2, s1); //copies string s1 to string s2
printf("%sn", s2);
return(0);
}
strrev() function
It is used to reverse the given string expression.
#include<stdio.h>
int main()
{
char s1[50];
printf("Enter your string: ");
gets(s1);
printf("nYour reverse string is: %s",strrev(s1));
return(0);
}
Structure & Union
Section
9
146
Questions
1. What is structure in C language? Explain with example.
2. Differentiate between structure and union.
3. How does a structure differ from an array? What is the basic difference between
a structure and union?
4. What are the advantages of structured variable over traditional variable?
147
Structure
• Structure is a user-defined datatype in C
language which allows us to combine data of
different types together.
• Structure helps to construct a complex data
type which is more meaningful.
• It is somewhat similar to an Array, but an array
holds data of similar type only.
• But structure on the other hand, can store data
of any type, which is practical more useful.
148
Declaring Structure Variables
149
Accessing Structure Members
#include<stdio.h>
#include<string.h>
struct Student
{
char name[25];
int age;
char branch[10];
char gender; //F for female and M for male
};
int main()
{
struct Student s1;
/* s1 is a variable of Student type and age is a member of
Student*/
s1.age = 18;
/* using string function to add name */
strcpy(s1.name, "Viraaj");
/* displaying the stored values */
printf("Name of Student 1: %sn", s1.name);
printf("Age of Student 1: %dn", s1.age);
return 0;
}
We can also use scanf() to give values to structure
members through terminal.
scanf(" %s ", &s1.name); // it obtain only one single word
scanf(" %d ", &s1.age);
Or, gets(s1.name) // to obtain full name
150
Structure Initialization
• Like a variable of any other data type, structure variable can also be
initialized at compile time.
151
Array of Structure
• We can also declare an array
of structure variables in which
each element of the array will
representa structure variable.
Example :
struct employee emp[5];
The below program defines an
array emp of size 5. Each element
of the array emp is of
type Employee.
152
Nested Structures
• Nesting of structures, is also permitted in
C language.
• Nested structures means, that one
structure has another structure as
member variable.
153
Structure vs. Union
• Unions are conceptually similar
to structures.
• The syntax to declare/define a union is
also similar to that of a structure.
• The only differences is in terms of
storage.
• In structure each member has its own
storage location, whereas all members
of union uses a single shared memory
location which is equal to the size of its
largest data member.
• This implies that although a union may
contain many members of different
types, it cannot handle all the members
at the same time. A union is declared
using the union keyword.
154
Accessing Union
• Syntax for accessing any union member is similar to accessing structure members-
union test
{
int a;
float b;
char c;
}t;
t.a; //to access members of
union t
t.b;
t.c;
Example
#include <stdio.h>
union item
{
int a; float b; char ch;
};
int main( )
{
union item it;
it.a = 12; it.b = 20.2; it.ch = 'z';
printf("%dn", it.a); printf("%fn", it.b);
printf("%cn", it.ch);
return 0;
}
C Pointers
Section
10
156
1. Define pointer. Mention the advantage of using pointer in C.
2. Define pointer variable. How is it different from normal variable?
3. Define Null pointer.
4. Differentiate between normal variable vs pointer variable.
5. What is a null pointer?
6. What is difference between far and near pointers?
7. Explain the concept behind using pointers and give an example of Array of
pointer.
8. Define Dangling Pointer.
157
Pointer in C
• Pointers in C language is a variable that stores/points the address of another variable.
• A Pointer in C is used to allocate memory dynamically i.e. at run time.
• The pointer variable might be belonging to any of the data type such as int, float, char, double, short
etc.
• Like any variable or constant, you must declare a pointer before using it to store any variable address.
The general form of a pointer variable declaration is −
type *var-name;
• Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the
pointer variable.
• The asterisk * used to declare a pointer is the same asterisk used for multiplication.
some of the valid pointer declarations −
• int *ip; /* pointer to an integer */
• double *dp; /* pointer to a double */
• float *fp; /* pointer to a float */
• char *ch /* pointer to a character */
158
How to Use Pointers?
• There are a few important operations, which
we will do with the help of pointers very
frequently.
a) We define a pointer variable,
b) Assign the address of a variable to a
pointer and
c) Finally access the value at the address
available in the pointer variable.
159
NULL Pointers
• It is always a good practice to assign a NULL value to a
pointer variable in case you do not have an exact
address to be assigned.
• This is done at the time of variable declaration. A
pointer that is assigned NULL is called a null pointer.
• The NULL pointer is a constant with a value of zero
defined in several standard libraries. Consider the
following program −
When the above code is compiled and executed, it
produces the following result −
The value of ptr is 0
160
C - Pointer arithmetic: Incrementing a Pointer
• Incrementing a Pointer
ptr++
• If ptr points to a character whose address is 1000, then
the above operation will point to the location 1001
because the next character will be available at 1001.
When the above code is compiled and executed, it
produces the following result −
161
Decrementing a Pointer
162
Array of Pointer
163
Array of Pointer
An array of pointers to character to store a list of strings
164
Pointer to Pointer
• A pointer to a pointer is a form of multiple indirection, or a chain of pointers.
Normally, a pointer contains the address of a variable.
• When we define a pointer to a pointer, the first pointer contains the address of
the second pointer, which points to the location that contains the actual value as
shown below.
• A variable that is a pointer to a pointer must be declared as such. This is done by
placing an additional asterisk in front of its name.
• For example, the following declaration declares a pointer to a pointer of type int −
• int **var;
Files in C
Section
11
166
Questions
1. Write short note on different modes of opening a file.
2. Explain with example- fopen(), fprintf(), fscanf(), fclose(),
167
Files I/O
Why files are needed?
• When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter them
all.
However, if you have a file containing all the data, you can easily access the
contents of the file using few commands in C.
• You can easily move your data from one computer to another without any
changes.
168
Types of Files
When dealing with files, there are two types of files you should know about:
• Text files
• Binary files
1. Text files:
• Text files are the normal .txt files that you can easily create using Notepad or any simple text
editors.
• When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.
• They take minimum effort to maintain, are easily readable, and provide least security and takes
bigger storage space.
2. Binary files
• Binary files are mostly the .bin files in your computer.
• Instead of storing data in plain text, they store it in the binary form (0's and 1's).
• They can hold higher amount of data, are not readable easily and provides a better security than
text files.
169
File Operations
In C, you can perform four major operations on the file, either text or binary:
• Creating a new file
• Opening an existing file
• Closing a file
• Reading from and writing information to a file
170
File operations
To Write something in a file
• fputc()
• fputw()
• fputs()
• fprintf()
• fwrite()
To read something in a file
• fgetc()
• fgetw()
• fgets()
• fscanf()
• fread()
171
Working with files
• When working with files, you need to declare a pointer of type file. This
declaration is needed for communication between the file and program.
• FILE *fptr;
172
Opening a file - for creation and edit
• Opening a file is performed using the library function in the "stdio.h" header file:
fopen().
• The syntax for opening a file in standard I/O is:
ptr = fopen("fileopen","mode")
For Example:
• fopen("E:cprogramnewprogram.txt","w");
• fopen("E:cprogramoldprogram.bin","rb");
173
Opening Modes in Standard I/O
File Mode Meaning of Mode During Inexistence of file
r Open for reading. If the file does not exist, fopen() returns NULL.
w
Open for writing.
If the file exists, its contents are overwritten. If the
file does not exist, it will be created.
a
Open for append. i.e, Data is added to
end of file.
If the file does not exists, it will be created.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
w+ Open for both reading and writing.
If the file exists, its contents are overwritten. If the
file does not exist, it will be created.
a+ Open for both reading and appending. If the file does not exists, it will be created.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
174
Closing a File
• The file (both text and binary) should be closed after reading/writing.
• Closing a file is performed using library function fclose().
fclose(fptr); //fptr is the file pointer associated with file to be closed.
175
Reading and writing to a text file
• For reading and writing to a text file, we use the functions fprintf() and fscanf().
• They are just the file versions of printf() and scanf(). The only difference is that,
fprint and fscanf expects a pointer to the structure FILE.
176
Example 1: Write to a text file using fprintf()
NB:
• exit(0) usually indicates that all
is well,
• whilst exit(1) indicates that
something has gone amiss.
• exit() should always be called
with an integer value and non-
zero values are used as error
codes
177
Example 2: Read from a text file using fscanf()
178
Write a C program to read name and marks of n number of students from user and store
them in a file.
179
Write a C program to read name and marks of n number of students from user and store them in a file.
If the file previously exits, add the information of n students.
Dynamic Memory
Allocation
Section
12
181
1. Distinguish between malloc() & calloc() memory allocation.
2. What do you mean by dynamic memory allocation? Is there any advantages of
it?
3. Explain- i) calloc() ii) malloc() iii) realloc() iv) free()
182
Dynamic Memory Allocation in C
• The process of allocating memory at runtime is known as dynamic memory
allocation.
• Library routines known as memory management functions are used for allocating
and freeing memory during execution of a program.
• These functions are defined in stdlib.h header file.
Function Description
malloc() allocates requested size of bytes and returns a void pointer pointing to the
first byte of the allocated space
calloc() allocates space for an array of elements, initialize them to zero and then
returns a void pointer to the memory
free releases previously allocated memory
realloc modify the size of previously allocated space
183
malloc()
• The name "malloc" stands for memory allocation.
• The malloc() function reserves a block of memory of the specified number of
bytes. And, it returns a pointer of type void which can be casted into pointer of
any form.
• Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
• Example:
ptr = (int*) malloc(100 * sizeof(int));
• Considering the size of int is 4 bytes, this statement allocates 400 bytes of
memory. And, the pointer ptr holds the address of the first byte in the allocated
memory.
• However, if the space is insufficient, allocation fails and returns a NULL pointer.
https://www.programiz.com/c-programming/c-dynamic-memory-allocation
184
Calloc
• The name "calloc" stands for contiguous allocation.
• The malloc() function allocates a single block of memory. Whereas, calloc()
allocates multiple blocks of memory and initializes them to zero.
• Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
• Example:
ptr = (float*) calloc(25, sizeof(float));
• This statement allocates contiguous space in memory for 25 elements each with
the size of float.
https://www.programiz.com/c-programming/c-dynamic-memory-allocation
185
calloc() and malloc()
https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/
186
Example
Malloc
Calloc
187
C realloc()
• “realloc” or “re-allocation” method is used to dynamically change the memory
allocation of a previously allocated memory.
• In other words, if the memory previously allocated with the help of malloc or
calloc is insufficient, realloc can be used to dynamically re-allocate memory.
• If the dynamically allocated memory is insufficient or more than required, you can
change the size of previously allocated memory using realloc() function
https://www.programiz.com/c-programming/c-dynamic-memory-allocation
https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/
188
C realloc()
https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/
189
free()
• “free” method is used to dynamically de-allocate the memory.
• The memory allocated using functions malloc() and calloc() are not de-allocated
on their own.
• Hence the free() method is used, whenever the dynamic memory allocation takes
place. It helps to reduce wastage of memory by freeing it.
https://www.programiz.com/c-programming/c-dynamic-memory-allocation
free(ptr);
Syntax:
190
free()
https://www.programiz.com/c-programming/c-dynamic-memory-allocation
191
Diffrence between malloc() and calloc()
malloc calloc
The name malloc stands for memory allocation. The name calloc stands for contiguous allocation.
void *malloc(size_t n) returns a pointer to n bytes of
uninitialized storage, or NULL if the request cannot
be satisfied. If the space assigned by malloc() is
overrun, the results are undefined.
void *calloc(size_t n, size_t size)returns a pointer to
enough free space for an array of n objects of the
specified size, or NULL if the request cannot be
satisfied. The storage is initialized to zero.
malloc() takes one argument that is, number of
bytes.
calloc() take two arguments those are: number of
blocks and size of each block.
syntax of malloc():
void *malloc(size_t n);
Allocates n bytes of memory. If the allocation
succeeds, a void pointer to the allocated memory is
returned. Otherwise NULL is returned.
syntax of calloc():
void *calloc(size_t n, size_t size);
Allocates a contiguous block of memory large
enough to hold n elements of sizebytes each. The
allocated region is initialized to zero.
malloc is faster than calloc. calloc takes little longer than malloc because of the
extra step of initializing the allocated memory by
zero. However, in practice the difference in speed is
very tiny and not recognizable.
192
Similarities Between Malloc and Calloc
• The pointer returned by malloc or calloc has the proper alignment for the object
in question, but it must be cast into the appropriate type.
• Proper alignment means the value of the returned address is guaranteed to be an
even multiple of alignment. The value of alignment must be a power of two and
must be greater than or equal to the size of a word.
• The malloc(), calloc() functions will fail if:
• The physical limits of the system are exceeded by n bytes of memory which
cannot be allocated.
• There is not enough memory available to allocate n bytes of memory; but the
application could try again later.
193
Important Function References
194
Important Function References
195
Important Function References
196
Palindrome
197
References
Books:
• Let Us C by Yashavant
• ANSI C- Balaguruswamy
Web Resources-
• https://www.studytonight.com/c
• https://www.tutorialspoint.com/cprogramming/
• https://www.programiz.com/c-programming
Exam Aid
C at a Glance
13
199
Basic Theory: What, why and how
• Variables, constants
• Data types
• Conditions ( if..else, if..else if..else,nested if else, switch, goto…label)
• Loops (for, while, do while)
• Functions (user define functions)
• Structure & Union
• Arrays
• Pointers
Ex- What is pointer? Why we use pointer? How to use it? Explain with an example.
200
Basic Syntax
• Variables, constants
• Comments
• Conditions ( if..else, if..elseif..else, nested if else, switch …. etc)
• Loops (for, while, do while, nested for)
• Functions (user define functions)
• Structure & Union
• Arrays
• Pointers
Etc.
Cover the contents given in the syllabus.
201
C Program and its Structure
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
Hello World
Different parts of C program
• Pre-processor
• Header file
• Function
• Variables
• Statements & expressions
• Comments
202
Variable, constant syntax
• dataType name= initialValue; // variable declaration and initialization
int number1=2;
• const dataType name= value;
const float pi=3.1416;
• Comment
// line comment
/*
paragraph comment
*/
203
Array syntax
• Single Dimensional Array syntax
dataType name[arraySize]={ arrayElements};
• Two-dimensional arrays are declared as follows,
data-type array-name[row-size][column-size]
• String
char name[stringSize+1]=“String”
204
Conditional Syntax
Simple if…else
if(condition)
{
Statement;
}
else
{
Statement;
}
if…elseif
if(condition)
{ Statement; }
else if(condition)
{ Statement; }
….
else
{ Statement; }
Nested If…else
if(condition)
{
if (condition){
statement;
}
else{ statement;}
}
else{
statement;
}
205
Conditional Syntax
Conditional operator
condition ? TrueExpression1 : FalseExpression2;
Switch
switch(value)
{
case 1:
statement;
break;
case 2:
statement;
break;
…..
default:
statement;
}
206
Conditional Syntax
Goto
{
….
go to label;
Label:
statements;
}
207
Loop
for loop
for(initialization; condition; increment/ decrement)
{
statement;
}
While loop
Initialization;
while(condition)
{
statement;
increment/ decrement
}
208
Loop
Do While loop
do
{
statement;
increment/ decrement
} while(condition)
209
Function
• User define functions may be defined as
Calling a Function:
functionName(type1 argument1, type2 argument2, ...)
Defining a Function:
returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}
210
Errors
• Logical and syntax error
• Definition error
• Data type error
Follow the reference book exercise sections for practice problem.
211
Find Values
• Basic operator operations
• Basic loops/ conditions
• User defined functions
212
Functions Description
• Standard input output functions (printf, scanf, gets, etc)
• Arithmatic/ Math library functions ( sin, floor, ceil, pow…etc)
• String functions (strcpy, strcat,….)
• File input/ output functions (fopen, fclose,….etc)
• Memory Allocation Functions ( calloc, malloc,… etc)
Follow the reference book exercise sections for practice problem.
213
Programming Problem
• Basic input output (printf, scanf)
• Basic formula based
• If.. Else condition based
• Loop based
• String based
• Array program
Practice Problem
Section
14
215
Arithmatic Problem
• Write a C program to calculate the following calculation
if two integer numbers are given as input
• Sum
• Difference
• Product
• Division
Write a program to find whether a number is
• Even or odd
• Prime or non-prime
• Positive or negative
Problem: Number
216
Geometry Problem: Circle
• Write a C program to find area and perimeter of a
circle if the radius/diameter is given from user as
input.
1. Write a C program to find area and perimeter of a
rectangle if the length and width are given from user as
input. Area of a triangle is given by
𝐴 = 𝑆 𝑆 − 𝑎 𝑆 − 𝑏 𝑆 − 𝐶 , where a, b, c are sides of a
triangle and 𝑆 = (𝑎 + 𝑏 + 𝑐)/2.
1. Given value: a, b. Find c?
2. Given value: a, c. Find b?
3. Given theta = 45°. Find the values of
• Sin
• Cos
• Tan
Geometry Problem: Triangle
Circle
217
Arithmatic Problem
• Write a program to find the sum and average of
five numbers taken from user as keyboard input.
• Write a program to convert Celsius to Fahrenheit (or
Fahrenheit to Celsius). Take user input for temperature
in Celsius and print the converted value in Fahrenheit
𝐹 =
9 × 𝐶
5
+ 32 𝑜𝑟 𝐶 =
𝐹 − 32
1.8
Or, Temperature of a city in Fahrenheit degrees is input
through the keyboard. Write a program to convert this
temperature into Centigrade degrees.
Problem: Conversion of Temperature
218
Arithmatic Problem: Interest Calculation
• You take input the following information-
1. Principle (P)
2. Simple Interest Rate (r)
3. Year (n)
• Print out the total money after the given duration.
𝑪𝒂𝒑𝒊𝒕𝒂𝒍 𝒘𝒊𝒕𝒉 𝒊𝒏𝒕𝒆𝒓𝒆𝒔𝒕 = 𝑷 + 𝑷𝒏𝒓
Write a C program to find if a given year is leap year or not.
Arithmatic Problem: Leap Year Calculation
219
Arithmatic Problem: Salary Calculation
• Write a program to calculate salary of a salesman. He is given bonus and
commission based on number of products sold. While given the following
information.
Basic Salary= 22,000, Bonus Rate= 200, Commission= 0.02
Take user input: Number of products sold, and the price of the product.
[𝐻𝑖𝑛𝑡𝑠:
𝐵𝑜𝑛𝑢𝑠 = 𝐵𝑜𝑛𝑢𝑠 𝑟𝑎𝑡𝑒 × 𝑞𝑢𝑎𝑛𝑡𝑖𝑡𝑦
𝐶𝑜𝑚𝑚𝑖𝑠𝑠𝑖𝑜𝑛 = 𝐶𝑜𝑚𝑚𝑖𝑠𝑠𝑖𝑜𝑛 × 𝑞𝑢𝑎𝑛𝑡𝑖𝑡𝑦 × 𝑝𝑟𝑖𝑐𝑒
𝐺𝑟𝑜𝑠𝑠 𝑆𝑎𝑙𝑎𝑟𝑦 = 𝐵𝑎𝑠𝑖𝑐 𝑆𝑎𝑙𝑎𝑟𝑦 + 𝑏𝑜𝑛𝑢𝑠 + 𝑐𝑜𝑚𝑚𝑖𝑠𝑠𝑖𝑜𝑛 ]
220
Electrical Arithmatic Problem
1. If for a dc circuit resistance is 50 ohm, delivered power is 100W. What will be
output voltage?
2. If 3 fans of 75W run 6hrs/day for a month. Then what will be the utility bill at
the end of the month with a price of 7tk/unit.
221
Arithmatic Problem: Salary Calculation
• Ramesh’s basic salary is input through the keyboard. His technical
allowance is 40% of basic salary, and house rent allowance is 20% of
basic salary. Write a program to calculate his gross salary
Arithmatic Problem: Day Calculation
• Write a program to convert days into Month and days. Assume each month has 30
days.
[𝑚𝑜𝑛𝑡ℎ =
𝑑𝑎𝑦𝑠
30
, 𝑟𝑒𝑚𝑎𝑖𝑛𝑖𝑛𝑔 𝑑𝑎𝑦𝑠 = 𝑑𝑎𝑦𝑠% 30]
222
Arithmatic Problem: Grocery Calculation
• Take input of how much rice and sugar the user has bought and show him the
total cost of his product using a C program.
[𝐻𝑖𝑛𝑡𝑠: 𝑇𝑜𝑡𝑎𝑙 𝐶𝑜𝑠𝑡 = 𝑄𝑢𝑎𝑛𝑡𝑖𝑡𝑦 𝑖𝑛 𝐾𝐺 × 𝑈𝑛𝑖𝑡 𝑃𝑟𝑖𝑐𝑒]
Item Price/ Unit
Rice 30 Tk/ Kg
Sugar 100 Tk/ Kg
223
Logical Problem: CGPA Calculation
• Write a program to calculate CGPA while given the information of GPA and credits
semester wise.
• [𝐻𝑖𝑛𝑡𝑠: 𝐶𝐺𝑃𝐴 =
∑𝐺𝑃𝐴×𝑇𝑜𝑡𝑎𝑙 𝐶𝑟𝑒𝑑𝑖𝑡𝑠
∑ 𝑇𝑜𝑡𝑎𝑙 𝐶𝑟𝑒𝑑𝑖𝑡𝑠
]
• Answer: 3.85
Level Term Credit Hours
Earned, TCI
GPA
Earned,
GPAi
GPAi*TCi
1 1 21.00 3.73 78.330
1 2 21.00 3.92 82.320
2 1 19.50 3.96 77.220
2 2 19.00 3.80 72.200
Total 80.50 310.07
224
Logical Problem: Grade Calculation
• Take a user mark as input and print his grade according to the grade
table.
Marks Grade
100-80 A+
70-79 A
60-69 B
50-59 C
40-49 D
0-39 F
225
Logical Problem: Corona Symptoms
• Suppose that you want to create a simple C program to recommend
initial treatment based on basic symptoms shown as the given chart
below.
• You need to take user input for following symptoms whether the
patient has i) Fever, ii) Dry cough, iii) Shortness of breath and iv) Aches
& pain- in ‘y’ for yes and ‘n’ for no and accordingly recommend him
treatment. For example- if he answer all the symptoms in y, then he
will be a potential COVID-19 patient.
Fever Dry Cough Shortness of Breath Aches and Pain
COVID-19 y y y y
Common Cold n y n n
FLU y y n y
226
Logical Problem: Ticketing Booth
• Suppose you are making an automatic ticketing booth for a public transport as per
the following table
Ticket fee/ person Age < 20 years Gender
60 tk N M
50 tk N F
40 tk Y M
35 tk Y F
• * N for No, Y for yes, F for female, M for Male
• For example- if a person has age less than 20 years and gender is Female (F) then her ticket fee
will be 35 Tk.
• Now write a C program to take user input for age & gender and accordingly print his/ her ticket
fee.
227
Problem with Loop implementation
• Write a program to find the sum and average of the following series-
• 1+2+3+…+100
• 2+4+6+…+100
• 1+3+5+…+100
• 3+6+9+…+99
• 1 +
1
2
+
1
3
+ ⋯ . +
1
100
• (2+4+6+…+100)+ (3+6+9+…+99)
228
Test Problem: Factorials Calculations
• Take user input.
• Find factorial of given number
• 0 != 1
• 6!= 6*5*4*3*2*1
229
Problem with Nested Loop implementation
Write a program to print the following print pattern using only one print statement.
*
* *
* * *
* * * *
Write a program to print the following print
pattern using only one print statement.
1
1 2
1 2 3
1 2 3 4
Write a program to print the following print
pattern using only one print statement.
1
2 3
4 5 6
7 8 9 10
230
Array Problem: finding highest
• Write a program to find the highest mark in the following set of data
Marks[6]={55, 60,39, 89, 75, 100}
Array Problem: Sorting
• Write a program to sort the following marks in ascending (or descending) order-
Marks[6]={55, 60,39, 89, 75, 100}

More Related Content

What's hot

Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem SolvingSukhendra Singh
 
Introduction to Computer and Programming - Lecture 01
Introduction to Computer and Programming - Lecture 01Introduction to Computer and Programming - Lecture 01
Introduction to Computer and Programming - Lecture 01hassaanciit
 
Von-Neumann machine and IAS architecture
Von-Neumann machine and  IAS architectureVon-Neumann machine and  IAS architecture
Von-Neumann machine and IAS architectureShishir Aryal
 
Assembly language
Assembly languageAssembly language
Assembly languagegaurav jain
 
Introduction to Computers Lecture # 9
Introduction to Computers Lecture # 9Introduction to Computers Lecture # 9
Introduction to Computers Lecture # 9Sehrish Rafiq
 
Unit i (part2) b.sc
Unit i (part2)   b.scUnit i (part2)   b.sc
Unit i (part2) b.scHepsijeba
 
Ch0 computer systems overview
Ch0 computer systems overviewCh0 computer systems overview
Ch0 computer systems overviewAboubakarIbrahima
 
Block diagram (computer programming & utilization)
Block diagram (computer programming & utilization)Block diagram (computer programming & utilization)
Block diagram (computer programming & utilization)Digvijaysinh Gohil
 
Computer Organization and Assembly Language
Computer Organization and Assembly LanguageComputer Organization and Assembly Language
Computer Organization and Assembly Languagefasihuddin90
 
Embedded systems tools & peripherals
Embedded systems   tools & peripheralsEmbedded systems   tools & peripherals
Embedded systems tools & peripheralsimtiazalijoono
 
VTU University Micro Controllers-06ES42 lecturer Notes
VTU University Micro Controllers-06ES42 lecturer NotesVTU University Micro Controllers-06ES42 lecturer Notes
VTU University Micro Controllers-06ES42 lecturer Notes24x7house
 
Part I:Introduction to assembly language
Part I:Introduction to assembly languagePart I:Introduction to assembly language
Part I:Introduction to assembly languageAhmed M. Abed
 

What's hot (20)

Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
Csc240 lecture 1
Csc240   lecture 1Csc240   lecture 1
Csc240 lecture 1
 
Assembly language
Assembly languageAssembly language
Assembly language
 
Introduction to Computer and Programming - Lecture 01
Introduction to Computer and Programming - Lecture 01Introduction to Computer and Programming - Lecture 01
Introduction to Computer and Programming - Lecture 01
 
CSC204PPTNOTES
CSC204PPTNOTESCSC204PPTNOTES
CSC204PPTNOTES
 
Von-Neumann machine and IAS architecture
Von-Neumann machine and  IAS architectureVon-Neumann machine and  IAS architecture
Von-Neumann machine and IAS architecture
 
Assembly language
Assembly languageAssembly language
Assembly language
 
Introduction to Computers Lecture # 9
Introduction to Computers Lecture # 9Introduction to Computers Lecture # 9
Introduction to Computers Lecture # 9
 
E.s unit 6
E.s unit 6E.s unit 6
E.s unit 6
 
Assembly language
Assembly languageAssembly language
Assembly language
 
Unit i (part2) b.sc
Unit i (part2)   b.scUnit i (part2)   b.sc
Unit i (part2) b.sc
 
Ch0 computer systems overview
Ch0 computer systems overviewCh0 computer systems overview
Ch0 computer systems overview
 
Lecture 22 - Error Handling
Lecture 22 - Error HandlingLecture 22 - Error Handling
Lecture 22 - Error Handling
 
Block diagram (computer programming & utilization)
Block diagram (computer programming & utilization)Block diagram (computer programming & utilization)
Block diagram (computer programming & utilization)
 
Software
SoftwareSoftware
Software
 
System software
System softwareSystem software
System software
 
Computer Organization and Assembly Language
Computer Organization and Assembly LanguageComputer Organization and Assembly Language
Computer Organization and Assembly Language
 
Embedded systems tools & peripherals
Embedded systems   tools & peripheralsEmbedded systems   tools & peripherals
Embedded systems tools & peripherals
 
VTU University Micro Controllers-06ES42 lecturer Notes
VTU University Micro Controllers-06ES42 lecturer NotesVTU University Micro Controllers-06ES42 lecturer Notes
VTU University Micro Controllers-06ES42 lecturer Notes
 
Part I:Introduction to assembly language
Part I:Introduction to assembly languagePart I:Introduction to assembly language
Part I:Introduction to assembly language
 

Similar to C Programming Basics

Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterHossam Hassan
 
computer languages
computer languagescomputer languages
computer languagesRajendran
 
introductiontocomputerprogramming.pptx
introductiontocomputerprogramming.pptxintroductiontocomputerprogramming.pptx
introductiontocomputerprogramming.pptxHazardRhenz1
 
Introduction to computers and programming languages
Introduction to computers and programming languages Introduction to computers and programming languages
Introduction to computers and programming languages binoysatheesh
 
Compilers and interpreters
Compilers and interpretersCompilers and interpreters
Compilers and interpretersRAJU KATHI
 
Compiler Design Introduction
Compiler Design IntroductionCompiler Design Introduction
Compiler Design IntroductionKuppusamy P
 
Computer Programming In C.pptx
Computer Programming In C.pptxComputer Programming In C.pptx
Computer Programming In C.pptxchouguleamruta24
 
Programming languages,compiler,interpreter,softwares
Programming languages,compiler,interpreter,softwaresProgramming languages,compiler,interpreter,softwares
Programming languages,compiler,interpreter,softwaresNisarg Amin
 
3. basic organization of a computer
3. basic organization of a computer3. basic organization of a computer
3. basic organization of a computerSHIKHA GAUTAM
 
Embedded programming Embedded programming (1).pptx
Embedded programming Embedded programming (1).pptxEmbedded programming Embedded programming (1).pptx
Embedded programming Embedded programming (1).pptxlematadese670
 
Computer-charecteristics,types of languages,translators
Computer-charecteristics,types of languages,translatorsComputer-charecteristics,types of languages,translators
Computer-charecteristics,types of languages,translatorsVarshaSivashanker
 
C program execution and algorithm
C program execution and algorithm C program execution and algorithm
C program execution and algorithm Kunal Pandhram
 
System software module 1 presentation file
System software module 1 presentation fileSystem software module 1 presentation file
System software module 1 presentation filejithujithin657
 
Programming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages ConceptsProgramming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages Conceptsimtiazalijoono
 

Similar to C Programming Basics (20)

lec 1.pptx
lec 1.pptxlec 1.pptx
lec 1.pptx
 
Program Logic and Design
Program Logic and DesignProgram Logic and Design
Program Logic and Design
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals master
 
computer languages
computer languagescomputer languages
computer languages
 
introductiontocomputerprogramming.pptx
introductiontocomputerprogramming.pptxintroductiontocomputerprogramming.pptx
introductiontocomputerprogramming.pptx
 
Introduction to computers and programming languages
Introduction to computers and programming languages Introduction to computers and programming languages
Introduction to computers and programming languages
 
Compilers and interpreters
Compilers and interpretersCompilers and interpreters
Compilers and interpreters
 
01CHAP_1.PPT
01CHAP_1.PPT01CHAP_1.PPT
01CHAP_1.PPT
 
SYSTEM SOFTWARE
SYSTEM SOFTWARE SYSTEM SOFTWARE
SYSTEM SOFTWARE
 
Compiler Design Introduction
Compiler Design IntroductionCompiler Design Introduction
Compiler Design Introduction
 
Computer Programming In C.pptx
Computer Programming In C.pptxComputer Programming In C.pptx
Computer Programming In C.pptx
 
Programming languages,compiler,interpreter,softwares
Programming languages,compiler,interpreter,softwaresProgramming languages,compiler,interpreter,softwares
Programming languages,compiler,interpreter,softwares
 
3. basic organization of a computer
3. basic organization of a computer3. basic organization of a computer
3. basic organization of a computer
 
Embedded programming Embedded programming (1).pptx
Embedded programming Embedded programming (1).pptxEmbedded programming Embedded programming (1).pptx
Embedded programming Embedded programming (1).pptx
 
Week 01.pdf
Week 01.pdfWeek 01.pdf
Week 01.pdf
 
Computer-charecteristics,types of languages,translators
Computer-charecteristics,types of languages,translatorsComputer-charecteristics,types of languages,translators
Computer-charecteristics,types of languages,translators
 
C program execution and algorithm
C program execution and algorithm C program execution and algorithm
C program execution and algorithm
 
System software module 1 presentation file
System software module 1 presentation fileSystem software module 1 presentation file
System software module 1 presentation file
 
Programming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages ConceptsProgramming Fundamentals and Programming Languages Concepts
Programming Fundamentals and Programming Languages Concepts
 
Microassembler a10
Microassembler a10Microassembler a10
Microassembler a10
 

Recently uploaded

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 

Recently uploaded (20)

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 

C Programming Basics

  • 1. Computer Programming CSE 2109 Credit 3.00 C Programming Md. Hassanul Karim Roni Lecturer EEE, BAUST
  • 2. Md. Hassanul Karim Roni Lecturer, EEE Bangladesh Army University of Engineering and Technology (BAUST) Present Address: BAUST, Saidpur Cant, Nilphamary hassanulkarim.roni@gmail.com Hassanul Karim Roni Facebook Group: HK Roni, Dept. of EEE Personal website: hkroni.cloudaccess.host f
  • 3. 3 Course Contents • Introduction to digital computers. • Programming languages, algorithms and flow charts. • Structured Programming using C. • Variable and constants, • operators, • expressions, • control statements, • function, • arrays, • pointers, • structure unions. • User defined data types. • Input output and files. • Object oriented Programming using C++: • Introduction, classes and objects. • Polyorphism, function and operator overloading, inheritance.
  • 4. 4 Software http://www.codeblocks.org/downloads/26 Download the mingw version codeblocks-17.12mingw-setup.exe https://code.visualstudio.com/Download Online Compiler https://www.tutorialspoint.com/compile_c_online.php https://www.onlinegdb.com/online_c_compiler
  • 9. 9 Reference Website https://www.tutorialspoint.com/cprogramming/ https://www.udemy.com/ https://www.coursera.org/ http://hkroni.cloudaccess.host/academic-courses/ https://www.cprogramming.com/ Online Courses You will get from this site • Class Lectures • Class Resources • Assignments/ Tests Questions • Important Links • Software and Download Links • Class Test Marks • Quiz Tests • My other courses
  • 11. 11 Questions 1. Define cache memory. 2. Define primary and secondary memory. Differentiate between RAM and ROM. 3. Draw the block diagram of Von Neumann Computer Architecture. 4. Draw a block diagram to illustrate the basic organization of a computer system and explain the functions of the various units. 5. Discuss the various storage classes of C. 6. Explain various input and output devices.
  • 12. 12 Types of Components A digital computer consists of mainly- • Hardware • Software
  • 13. 13 Basic Hardware of a Personal Computer • Monitor • Motherboard • CPU (Microprocessor) • Expansion Card • Power Supply • Storage • Keyboard • Mouse • Optical Disc Drive
  • 14. 14 Classification of Hardware Four Major Classes of Hardware 1. CPU – Central Processing Unit • Makes decision Makes decisions, performs computations, and delegates input/output requests 2. Memory • Stores information 3. Input Devices • Gets information from the user to the computer 4. Output Devices • Sends information from computer to the user
  • 17. 17 Computer Memory Memory is primarily of three types − • Cache Memory • Primary Memory/Main Memory • Secondary Memory
  • 18. 18 Computer Memory: Cache Memory • Cache memory is a very high speed semiconductor memory which can speed up the CPU. • It acts as a buffer between the CPU and the main memory. • It is used to hold those parts of data and program which are most frequently used by the CPU. • The parts of data and programs are transferred from the disk to cache memory by the operating system, from where the CPU can access them.
  • 19. 19 Computer Memory: Primary Memory • Primary memory holds only those data and instructions on which the computer is currently working. • It has a limited capacity and data is lost when power is switched off. • It is generally made up of semiconductor device. • These memories are not as fast as registers. The data and instruction required to be processed resides in the main memory. • It is divided into two subcategories RAM and ROM.
  • 21. 21 RAM (Random Access Memory) • It is also called as read write memory or the main memory or the primary memory. • The programs and data that the CPU requires during execution of a program are stored in this memory. • It is a volatile memory as the data loses when the power is turned off. • RAM is further classified into two types- SRAM (Static Random Access Memory)and DRAM (Dynamic Random Access Memory).
  • 23. 23 RAM vs. ROM Definition • RAM is a form of data storage that can be accessed randomly at any time, in any order and from any physical location., allowing quick access and manipulation. • Read-only memory or ROM is also a form of data storage that can not be easily altered or reprogrammed. • Stores instructions that are not nesccesary for re-booting up to make the computer operate when it is switched off. • They are hardwired. Stands for Random Access Memory Read-only memory Use RAM allows the computer to read data quickly to run applications. It allows reading and writing. ROM stores the program required to initially boot the computer. It only allows reading. Volatility RAM is volatile i.e. its contents are lost when the device is powered off. It is non-volatile i.e. its contents are retained even when the device is powered off. Types The two main types of RAM are static RAM and dynamic RAM. The types of ROM include PROM, EPROM and EEPROM.
  • 24. 24 Computer Memory: Secondary Memory • This type of memory is also known as external memory or non-volatile. • It is slower than the main memory. • These are used for storing data/information permanently. • CPU directly does not access these memories, instead they are accessed via input-output routines. • The contents of secondary memories are first transferred to the main memory, and then the CPU can access it. • For example, disk, CD-ROM, DVD, etc.
  • 25. 25 Test Your Self • Monitor • Keyboard • CPU (The Box) • Floppy Drive • CD-ROM • Printer • Scanner • Modem • Digital Camera • CD Writer/Burner • Hard Drive • LCD Projector • Laser Pointer • Network Card • Bluetooth Card • Speakers
  • 26. 26 Computer Software Computer Software System Software Application Software
  • 27. 27 Operating System • Controls and manages the computing resources • Examples • Windows, Unix, MSDOS, • Important services that an operating system provides: • Security: prevent unauthorized users from accessing the system • Commands to manipulate the file system • Input and output on a variety of devices • Window management
  • 28. 28 Application Software • Application software makes computer popular and easy to use • Common application software: • Microsoft Office • Firefox, Opera, Chrome • Photo Shop, Photo-Paint • Media Player, VLC player, KM Player • Dreamweaver, code block
  • 29. 29 What is a (programming) language? • A program needs to be written in a language • There are many programming languages • Low-level, understandable by a computer • High-level, needs a translator! • C is a high level programming language A sequence of instructions A program (in computer language) An algorthm (in human language)
  • 30. 30 Levels of programming language • Machine binary language: unintelligible • Low-level assembly language • Mnemonic names for machine operations • Explicit manipulation of memory addresses • Machine-dependent • High-level language • Readable • Machine-independent
  • 31. 31 An example of Programs Machine binary language Low-level assembly High-level
  • 32. 32 Von Neumann Computer Architecture
  • 34. 34 Questions 1. Define the following: i) High level language ii) Machine Language iii) Mid-Level Language 2. Define- i) Assembler ii) Compiler iii) Interpreter 3. What are the basic features of C programming? 4. Importance of C Programming. 5. Mention some applications of C programming. 6. What are the steps of executing a C Program? Explain the process of compiling and running a C program using a suitable flowchart. 7. Why and when do we use #define directive? 8. What is preprocessor directives? Why they are used? 9. Why and when do we use #include directive? 10. Why do we need to use comment in programs? 11. Explain the basic parts of a C program using a C program that finds the average of 3 numbers.
  • 35. 35 Programs used in C • Assembler • Compiler • Interpreter
  • 36. 36 Assembler • Assembler is a computer program which is used to translate program written in Assembly Language in to machine language. The translated program is called as object program. Assembler checks each instruction for its correctness and generates diagnostic messages, if there are mistakes in the program. • Various steps of assembling are: 1. Input source program in Assembly Language through an input device. 2. Use Assembler to produce object program in machine language. 3. Execute the program.
  • 37. 37 Compiler • A compiler is a program that translates a program written in HLL to executable machine language. • For example: Turbo C, Code Blocks, Dev C++ etc. The function of a complier includes the following: 1. To translate HLL source program to machine codes. 2. To trace variables in the program 3. To include linkage for subroutines. 4. To allocate memory for storage of program and variables. 5. To generate error messages, if there are errors in the program.
  • 38. 38 Interpreter • The basic purpose of interpreter is same as that of complier. In compiler, the program is translated completely and directly executable version is generated. Whereas interpreter translates each instruction, executes it and then the next instruction is translated and this goes on until end of the program. In this case, object code is not stored and reused. • Every time the program is executed, the interpreter translates each instruction freshly. It also has program diagnostic capabilities. However, it has some disadvantages as below: 1. Instructions repeated in program must be translated each time they are executed. 2. Because the source program is translated fresh every time it is used, it is slow process or execution takes more time. Approx. 20 times slower than complier.
  • 40. 40 Features of C • It is a robust language with rich set of built-in functions and operators that can be used to write any complex program. • The C compiler combines the capabilities of an assembly language with features of a high-level language. • Programs Written in C are efficient and fast. This is due to its variety of data type and powerful operators. It is many time faster than BASIC. • C is highly portable this means that programs once written can be run on another machines with little or no modification. • Another important feature of C program, is its ability to extend itself. • A C program is basically a collection of functions that are supported by C library. We can also create our own function and add it to C library. • C language is the most widely used language in operating systems and embedded system development today.
  • 41. 41 Why learn C? • Two Step Learning Process: One should first learn all the language elements very thoroughly using C language before migrating to C++, C# or Java. • Basic Programming Skill and introduction to basic programming elements through C. • Useful Elements: Though many C++ and Java based programming tools and frameworks have evolved over the years, yet knowingly or unknowingly while using these frameworks and tools you would be still required to use the core C language elements. • Operating Systems in C: Major parts of popular operating systems like Windows, UNIX, Linux is still written in C.
  • 42. 42 Why learn C? • Electronics Devices OS in C: Common consumer devices like microwave oven, washing machines and digital cameras has an operating system and a program embedded in this devices. These programs not only have to run fast but also have to work in limited amount of memory. No wonder that such programs are written in C. • Faster Game Experience: Many popular gaming frameworks have been built using C language. The essence of all such games is speed. This is where C language scores over other languages. • At times one is required to very closely interact with the hardware devices. Since C provides several language elements that make this interaction feasible without compromising the performance it is the preferred choice of the programmer.
  • 43. 43 Steps in Learning C In C language characters are grouped into the following catagories, 1. Letters (all alphabets a to z & A to Z). 2. Digits (all digits 0 to 9). 3. Special characters, (such as colon :, semicolon ; , period ., underscore _ , ampersand & etc). 4. White spaces.
  • 44. 44 First C Program and its Structure #include <stdio.h> int main() { printf("Hello World"); return 0; } Hello World Different parts of C program • Pre-processor • Header file • Function • Variables • Statements & expressions • Comments
  • 45. 45 Important to Remember • C is a case sensitive language so all C instructions must be written in lower case letter. • All C statement must end with a semicolon. • Whitespace is used in C to describe blanks and tabs. • Whitespace is required between keywords and identifiers.
  • 46. 46 Questions 1. Write short notes on: C Tokens, Keywords, Identifiers , Constants, Variables 2. What are the rules to name an Identifier? 3. Define variable. Mention the rules of naming a variable in C language. 4. Define- local variable, global variable and static variable and Register variable. 5. Define constant. Mention the rules of naming a constant in C language 6. Mention the names of various types of C token with examples. 7. What are the white spaces used in C programming? 8. What are the basic data type associated with C? Explain with examples. 9. What are the rules to construct real constant? 10. What are the rules for constructing a variable? 11. What are the different control instruction in C language? 12. What is typecasting in C programming?
  • 47. 47 Questions 1. Find valid and invalid variable names. If invalid mention the proper reason- • First_tag • char • Price$ • Group one • Int_type • _Team1 • Mark-1 • 1_team 2. Describe the basic data types in C? How can you extend the range of values they represent? 3. Compare ‘x’ and “x” for their types, the storage they occupy and comment if they are same? 4. What is the difference between the constants 7, ‘7’, “7”? 5. Is it possible to store 32768 in an int data type variable? If possible, explain how.
  • 48. 48 Constants • A constant is an entity that doesn’t change whereas a variable is an entity that may change.
  • 49. 49 Variable • An entity that may vary during program execution is called a variable. Rules for Constructing Variable Names • A variable name is any combination of 1 to 31 alphabets, digits or underscores. • The first character in the variable name must be an alphabet or underscore. • No commas or blanks are allowed within a variable name. • No special symbol other than an underscore (as in gross_sal) can be used in a variable name. • Keywords are not allowed to be used as variable name.
  • 50. 50 Types of Variables: Local Variable Local Variables: The variables which are declared inside the function, compound statement (or block) are called Local variables. • They are available only inside the function in which they are defined. • The same variable names can be used in a different function and they will not conflict with each other void function_1() { int a = 1, b = 2; } void function_2() { int a = 10, b = 20; }
  • 51. 51 Types of Variables: Global Variable • The variables declared outside any function are called global variables. • They are not limited to any function. Any function can access and modify global variables. • Global variables are automatically initialized to 0 at the time of declaration. • Global variables are generally written before main() function. • Unlike local variables, global variables are not destroyed as soon as the function ends. They are available to any function until the program is executing. #include<stdio.h> void func_1(); void func_2(); int a, b = 10; // declaring and initializing global variables int main() { printf("Global a = %dn", a); printf("Global b = %dnn", b); func_1(); func_2(); return 0; } void func_1() { printf("From func_1() Global a = %dn", a); printf("From func_1() Global b = %dnn", b); } void func_2() { int a = 5; printf("Inside func_2() a = %dn", a); }
  • 52. 52 Types of Variables: Static Variable • A Static variable is able to retain its value between different function calls. • The static variable is only initialized once, if it is not initialized, then it is automatically initialized to 0. #include<stdio.h> void func_1(); int a, b = 10; int main() { func_1(); func_1(); func_1(); return 0; } void func_1() { int a = 1; static int b = 100; printf("a = %dn", a); printf("b = %dnn", b); a++; b++; }
  • 53. 53 Difference between local and global variables Basis for Comparison Local Variable Global Variable Declaration Variables are declared inside a function. Variables are declared outside any Scope Within a function, inside which they are declared. Throughout the program. Access Accessed only by the statements, inside a function in which they are declared. Accessed by any statement in the entire program. Life Created when the function block is entered and destroyed upon exit. Remain in existence for the entire time your program is executing. Storage Local variables are stored on the stack, unless specified. Stored on a fixed location decided by a compiler
  • 54. 54 Keywords in C • Keywords are preserved words that have special meaning in C language. • The meaning of C language keywords has already been described to the C compiler. These meaning cannot be changed. • keywords cannot be used as variable names because that would try to change the existing meaning of the keyword, which is not allowed. • There are total 32 keywords in C language. auto double int struct break else long switch case enum register typedef const extern return union char float short unsigned continue for signed volatile default goto sizeof void auto double int struct
  • 55. 55 Identifiers • In C language identifiers are the names given to variables, constants, functions and user-define data. • 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 identifiers 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.
  • 56. 56 Data types in C Language • Data types specify how we enter data into our programs and what type of data we enter. • C language supports 2 different type of data types: 1. Primary data types: integer(int), floating point(float), character(char) and void. 2. Derived data types: array, structure, union and pointer.
  • 57. 57 Modifiers in C There are 5 modifiers available in C programming language as follows. • Short • Long • Signed • Unsigned • long long
  • 58. 58 Integer type Type Size(bytes) Range int or signed int 2= 216bits -32,768 to 32767 unsigned int 2= 216 bits 0 to 65535 short int or signed short int 1= 28 bits -128 to 127 unsigned short int 1= 28bits 0 to 255 long int or signed long int 4= 232bits -2,147,483,648 to 2,147,483,647 unsigned long int 4= 232 bits 0 to 4,294,967,295
  • 59. 59 Difference between signed and unsigned data type • Signed variables, such as signed integers will allow you to represent numbers both in the positive and negative ranges. • Unsigned variables, such as unsigned integers, will only allow you to represent numbers in the positive. • Unsigned and signed variables of the same type (such as int and byte) both have the same range (range of 65,536 and 256 numbers, respectively), but unsigned can represent a larger magnitude number than the corresponding signed variable. • For example, an unsigned byte can represent values from 0 to 255 (numeric value 0 to 65,536) while signed byte can represent -128 to 127 (numeric value -32768 to 32767).
  • 60. 60 Is that possible to store 32768 in an int data type variable? • int data type only capable of storing values between – 32768 to 32767. • To store 32768 a modifier needs to use with int data type. • Long int can use and also if there is no any negative values unsigned int is also possible to use.
  • 62. 62 Key Points To Remember In C Printf() And Scanf(): • printf() is used to display the output and scanf() is used to read the inputs. • printf() and scanf() functions are declared in “stdio.h” header file in C library. • All syntax in C language including printf() and scanf() functions are case sensitive.
  • 63. 63 Print a number int age=20; printf("My age is %d",age); int price=1.99; printf("Age:%f",price); printf("'%4.3f'", 10.345642);
  • 64. 64 Print multiple Values char name[]="poftut"; int age=2; char city[]="ankara"; printf("Name:%s , Age:%d , City:%s", name, age, city);
  • 65. 65 Print Special Symbol • printf("% is percent sign."); or • printf("%% is percent sign.");
  • 66. 66 Printf Special Characters a audible alert n newline, or linefeed t tab v vertical tab backslash
  • 67. 67 Scanf() • In C programming language, scanf() function is used to read character, string, numeric data from keyboard The scanf() function uses the same placeholders as printf: • int uses %d • float uses %f • char uses %c • character strings use %s
  • 68. 68 Example #include <stdio.h> int main() { int a, b, c; printf("Enter the first value:"); scanf("%d", &a); printf("Enter the second value:"); scanf("%d", &b); c = a + b; printf("%d + %d = %dn", a, b, c); return 0; }
  • 71. 71 Questions 1. What are the different operators used in C? 2. Briefly explain arithmetic and bitwise operators. 3. Differentiate between ++m and m++ using suitable example. 4. What does the && operator do in a C program? Explain with an example. 5. What is the difference between the expression “++a” and “a++”? 6. Differentiate between increment and decrement operators 7. Differentiate between bitwise AND (&) and logical AND (&&) operator in C language using proper example. 8. Using conditional operator statement (?: operator) write a C program to find whether the given number is even or odd. 9. Describe the difference between ‘=’ and ‘= =’ symbols in C programming?
  • 72. 72 C operators C operators can be classified into following types: • Arithmetic operators • Relational operators • Logical operators • Bitwise operators • Assignment operators • Conditional operators • Special operators A + B * C Operators Operands According to the number of operands • Unary operator (a++, a--) • Binary operator (a+b) • Ternary operator (?:) ( condition? Statement if true : statement if false)
  • 73. 73 Arithmetic Operator Operator Description + adds two operands - subtract second operands from first * multiply two operand / divide numerator by denominator % remainder of division ++ Increment operator - increases integer value by one -- Decrement operator - decreases integer value by one int a=10; printf(‘%d’, a++); int b=10; printf(‘%d’, ++b); int c=10; int d=3; printf(‘%d’,c%d); ? Arithmetic Operator Operator Description + adds two operands - subtract second operands from first * multiply two operand / divide numerator by denominator % remainder of division ++ Increment operator - increases integer value by one -- Decrement operator - decreases integer value by one
  • 74. 74 Assignment Operator 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
  • 75. 75 Relational Operator 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
  • 76. 76 Logical operators Operator Description Example && Logical AND (a && b) is false || Logical OR (a || b) is true ! Logical NOT (!a) is false
  • 77. 77 Bitwise operators Operator Description & Bitwise AND | Bitwise OR ^ Bitwise exclusive OR << left shift >> right shift a = 0001000 b = 2 a << b = 0100000 a >> b = 0000010
  • 82. 82 Conditional operator The conditional operators in C language are known by two more names • Ternary Operator • ? : Operator conditionalExpression ? expression1 : expression2
  • 83. 83 C Input and Output • The standard input-output header file, named stdio.h contains the definition of the functions printf() and scanf() #include<stdio.h> void main() { int i; // defining a variable printf("Please enter a value..."); scanf("%d", &i); // Take user input // Display out the value printf("nYou entered: %d", i); }
  • 84. 84 Format String Meaning %d Scan or print an integer as signed decimal number %f Scan or print a floating point number %c To scan or print a character %s To scan or print a character string. The scanning ends at whitespace.
  • 85. 85 getchar() & putchar() functions • The getchar() function reads a character from the terminal and returns it as an integer. This function reads only single character at a time. • The putchar() function displays the character passed to it on the screen and returns the same character. This function too displays only a single character at a time. • In case you want to display more than one characters, use putchar() method in a loop.
  • 86. 86 Find the printed Value • Find the printed values- I. int a=2, b=3, c=(a+b)%a; printf(“%d”, c); II. int x=3, y=6, z=x&y; printf(“%d”, y/x); III. int m=5, n=7, z=m^n; printf(“%d”,z+2); IV. int a=5, b=0, c=2; printf(“%d”, (a&&b) |c);
  • 87. Decision Making in C Section 4
  • 88. 88 Decision making in C C language handles decision-making by supporting the following statements, • if statement • switch statement • conditional operator statement (? : operator) • goto statement
  • 89. 89 Decision making with if statement • The different forms are, • Simple if statement • if....else statement • Nested if....else statement • Using else if statement
  • 90. 90 Simple if if(expression) { statement inside; } Example: #include <stdio.h> void main( ) { int x, y; x = 15; y = 13; if (x > y ) { printf("x is greater than y"); } }
  • 91. 91 if...else statement if...else statement The general form of a simple if...else statement is, if(expression) { statement block1; } else { statement block2; } Example: #include <stdio.h> void main( ) { int x, y; x = 15; y = 18; if (x > y ) { printf("x is greater than y"); } else { printf("y is greater than x"); } }
  • 92. 92 Nested if....else statement if( expression ) { if( expression1 ) { statement block1; } else { statement block2; } } else { statement block3; } #include <stdio.h> void main( ) { int a, b, c; printf("Enter 3 numbers..."); scanf("%d%d%d",&a, &b, &c); if(a > b) { if(a > c) { printf("a is the greatest"); } else { printf("c is the greatest"); } } else {if(b > c) { printf("b is the greatest"); } else { printf("c is the greatest"); } } }
  • 93. 93 else if ladder if(expression1) { statement block1; } else if(expression2) { statement block2; } else if(expression3 ) { statement block3; } else default statement; #include <stdio.h> void main( ) { int a; printf("Enter a number..."); scanf("%d", &a); if(a%5 == 0 && a%8 == 0) { printf("Divisible by both 5 and 8"); } else if(a%8 == 0) { printf("Divisible by 8"); } else if(a%5 == 0) { printf("Divisible by 5"); } else { printf("Divisible by none"); } }
  • 94. 94 switch statement #include<stdio.h> void main( ) { int a, b, c, choice; while(choice != 3) { /* Printing the available options */ printf("n 1. Press 1 for addition"); printf("n 2. Press 2 for subtraction"); printf("n Enter your choice"); scanf("%d", &choice); // Taking users input switch(choice) { case 1: printf("Enter 2 numbers"); scanf("%d%d", &a, &b); c = a + b; printf("%d", c); break; case 2: printf("Enter 2 numbers"); scanf("%d%d", &a, &b); c = a - b; printf("%d", c); break; default: printf("you have passed a wrong key"); printf("n press any key to continue"); } } } Rules for using switch statement 1. The expression (after switch keyword) must yield an integer value i.e the expression should be an integer or a variable or an expression that evaluates to an integer. 2. The case label values must be unique. 3. The case label must end with a colon(:) 4. The next line, after the case statement, can be any valid C statement.
  • 95. 95 Go To Statement • Goto statements is used to transfer the normal flow of a program to the specified label in program. • Syntax for goto { …. go to label; Label: statements; }
  • 97. 97 Questions 1. What is a nested loop? 2. Give the basic difference between the following- • While and do while • Break and continue 3. Create an infinite loop using C program. 4. Write a program to find the sum and average of the following series- (i) 1+2+3+…+100 (ii) 2+4+6+…+100 (iii) 1+3+5+…+100 (iv) 3+6+9+…+99 (v) 1 + 1 2 + 1 3 + ⋯ . + 1 100 (vi) (2+4+6+…+100)+ (3+6+9+…+99)
  • 98. 98 Looping • There are 4 types of loop statement- 1. While Loop 2. Do Loop 3. For Loop 4. Nested For Loop
  • 99. 99 Loop for loop for(initialization; condition; increment/ decrement) { statement; } While loop Initialization; while(condition) { statement; increment/ decrement }
  • 100. 100 Loop Do While loop do { statement; increment/ decrement } while(condition)
  • 102. 102 Questions 1. Define array. Write down the advantages and limitations of array. 2. Define array. Mention its importance. How can we access the values within an array? 3. Write a C program to add 5 elements of an integer array.
  • 103. 103 Arrays in C In C language, arrays are referred to as structured data types. An array is defined as finite ordered collection of homogenous data, stored in contiguous memory locations. Here the words, • finite means data range must be defined. • ordered means data must be stored in continuous memory addresses. • homogenous means data must be of similar data type. Example where arrays are used, • to store list of Employee or Student names, • to store marks of students, • or to store list of numbers or characters etc.
  • 104. 104 Arrays in C • An array is a collection of a fixed number of values of a single type. For example: if you want to store 100 integers in sequence, you can create an array for it. int data[100]; • The size and type of arrays cannot be changed after its declaration. Arrays are of two types: • One-dimensional arrays • Multidimensional arrays
  • 105. 105 Properties of Array • Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes. • Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location. • Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.
  • 106. 106 Advantage of C Array 1) Code Optimization: Less code to the access the data. 2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily. 3) Ease of sorting: To sort the elements of the array, we need a few lines of code only. 4) Random Access: We can access any element randomly using the array. Disadvantage of C Array 1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So, it doesn't grow the size dynamically like Linked List which we will learn later.
  • 107. 107 Declaring an Array • Like any other variable, arrays must be declared before they are used. General form of array declaration is, data-type variable-name[size]; /* Example of array declaration */ int arr[10];  Here int is the data type, arr is the name of the array and 10 is the size of array. It means array arr can only contain 10 elements of int type.  Index of an array starts from 0 to (size-1) i.e first element of arr array will be stored at arr[0] address and the last element will occupy arr[9].
  • 108. 108 Initialization of an Array • After an array is declared it must be initialized. • Otherwise, it will contain garbage value(any random value). • An array can be initialized at either compile time or at runtime.
  • 109. 109 Compile time Array initialization • Compile time initialization of array elements is same as ordinary variable initialization. • The general form of initialization of array is, data-type array-name[size] = { list of values }; /* Here are a few examples */ int marks[4]={ 67, 87, 56, 77 }; // integer array initialization float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization int marks[4]={ 67, 87, 56, 77, 59 }; // Compile time error
  • 110. 110 Initialize an array • Another method to initialize array during declaration: int mark[] = {19, 10, 8, 17, 9}; Here, mark[0] is equal to 19 mark[1] is equal to 10 mark[2] is equal to 8 mark[3] is equal to 17 mark[4] is equal to 9
  • 111. 111 Runtime Array initialization • An array can also be initialized at runtime using scanf() function. • This approach is usually used for initializing large arrays, or to initialize arrays with user specified values. Example-> #include<stdio.h> void main() { int arr[4]; int i, j; printf("Enter array element"); for(i = 0; i < 4; i++) { scanf("%d", &arr[i]); //Run time array initialization } for(j = 0; j < 4; j++) { printf("%dn", arr[j]); } }
  • 112. 112 Insert and print array elements int mark[5] = {19, 10, 8, 17, 9} // insert different value to third element mark[3] = 9; // take input from the user and insert in third element scanf("%d", &mark[2]); // take input from the user and insert in (i+1)th element scanf("%d", &mark[i]); // print first element of an array printf("%d", mark[0]); // print ith element of an array printf("%d", mark[i-1]);
  • 113. 113 Program to find the average of n (n < 10) numbers using arrays #include <stdio.h> int main() { int marks[10], i, n, sum = 0, average; printf("Enter n: "); scanf("%d", &n); for(i=0; i<n; ++i) { printf("Enter number%d: ",i+1); scanf("%d", &marks[i]); sum += marks[i]; } average = sum/n; printf("Average = %d", average); return 0; } Output Enter n: 5 Enter number1: 45 Enter number2: 35 Enter number3: 38 Enter number4: 31 Enter number5: 49 Average = 39
  • 114. 114 Display Largest Element of an array #include <stdio.h> int main() { int i, n; float arr[100]; printf("Enter total number of elements(1 to 100): "); scanf("%d", &n); printf("n"); // Stores number entered by the user for(i = 0; i < n; ++i) { printf("Enter Number %d: ", i+1); scanf("%f", &arr[i]); } // Loop to store largest number to arr[0] for(i = 1; i < n; ++i) { // Change < to > if you want to find the smallest element if(arr[0] < arr[i]) arr[0] = arr[i]; } printf("Largest element = %.2f", arr[0]); return 0; }
  • 115. 115 Two dimensional Arrays • C language supports multidimensional arrays also. The simplest form of a multidimensional array is the two-dimensional array. Both the row's and column's index begins from 0. • Two-dimensional arrays are declared as follows, data-type array-name[row-size][column-size] /* Example */ int a[3][4]; An array can also be declared and initialized together. For example, int arr[][3] = { {0,0,0}, {1,1,1} };
  • 116. 116 Runtime initialization of a two dimensional Array #include<stdio.h> void main() { int arr[3][4]; int i, j, k; printf("Enter array element"); for(i = 0; i < 3;i++) { for(j = 0; j < 4; j++) { scanf("%d", &arr[i][j]); } } for(i = 0; i < 3; i++) { for(j = 0; j < 4; j++) { printf("%d", arr[i][j]); } } }
  • 117. 117 Sorting an Array #include<stdio.h> void main () { int i, j,temp; int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23}; for(i = 0; i<10; i++) { for(j = i+1; j<10; j++) { if(a[j] > a[i]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } printf("Printing Sorted Element List ...n"); for(i = 0; i<10; i++) { printf("%d n",a[i]); } }
  • 118. 118 Program to print the largest and second largest element of the array #include<stdio.h> void main () { int arr[100],i,n,largest,sec_largest; printf("Enter the size of the array?"); scanf("%d",&n); printf("Enter the elements of the array?"); for(i = 0; i<n; i++) { scanf("%d",&arr[i]); } largest = arr[0]; sec_largest = arr[1]; for(i=0;i<n;i++) { if(arr[i]>largest) { sec_largest = largest; largest = arr[i]; } else if (arr[i]>sec_largest && arr[i]!=largest) { sec_largest=arr[i]; } } printf("largest = %d, second largest = %d",largest,sec_largest); }
  • 120. 120 Questions 1. What is the difference between actual and formal parameters? 2. Differentiate among: getch(), getche() and getchar(); 3. What is user defined function? Why do we need it? 4. Differentiate between user defined and library function. Explain with example. 5. What is the difference between Call by Value and Call by Reference? 6. What is recursion? Write a program in C to calculate the factorial of a number using recursive function.
  • 121. 121 Questions 1. Briefly discuss the function of the following functions- • printf() • scanf() • getch(), getche(), getchar(), gets() • add(), sub() • sizeof() p-72 • fopen(), fprintf(), fscanf(), fclose(), • atoi(), atof() • toupper(),strcat(), strcpy(),tolower()
  • 122. 122 Functions • Functions is basically a set of statements that takes inputs, perform some computation and produces output. • Syntax: returntype functionName(type1 parameter1, type2 parameter2,...); • C functions can be classified into two categories, • Library functions • User-defined functions
  • 123. 123 How function works in C Syntax of function definition returnType functionName(type1 argument1, type2 argument2, ...) { //body of the function }
  • 124. 124 Types of Function • Library functions are those functions which are already defined in C library, example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use these functions. These are already declared and defined in C libraries. • A User-defined functions on the other hand, are those functions which are defined by the user at the time of writing program. These functions are made for code reusability and for saving time and space.
  • 125. 125 Benefits of Using Functions • It provides modularity to your program's structure. • It makes your code reusable. You just have to call the function by its name to use it, wherever required. • In case of large programs with thousands of code lines, debugging and editing becomes easier if you use functions. • It makes the program more readable and easy to understand.
  • 126. 126 Advantages of user-defined function • The program will be easier to understand, maintain and debug. • Reusable codes that can be used in other programs • A large program can be divided into smaller modules. Hence, a large project can be divided among many programmers. Example: User-defined function Here is an example to add two integers. To perform this task, an user-defined function addNumbers() is defined. #include <stdio.h> int addNumbers(int a, int b); // function prototype int main() { int n1,n2,sum; printf("Enters two numbers: "); scanf("%d %d",&n1,&n2); sum = addNumbers(n1, n2); // function call printf("sum = %d",sum); return 0; } int addNumbers(int a,int b) // function definition { int result; result = a+b; return result; // return statement }
  • 127. 127 Example: Multiplication #include<stdio.h> int multiply(int a, int b); // function declaration int main() { int i, j, result; printf("Please enter 2 numbers you want to multiply..."); scanf("%d%d", &i, &j); result = multiply(i, j); // function call printf("The result of muliplication is: %d", result); return 0; } int multiply(int a, int b) { return (a*b); // function defintion, this can be done in one line }
  • 128. 128 Calling a function • When a function is called, control of the program gets transferred to the function. functionName(argument1, argument2,...); • Passing Arguments to a function: Arguments are the values specified during the function call, for which the formal parameters are declared while defining the function.
  • 129. 129 Returning a value from function
  • 130. 130 Recall • Actual Parameters: The parameters passed to a function • Formal Parameters: The parameters received by a function
  • 131. 131 Call by Value • Here values of actual parameters will be copied to formal parameters and these two different parameters store values in different locations.
  • 132. 132 Call by Reference • The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. #include <stdio.h> void swap(int *x, int *y); int main () { /* local variable definition */ int a = 100; int b = 200; printf("Before swap, value of a : %dn", a ); printf("Before swap, value of b : %dn", b ); /* calling a function to swap the values. * &a indicates pointer to a ie. address of variable a and * &b indicates pointer to b ie. address of variable b. */ swap(&a, &b); printf("After swap, value of a : %dn", a ); printf("After swap, value of b : %dn", b ); return 0; } /* function definition to swap the values */ void swap(int *x, int *y) { int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put temp into y */ return; }
  • 133. 133 Recursion • Recursion is a process in which a function calls itself directly or indirectly. • A function that calls itself is called a recursive function. • in a recursive function, there must be a terminating condition to stop the recursion. This condition is known as the base condition. • Often recursion can be used where loops can be used. Generally, recursive solutions are elegant but less efficient than loop solutions. int main() { callme(); } void callme() { if(base_condition) { // terminating condition } statement 1; ... callme(); }
  • 134. 134 Example • Find the printed value
  • 135. 135 Example • Find the printed value
  • 137. 137 Questions 1. What are strings? Discuss some basic functions of “string.h” header file. 2. Explain with example: I. strlen(), strcat(), strcmp(), strcpy(), II. tolower(), toupper()
  • 138. 138 String in C • String is a sequence of characters that is treated as a single data item and terminated by null character '0'. • A string is actually one-dimensional array of characters in C language. Function Work of Function strlen() Calculates the length of string strcpy() Copies a string to another string strcat() Concatenates(joins) two strings strcmp() Compares two string strlwr() Converts string to lowercase strupr() Converts string to uppercase
  • 140. 140 Declaring and Initializing a string variables There are different ways to initialize a character array variable. • char name[13] = "StudyTonight"; // valid character array initialization • char name[10] = {'L','e','s','s','o','n','s', '0' }; // valid initialization Remember that when you initialize a character array by listing all of its characters separately then you must supply the '0'character explicitly. Error Test: 1. char ch[3] = "hell"; // Illegal 2. char str[4]; str = "hell"; // Illegal
  • 141. 141 String Input and Output • Input function scanf() can be used with %s format specifier to read a string input from the terminal. • Read a string char text[20]; gets(text); printf("%s", text);
  • 142. 142 String Operation strcat() function • strcat("hello", "world"); • strcat() function will add the string "world" to "hello" i.e it will ouput helloworld strlen() function • strlen() function will return the length of the string passed to it. int j; j = strlen("studytonight"); printf("%d",j);
  • 143. 143 String Operation strcmp() function • strcmp() function will return the ASCII difference between first unmatching character of two strings. int j; j = strcmp("study", "tonight"); printf("%d",j);
  • 144. 144 String Operation strcpy() function It copies the second string argument to the first string argument. #include<stdio.h> #include<string.h> int main() { char s1[50]; char s2[50]; strcpy(s1, "StudyTonight"); //copies "studytonight" to string s1 strcpy(s2, s1); //copies string s1 to string s2 printf("%sn", s2); return(0); } strrev() function It is used to reverse the given string expression. #include<stdio.h> int main() { char s1[50]; printf("Enter your string: "); gets(s1); printf("nYour reverse string is: %s",strrev(s1)); return(0); }
  • 146. 146 Questions 1. What is structure in C language? Explain with example. 2. Differentiate between structure and union. 3. How does a structure differ from an array? What is the basic difference between a structure and union? 4. What are the advantages of structured variable over traditional variable?
  • 147. 147 Structure • Structure is a user-defined datatype in C language which allows us to combine data of different types together. • Structure helps to construct a complex data type which is more meaningful. • It is somewhat similar to an Array, but an array holds data of similar type only. • But structure on the other hand, can store data of any type, which is practical more useful.
  • 149. 149 Accessing Structure Members #include<stdio.h> #include<string.h> struct Student { char name[25]; int age; char branch[10]; char gender; //F for female and M for male }; int main() { struct Student s1; /* s1 is a variable of Student type and age is a member of Student*/ s1.age = 18; /* using string function to add name */ strcpy(s1.name, "Viraaj"); /* displaying the stored values */ printf("Name of Student 1: %sn", s1.name); printf("Age of Student 1: %dn", s1.age); return 0; } We can also use scanf() to give values to structure members through terminal. scanf(" %s ", &s1.name); // it obtain only one single word scanf(" %d ", &s1.age); Or, gets(s1.name) // to obtain full name
  • 150. 150 Structure Initialization • Like a variable of any other data type, structure variable can also be initialized at compile time.
  • 151. 151 Array of Structure • We can also declare an array of structure variables in which each element of the array will representa structure variable. Example : struct employee emp[5]; The below program defines an array emp of size 5. Each element of the array emp is of type Employee.
  • 152. 152 Nested Structures • Nesting of structures, is also permitted in C language. • Nested structures means, that one structure has another structure as member variable.
  • 153. 153 Structure vs. Union • Unions are conceptually similar to structures. • The syntax to declare/define a union is also similar to that of a structure. • The only differences is in terms of storage. • In structure each member has its own storage location, whereas all members of union uses a single shared memory location which is equal to the size of its largest data member. • This implies that although a union may contain many members of different types, it cannot handle all the members at the same time. A union is declared using the union keyword.
  • 154. 154 Accessing Union • Syntax for accessing any union member is similar to accessing structure members- union test { int a; float b; char c; }t; t.a; //to access members of union t t.b; t.c; Example #include <stdio.h> union item { int a; float b; char ch; }; int main( ) { union item it; it.a = 12; it.b = 20.2; it.ch = 'z'; printf("%dn", it.a); printf("%fn", it.b); printf("%cn", it.ch); return 0; }
  • 156. 156 1. Define pointer. Mention the advantage of using pointer in C. 2. Define pointer variable. How is it different from normal variable? 3. Define Null pointer. 4. Differentiate between normal variable vs pointer variable. 5. What is a null pointer? 6. What is difference between far and near pointers? 7. Explain the concept behind using pointers and give an example of Array of pointer. 8. Define Dangling Pointer.
  • 157. 157 Pointer in C • Pointers in C language is a variable that stores/points the address of another variable. • A Pointer in C is used to allocate memory dynamically i.e. at run time. • The pointer variable might be belonging to any of the data type such as int, float, char, double, short etc. • Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is − type *var-name; • Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. • The asterisk * used to declare a pointer is the same asterisk used for multiplication. some of the valid pointer declarations − • int *ip; /* pointer to an integer */ • double *dp; /* pointer to a double */ • float *fp; /* pointer to a float */ • char *ch /* pointer to a character */
  • 158. 158 How to Use Pointers? • There are a few important operations, which we will do with the help of pointers very frequently. a) We define a pointer variable, b) Assign the address of a variable to a pointer and c) Finally access the value at the address available in the pointer variable.
  • 159. 159 NULL Pointers • It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. • This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer. • The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program − When the above code is compiled and executed, it produces the following result − The value of ptr is 0
  • 160. 160 C - Pointer arithmetic: Incrementing a Pointer • Incrementing a Pointer ptr++ • If ptr points to a character whose address is 1000, then the above operation will point to the location 1001 because the next character will be available at 1001. When the above code is compiled and executed, it produces the following result −
  • 163. 163 Array of Pointer An array of pointers to character to store a list of strings
  • 164. 164 Pointer to Pointer • A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. • When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below. • A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name. • For example, the following declaration declares a pointer to a pointer of type int − • int **var;
  • 166. 166 Questions 1. Write short note on different modes of opening a file. 2. Explain with example- fopen(), fprintf(), fscanf(), fclose(),
  • 167. 167 Files I/O Why files are needed? • When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates. • If you have to enter a large number of data, it will take a lot of time to enter them all. However, if you have a file containing all the data, you can easily access the contents of the file using few commands in C. • You can easily move your data from one computer to another without any changes.
  • 168. 168 Types of Files When dealing with files, there are two types of files you should know about: • Text files • Binary files 1. Text files: • Text files are the normal .txt files that you can easily create using Notepad or any simple text editors. • When you open those files, you'll see all the contents within the file as plain text. You can easily edit or delete the contents. • They take minimum effort to maintain, are easily readable, and provide least security and takes bigger storage space. 2. Binary files • Binary files are mostly the .bin files in your computer. • Instead of storing data in plain text, they store it in the binary form (0's and 1's). • They can hold higher amount of data, are not readable easily and provides a better security than text files.
  • 169. 169 File Operations In C, you can perform four major operations on the file, either text or binary: • Creating a new file • Opening an existing file • Closing a file • Reading from and writing information to a file
  • 170. 170 File operations To Write something in a file • fputc() • fputw() • fputs() • fprintf() • fwrite() To read something in a file • fgetc() • fgetw() • fgets() • fscanf() • fread()
  • 171. 171 Working with files • When working with files, you need to declare a pointer of type file. This declaration is needed for communication between the file and program. • FILE *fptr;
  • 172. 172 Opening a file - for creation and edit • Opening a file is performed using the library function in the "stdio.h" header file: fopen(). • The syntax for opening a file in standard I/O is: ptr = fopen("fileopen","mode") For Example: • fopen("E:cprogramnewprogram.txt","w"); • fopen("E:cprogramoldprogram.bin","rb");
  • 173. 173 Opening Modes in Standard I/O File Mode Meaning of Mode During Inexistence of file r Open for reading. If the file does not exist, fopen() returns NULL. w Open for writing. If the file exists, its contents are overwritten. If the file does not exist, it will be created. a Open for append. i.e, Data is added to end of file. If the file does not exists, it will be created. r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL. w+ Open for both reading and writing. If the file exists, its contents are overwritten. If the file does not exist, it will be created. a+ Open for both reading and appending. If the file does not exists, it will be created. rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
  • 174. 174 Closing a File • The file (both text and binary) should be closed after reading/writing. • Closing a file is performed using library function fclose(). fclose(fptr); //fptr is the file pointer associated with file to be closed.
  • 175. 175 Reading and writing to a text file • For reading and writing to a text file, we use the functions fprintf() and fscanf(). • They are just the file versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a pointer to the structure FILE.
  • 176. 176 Example 1: Write to a text file using fprintf() NB: • exit(0) usually indicates that all is well, • whilst exit(1) indicates that something has gone amiss. • exit() should always be called with an integer value and non- zero values are used as error codes
  • 177. 177 Example 2: Read from a text file using fscanf()
  • 178. 178 Write a C program to read name and marks of n number of students from user and store them in a file.
  • 179. 179 Write a C program to read name and marks of n number of students from user and store them in a file. If the file previously exits, add the information of n students.
  • 181. 181 1. Distinguish between malloc() & calloc() memory allocation. 2. What do you mean by dynamic memory allocation? Is there any advantages of it? 3. Explain- i) calloc() ii) malloc() iii) realloc() iv) free()
  • 182. 182 Dynamic Memory Allocation in C • The process of allocating memory at runtime is known as dynamic memory allocation. • Library routines known as memory management functions are used for allocating and freeing memory during execution of a program. • These functions are defined in stdlib.h header file. Function Description malloc() allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated space calloc() allocates space for an array of elements, initialize them to zero and then returns a void pointer to the memory free releases previously allocated memory realloc modify the size of previously allocated space
  • 183. 183 malloc() • The name "malloc" stands for memory allocation. • The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of type void which can be casted into pointer of any form. • Syntax of malloc() ptr = (cast-type*) malloc(byte-size) • Example: ptr = (int*) malloc(100 * sizeof(int)); • Considering the size of int is 4 bytes, this statement allocates 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory. • However, if the space is insufficient, allocation fails and returns a NULL pointer. https://www.programiz.com/c-programming/c-dynamic-memory-allocation
  • 184. 184 Calloc • The name "calloc" stands for contiguous allocation. • The malloc() function allocates a single block of memory. Whereas, calloc() allocates multiple blocks of memory and initializes them to zero. • Syntax of calloc() ptr = (cast-type*)calloc(n, element-size); • Example: ptr = (float*) calloc(25, sizeof(float)); • This statement allocates contiguous space in memory for 25 elements each with the size of float. https://www.programiz.com/c-programming/c-dynamic-memory-allocation
  • 187. 187 C realloc() • “realloc” or “re-allocation” method is used to dynamically change the memory allocation of a previously allocated memory. • In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. • If the dynamically allocated memory is insufficient or more than required, you can change the size of previously allocated memory using realloc() function https://www.programiz.com/c-programming/c-dynamic-memory-allocation https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/
  • 189. 189 free() • “free” method is used to dynamically de-allocate the memory. • The memory allocated using functions malloc() and calloc() are not de-allocated on their own. • Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. https://www.programiz.com/c-programming/c-dynamic-memory-allocation free(ptr); Syntax:
  • 191. 191 Diffrence between malloc() and calloc() malloc calloc The name malloc stands for memory allocation. The name calloc stands for contiguous allocation. void *malloc(size_t n) returns a pointer to n bytes of uninitialized storage, or NULL if the request cannot be satisfied. If the space assigned by malloc() is overrun, the results are undefined. void *calloc(size_t n, size_t size)returns a pointer to enough free space for an array of n objects of the specified size, or NULL if the request cannot be satisfied. The storage is initialized to zero. malloc() takes one argument that is, number of bytes. calloc() take two arguments those are: number of blocks and size of each block. syntax of malloc(): void *malloc(size_t n); Allocates n bytes of memory. If the allocation succeeds, a void pointer to the allocated memory is returned. Otherwise NULL is returned. syntax of calloc(): void *calloc(size_t n, size_t size); Allocates a contiguous block of memory large enough to hold n elements of sizebytes each. The allocated region is initialized to zero. malloc is faster than calloc. calloc takes little longer than malloc because of the extra step of initializing the allocated memory by zero. However, in practice the difference in speed is very tiny and not recognizable.
  • 192. 192 Similarities Between Malloc and Calloc • The pointer returned by malloc or calloc has the proper alignment for the object in question, but it must be cast into the appropriate type. • Proper alignment means the value of the returned address is guaranteed to be an even multiple of alignment. The value of alignment must be a power of two and must be greater than or equal to the size of a word. • The malloc(), calloc() functions will fail if: • The physical limits of the system are exceeded by n bytes of memory which cannot be allocated. • There is not enough memory available to allocate n bytes of memory; but the application could try again later.
  • 197. 197 References Books: • Let Us C by Yashavant • ANSI C- Balaguruswamy Web Resources- • https://www.studytonight.com/c • https://www.tutorialspoint.com/cprogramming/ • https://www.programiz.com/c-programming
  • 198. Exam Aid C at a Glance 13
  • 199. 199 Basic Theory: What, why and how • Variables, constants • Data types • Conditions ( if..else, if..else if..else,nested if else, switch, goto…label) • Loops (for, while, do while) • Functions (user define functions) • Structure & Union • Arrays • Pointers Ex- What is pointer? Why we use pointer? How to use it? Explain with an example.
  • 200. 200 Basic Syntax • Variables, constants • Comments • Conditions ( if..else, if..elseif..else, nested if else, switch …. etc) • Loops (for, while, do while, nested for) • Functions (user define functions) • Structure & Union • Arrays • Pointers Etc. Cover the contents given in the syllabus.
  • 201. 201 C Program and its Structure #include <stdio.h> int main() { printf("Hello World"); return 0; } Hello World Different parts of C program • Pre-processor • Header file • Function • Variables • Statements & expressions • Comments
  • 202. 202 Variable, constant syntax • dataType name= initialValue; // variable declaration and initialization int number1=2; • const dataType name= value; const float pi=3.1416; • Comment // line comment /* paragraph comment */
  • 203. 203 Array syntax • Single Dimensional Array syntax dataType name[arraySize]={ arrayElements}; • Two-dimensional arrays are declared as follows, data-type array-name[row-size][column-size] • String char name[stringSize+1]=“String”
  • 204. 204 Conditional Syntax Simple if…else if(condition) { Statement; } else { Statement; } if…elseif if(condition) { Statement; } else if(condition) { Statement; } …. else { Statement; } Nested If…else if(condition) { if (condition){ statement; } else{ statement;} } else{ statement; }
  • 205. 205 Conditional Syntax Conditional operator condition ? TrueExpression1 : FalseExpression2; Switch switch(value) { case 1: statement; break; case 2: statement; break; ….. default: statement; }
  • 206. 206 Conditional Syntax Goto { …. go to label; Label: statements; }
  • 207. 207 Loop for loop for(initialization; condition; increment/ decrement) { statement; } While loop Initialization; while(condition) { statement; increment/ decrement }
  • 208. 208 Loop Do While loop do { statement; increment/ decrement } while(condition)
  • 209. 209 Function • User define functions may be defined as Calling a Function: functionName(type1 argument1, type2 argument2, ...) Defining a Function: returnType functionName(type1 argument1, type2 argument2, ...) { //body of the function }
  • 210. 210 Errors • Logical and syntax error • Definition error • Data type error Follow the reference book exercise sections for practice problem.
  • 211. 211 Find Values • Basic operator operations • Basic loops/ conditions • User defined functions
  • 212. 212 Functions Description • Standard input output functions (printf, scanf, gets, etc) • Arithmatic/ Math library functions ( sin, floor, ceil, pow…etc) • String functions (strcpy, strcat,….) • File input/ output functions (fopen, fclose,….etc) • Memory Allocation Functions ( calloc, malloc,… etc) Follow the reference book exercise sections for practice problem.
  • 213. 213 Programming Problem • Basic input output (printf, scanf) • Basic formula based • If.. Else condition based • Loop based • String based • Array program
  • 215. 215 Arithmatic Problem • Write a C program to calculate the following calculation if two integer numbers are given as input • Sum • Difference • Product • Division Write a program to find whether a number is • Even or odd • Prime or non-prime • Positive or negative Problem: Number
  • 216. 216 Geometry Problem: Circle • Write a C program to find area and perimeter of a circle if the radius/diameter is given from user as input. 1. Write a C program to find area and perimeter of a rectangle if the length and width are given from user as input. Area of a triangle is given by 𝐴 = 𝑆 𝑆 − 𝑎 𝑆 − 𝑏 𝑆 − 𝐶 , where a, b, c are sides of a triangle and 𝑆 = (𝑎 + 𝑏 + 𝑐)/2. 1. Given value: a, b. Find c? 2. Given value: a, c. Find b? 3. Given theta = 45°. Find the values of • Sin • Cos • Tan Geometry Problem: Triangle Circle
  • 217. 217 Arithmatic Problem • Write a program to find the sum and average of five numbers taken from user as keyboard input. • Write a program to convert Celsius to Fahrenheit (or Fahrenheit to Celsius). Take user input for temperature in Celsius and print the converted value in Fahrenheit 𝐹 = 9 × 𝐶 5 + 32 𝑜𝑟 𝐶 = 𝐹 − 32 1.8 Or, Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program to convert this temperature into Centigrade degrees. Problem: Conversion of Temperature
  • 218. 218 Arithmatic Problem: Interest Calculation • You take input the following information- 1. Principle (P) 2. Simple Interest Rate (r) 3. Year (n) • Print out the total money after the given duration. 𝑪𝒂𝒑𝒊𝒕𝒂𝒍 𝒘𝒊𝒕𝒉 𝒊𝒏𝒕𝒆𝒓𝒆𝒔𝒕 = 𝑷 + 𝑷𝒏𝒓 Write a C program to find if a given year is leap year or not. Arithmatic Problem: Leap Year Calculation
  • 219. 219 Arithmatic Problem: Salary Calculation • Write a program to calculate salary of a salesman. He is given bonus and commission based on number of products sold. While given the following information. Basic Salary= 22,000, Bonus Rate= 200, Commission= 0.02 Take user input: Number of products sold, and the price of the product. [𝐻𝑖𝑛𝑡𝑠: 𝐵𝑜𝑛𝑢𝑠 = 𝐵𝑜𝑛𝑢𝑠 𝑟𝑎𝑡𝑒 × 𝑞𝑢𝑎𝑛𝑡𝑖𝑡𝑦 𝐶𝑜𝑚𝑚𝑖𝑠𝑠𝑖𝑜𝑛 = 𝐶𝑜𝑚𝑚𝑖𝑠𝑠𝑖𝑜𝑛 × 𝑞𝑢𝑎𝑛𝑡𝑖𝑡𝑦 × 𝑝𝑟𝑖𝑐𝑒 𝐺𝑟𝑜𝑠𝑠 𝑆𝑎𝑙𝑎𝑟𝑦 = 𝐵𝑎𝑠𝑖𝑐 𝑆𝑎𝑙𝑎𝑟𝑦 + 𝑏𝑜𝑛𝑢𝑠 + 𝑐𝑜𝑚𝑚𝑖𝑠𝑠𝑖𝑜𝑛 ]
  • 220. 220 Electrical Arithmatic Problem 1. If for a dc circuit resistance is 50 ohm, delivered power is 100W. What will be output voltage? 2. If 3 fans of 75W run 6hrs/day for a month. Then what will be the utility bill at the end of the month with a price of 7tk/unit.
  • 221. 221 Arithmatic Problem: Salary Calculation • Ramesh’s basic salary is input through the keyboard. His technical allowance is 40% of basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his gross salary Arithmatic Problem: Day Calculation • Write a program to convert days into Month and days. Assume each month has 30 days. [𝑚𝑜𝑛𝑡ℎ = 𝑑𝑎𝑦𝑠 30 , 𝑟𝑒𝑚𝑎𝑖𝑛𝑖𝑛𝑔 𝑑𝑎𝑦𝑠 = 𝑑𝑎𝑦𝑠% 30]
  • 222. 222 Arithmatic Problem: Grocery Calculation • Take input of how much rice and sugar the user has bought and show him the total cost of his product using a C program. [𝐻𝑖𝑛𝑡𝑠: 𝑇𝑜𝑡𝑎𝑙 𝐶𝑜𝑠𝑡 = 𝑄𝑢𝑎𝑛𝑡𝑖𝑡𝑦 𝑖𝑛 𝐾𝐺 × 𝑈𝑛𝑖𝑡 𝑃𝑟𝑖𝑐𝑒] Item Price/ Unit Rice 30 Tk/ Kg Sugar 100 Tk/ Kg
  • 223. 223 Logical Problem: CGPA Calculation • Write a program to calculate CGPA while given the information of GPA and credits semester wise. • [𝐻𝑖𝑛𝑡𝑠: 𝐶𝐺𝑃𝐴 = ∑𝐺𝑃𝐴×𝑇𝑜𝑡𝑎𝑙 𝐶𝑟𝑒𝑑𝑖𝑡𝑠 ∑ 𝑇𝑜𝑡𝑎𝑙 𝐶𝑟𝑒𝑑𝑖𝑡𝑠 ] • Answer: 3.85 Level Term Credit Hours Earned, TCI GPA Earned, GPAi GPAi*TCi 1 1 21.00 3.73 78.330 1 2 21.00 3.92 82.320 2 1 19.50 3.96 77.220 2 2 19.00 3.80 72.200 Total 80.50 310.07
  • 224. 224 Logical Problem: Grade Calculation • Take a user mark as input and print his grade according to the grade table. Marks Grade 100-80 A+ 70-79 A 60-69 B 50-59 C 40-49 D 0-39 F
  • 225. 225 Logical Problem: Corona Symptoms • Suppose that you want to create a simple C program to recommend initial treatment based on basic symptoms shown as the given chart below. • You need to take user input for following symptoms whether the patient has i) Fever, ii) Dry cough, iii) Shortness of breath and iv) Aches & pain- in ‘y’ for yes and ‘n’ for no and accordingly recommend him treatment. For example- if he answer all the symptoms in y, then he will be a potential COVID-19 patient. Fever Dry Cough Shortness of Breath Aches and Pain COVID-19 y y y y Common Cold n y n n FLU y y n y
  • 226. 226 Logical Problem: Ticketing Booth • Suppose you are making an automatic ticketing booth for a public transport as per the following table Ticket fee/ person Age < 20 years Gender 60 tk N M 50 tk N F 40 tk Y M 35 tk Y F • * N for No, Y for yes, F for female, M for Male • For example- if a person has age less than 20 years and gender is Female (F) then her ticket fee will be 35 Tk. • Now write a C program to take user input for age & gender and accordingly print his/ her ticket fee.
  • 227. 227 Problem with Loop implementation • Write a program to find the sum and average of the following series- • 1+2+3+…+100 • 2+4+6+…+100 • 1+3+5+…+100 • 3+6+9+…+99 • 1 + 1 2 + 1 3 + ⋯ . + 1 100 • (2+4+6+…+100)+ (3+6+9+…+99)
  • 228. 228 Test Problem: Factorials Calculations • Take user input. • Find factorial of given number • 0 != 1 • 6!= 6*5*4*3*2*1
  • 229. 229 Problem with Nested Loop implementation Write a program to print the following print pattern using only one print statement. * * * * * * * * * * Write a program to print the following print pattern using only one print statement. 1 1 2 1 2 3 1 2 3 4 Write a program to print the following print pattern using only one print statement. 1 2 3 4 5 6 7 8 9 10
  • 230. 230 Array Problem: finding highest • Write a program to find the highest mark in the following set of data Marks[6]={55, 60,39, 89, 75, 100} Array Problem: Sorting • Write a program to sort the following marks in ascending (or descending) order- Marks[6]={55, 60,39, 89, 75, 100}