0% found this document useful (0 votes)
16 views125 pages

Computer Programming

The document provides an overview of computer programming, detailing the definition of a computer, its components, and the programming process. It explains various programming languages, their types, and the importance of algorithms and flowcharts in programming. Additionally, it covers the history and significance of the C programming language, including its structure, data types, and the concept of variables.

Uploaded by

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

Computer Programming

The document provides an overview of computer programming, detailing the definition of a computer, its components, and the programming process. It explains various programming languages, their types, and the importance of algorithms and flowcharts in programming. Additionally, it covers the history and significance of the C programming language, including its structure, data types, and the concept of variables.

Uploaded by

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

COMPUTER PROGRAMMING

LECTURE 1
PRESENTED BY:
Prof. Dr. Md Abdur Rahim
Chairman
Department of Computer Science and Engineering
&
Director, ICT Cell
Pabna University of Science and Technology, Rajapur, Pabna.
Email: rahim@[Link]
Contact: +8801728548300
COMPUTER
A computer is an electronic machine that takes input from the user, processes
the given input and generates output in the form of useful information.
Requirements of a computer:
❑ Process data

❑ Store data

❑ Move data between the computer and

the outside world


❑ Control the operation of the above
COMPUTER (CONT.)

• Input: data, programs, user reply


• Data: the raw details that need to be processed to generate some useful information.
• Programs: the set of instructions that can be executed by the computer in sequential
or non-sequential manner.
• User reply: the input provided by the user in response to a question asked by the
computer.
COMPONENT OF A COMPUTER

• Input Unit
• Central Processing Unit(CPU)
• Output Unit
➢CPU is known as the brain of the computer system. All the operations within the
system are supervised & controlled by the CPU.
➢The CPU control all internal & external devices, perform arithmetic and logical
operation, controls memory usage, and control the sequence of operation.
PROGRAMMING

• Programming refers to a technological


process for telling a computer which tasks
to perform in order to solve problems
• Programming as a collaboration between
humans and computers, in which humans
create instructions for a computer to follow
(code) in a language computers can
understand.
PROGRAMMING (CONT.)

5 Types of Programming Languages


1. Procedural programming languages
A procedural language follows a sequence of statements or commands in order to
achieve a desired output.
• C and C++
• Java
• Pascal
• BASIC
PROGRAMMING (CONT.)

2. Functional programming languages


Rather than focusing on the execution of statements, functional languages
focus on the output of mathematical functions and evaluations.
• Scala
• Erlang
• Haskell
• Elixir
• F#
PROGRAMMING (CONT.)

3. Object-oriented programming languages (OOP)


This type of language treats a program as a group of objects composed of data and
program elements, known as attributes and methods.
• Java
• Python
• PHP
• C++
• Ruby
PROGRAMMING (CONT.)

4. Scripting languages
Programmers use scripting languages to automate repetitive tasks, manage dynamic web
content, or support processes in larger applications.
• PHP
• Ruby
• Python
• bash
• Perl
• [Link]
PROGRAMMING (CONT.)

5. Logic programming languages


Instead of telling a computer what to do, a logic programming language expresses a
series of facts and rules to instruct the computer on how to make decisions.
PHP
• Prolog
• Absys
• Datalog
• Alma-0
COMPUTER PROGRAMMING
• Computer programming is the process of writing code to facilitate specific actions
in a computer, application or software program, and instructs them on how to
perform.
• Computer programmers are professionals that create instructions for a computer
to execute by writing and testing code that enables applications and software
programs to operate successfully.
Programming Challenges
❖ Is not just for experts ❖ Need to learn what computers can do
❖ Is a natural, satisfying and creative experience ❖ Need to learn a programming language
❖ Enables accomplishments not otherwise possible
❖ The path to a new world of intellectual endeavor
COMPUTER PROGRAM
• Computer program – A set of logical instructions given to a computer for data
processing that is interpreted by a computer to produce useful information.
• It is therefore a must for computer programmers to learn the language the computer
can understand.
• Computer Language is composed of arithmetic operators, logical operators, relational
operators, important terminologies and systems
COMPUTER PROGRAM (CONT.)
PROBLEM ANALYSIS
• Problem analysis is a way of understanding the context within which you intend to work.
• it provides a structured approach for identifying problems and their root causes to ensure that
attention is focused upon the real issues.

Five Steps for problem analysis: Identify, analyze, resolve, execute, evaluate

• Step 1: Identify: Identifying the problem may be simple, or it could be a detailed cognitive
process that breaks the issue into manageable components.
• Step 2: Analyze: Consider underlying factors and devise strategies.
• Step 3: Resolve: Develop some reasonable solutions that are aligned with the capabilities
of your team and the mission, vision, and values of your company.
• Step 4: Execute: The execution phase is the bridge between theory and practice
• Step 5: Evaluate: reflect on the outcome of your problem solving strategies
PROBLEM SOLVING
ALGORITHM
• An algorithm is a procedure used for solving a problem or performing a computation.
• Algorithms act as an exact list of instructions that conduct specified actions step by step in either
hardware- or software-based routines.
ALGORITHM (CONT.)
Use of the Algorithms
Computer Science
Mathematics
Operations Research
Artificial Intelligence
Data Science

How to Design an Algorithm?


1. The problem that is to be solved by this algorithm i.e. clear problem definition.
2. The constraints of the problem must be considered while solving the problem.
3. The input to be taken to solve the problem.
4. The output is to be expected when the problem is solved.
5. The solution to this problem is within the given constraints.
ALGORITHM (CONT.)
Example: Consider the example to add three numbers and print the sum.
Algorithm to add 3 numbers and print their sum:
1. START
2. Declare 3 integer variables num1, num2, and num3.
3. Take the three numbers, to be added, as inputs in variables num1, num2, and
num3 respectively.
4. Declare an integer variable sum to store the resultant sum of the 3 numbers.
5. Add the 3 numbers and store the result in the variable sum.
6. Print the value of the variable sum
7. END
Disadvantages of Algorithms:
Advantages of Algorithms:
• Writing an algorithm takes a long time so it is time-
• It is easy to understand.
consuming.
• An algorithm is a step-wise representation of a
• Understanding complex logic through algorithms can
solution to a given problem.
be very difficult.
• In an Algorithm the problem is broken down into
• Branching and Looping statements are difficult to
smaller pieces or steps hence, it is easier for the
show in Algorithms.
programmer to convert it into an actual program.
COMPUTER PROGRAMMING
LECTURE 2
PRESENTED BY:
Prof. Dr. Md Abdur Rahim
Chairman
Department of Computer Science and Engineering
&
Director, ICT Cell
Pabna University of Science and Technology, Rajapur, Pabna.
Email: rahim@[Link]
Contact: +8801728548300
FLOWCHART (CONT.)
The Flowchart is the most widely used graphical representation of an algorithm and procedural design workflows.
Types of Flowchart
•Horizontal Flowchart
•Panoramic Flowchart
•Vertical Flowchart
•Architectural Flowchart
Rules or guidelines of Flow chart

• Only conventional flowchart symbols should be used.


• Proper use of names and variables in the flowchart.
• If the flowchart becomes large and complex, use connector
symbols.
• Flowcharts should have start and stop points.
FLOWCHART (CONT.)
Terminal Symbol: denoting the start and stop symbol.

Input/output Symbol: The symbol given below is used for representing the Input/output symbol.

Processing Symbol: represent the arithmetic and data movement instructions

Decision Symbol: Diamond symbol is used for represents decision-making statements.

Connector Symbol: The connector symbol is used if flows discontinued at some point and
continued again at another place.

Flow lines: It represents the exact sequence in which instructions are executed.
FLOWCHART (CONT.)
Hexagon symbol (Flat): It is used to create a preparation box containing the loop setting statement.

On-Page Reference Symbol: This symbol contains a letter inside that indicates the flow continues
on a matching symbol containing the same letters somewhere else on the same page.

Off-Page Reference: This symbol contains a letter inside indicating that the flow continues on a
matching symbol containing the same letter somewhere else on a different page.

Delay or Bottleneck: This symbol is used for identifying a delay in a flowchart.

Internal storage symbol: The symbol given below is used to represent the internal storage
symbol.
ADVANTAGES OF FLOWCHART
Following are the various advantages of flowchart:
• Communication: A flowchart is a better way of communicating the logic of a program.
• Synthesis: Flowchart is used as working models in designing new programs and software systems.
• Efficient Coding: Flowcharts act as a guide for a programmer in writing the actual code in a high-level language.
• Proper Debugging: Flowcharts help in the debugging process.
• Effective Analysis: Effective analysis of logical programs can be easily done with the help of a related flowchart.
• Proper Documentation: Flowchart provides better and proper documentation. It consists of various activities
such as collecting, organizing, storing, and maintaining all related program records.
• Testing: A flowchart helps in the testing process.
• Efficient program maintenance: The maintenance of the program becomes easy with the help of a flowchart.

Disadvantages of Flowchart in C:
• Time-consuming: Designing a flowchart is a very time-consuming process.
• Complex: It isn't easy to draw a flowchart for large and complex programs.
• There is no standard in the flowchart; there is no standard to determine the quantity of detail.
• Difficult to modify: It is very difficult to modify the existing flowchart.
EXAMPLE OF FLOWCHART
Design a flowchart for adding two
numbers entered by the user. Design a flowchart for finding the largest
among three numbers entered by the user.
EXAMPLE OF FLOWCHART
Design a flowchart for calculating the Design a flowchart for checking whether the number is positive
area of a rectangle. or negative according to the number entered by the user.
DEBUGGING
Debugging is a methodical process of finding and reducing the number of bugs (or defects) in a
computer program, thus making it behave as originally expected.
#include <stdio.h>
int main()
{
int i;
int numTerms = 10;
int t1 = 0, t2 = 1;
int nextTerm;
printf("Fibonacci Series: ");
for (i = 1; i <= numTerms; ++i)
{
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
ORIGIN AND HISTORY OF C
❖ The C Programming Language was initially developed by Denis Ritchie using a Unix system in 1972. This was
varied and modified until a standard was defined by Brian Kernighan and Dennis Ritchie in 1978 in "The C
Programming Language".
❖ By the early 80's many versions of C were available which were inconsistent with each other in many aspects.
This led to a standard being defined by ANSI in 1983. It is this standard this set of notes primarily addresses.
❖ C’ is one of the most popular computer languages today because it is a structured, high-level, machine
independent language. It allows software developers to develop programs without worrying about the
hardware platforms where they will be implemented.
❖ The root of all modern languages is ALGOL (short for Algorithmic Language), introduced in the early 1960s.
ALGOL was the first computer language to use a block structure.
❖ In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language)
primarily for writing system software. In 1970, Ken Thompson created a language using many features of
BCPL and called it simply B.
❖ C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell Laboratories in 1972.
❖ Today, C is running under a variety of operating system and hardware platforms.
IMPORTANCE OF C
• C is a robust language whose rich set of built-in functions and operators can be used to write any complex
program. C is the most popular programming language for the following reasons:
➢ Programs written in C are efficient and fast.
➢ There are only 32 keywords in ANSI C and strength lies in its built-in functions.
➢ C is highly portable.
➢ C language is well-suited for structured programming.
➢ C has its ability to extend itself.
➢ C is widely used in operating systems, embedded systems, compilers, and application development.
BASIC STRUCTURE OF C
• Documentation section
• The documentation section consists of a set of comment lines giving
the name of the program, the author and other details.
• Link section
• The link section provides instructions to the compiler to link
functions from the system library.
BASIC STRUCTURE OF C
/*Documentation Section: program to find the area of circle*/
#include <stdio.h> /*link section*/
#include <conio.h> /*link section*/
#define PI 3.14 /*definition section*/
float area; /*global declaration section*/
void main()
{
float r; /*declaration part*/
printf("Enter the radius of the circle"); /*executable part starts here*/
scanf("% f", & r);
area=PI*r*r;
printf("Area of the circle=%f", area);
//getch();
return 0;
}
DATA TYPES
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

Types Data Types


Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Enumeration Data Type enum
Void Data Type void
DATA TYPES (CONT.)
• The basic data types are integer-based and floating-point based. C language supports both signed and
unsigned literals.
• The memory size of the basic data types may change according to 32 or 64-bit operating system.

➢ "unsigned" indicates a variable that can hold only positive numbers.


➢ "signed" indicates that a variable can hold negative and positive values.

Data Types Memory Size Range


int 2 byte −32,768 to 32,767
signed int 2 byte −32,768 to 32,767
unsigned int 2 byte 0 to 65,535
DATA TYPES (CONT.)
Data Types Memory Size Range
• Integers are entire numbers without any fractional or decimal parts char 1 byte −128 to 127
signed char 1 byte −128 to 127

• Individual characters are represented by the char data type. Typically unsigned char 1 byte 0 to 255
short 2 byte −32,768 to 32,767
used to hold ASCII or UTF-8 encoding scheme characters, such
signed short 2 byte −32,768 to 32,767
as letters, numbers, symbols, or commas.
unsigned short 2 byte 0 to 65,535
int 2 byte −32,768 to 32,767
• Floating numbers can be used to represent fractional units or numbers signed int 2 byte −32,768 to 32,767
with decimal places. unsigned int 2 byte 0 to 65,535
short int 2 byte −32,768 to 32,767
• Double type, which uses 8 bytes of memory and has an accuracy of signed short int 2 byte −32,768 to 32,767
about 15 decimal places, yields larger values. unsigned short int 2 byte 0 to 65,535
long int 4 byte -2,147,483,648 to
• void to indicate that a function doesn't return a value or that it has 2,147,483,647
no parameters or both. signed long int 4 byte -2,147,483,648 to
2,147,483,647
int age = 25; unsigned long int 4 byte 0 to 4,294,967,295
char grade = 'A'; float 4 byte
float temperature = 98.6; double 8 byte

double pi = 3.14159265359; long double 10 byte


VARIABLES
➢ A variable is a named piece of memory which is used to hold a value
➢ A variable has three attributes : its type, its value and its address.

All C variables must be declared as follows :-


type variable-list ;
For Example :-
int i ;
char a, b, ch ;
Variables are declared in three general areas in a C program:
1. Local Variables: When declared inside functions as follows void main()
they are termed local variables and are visible (or accessible) {
within the function ( or code block ) only. int i, j ;
...
}
VARIABLES (CONT.)
2. Global Variables: When declared outside functions they are termed global variables and are visible
throughout the file or have file scope.
int i ;
void main()
{
...
}

3. Formal Parameters: When declared within the braces of a function they are termed the formal
parameters of the function
int func1( int a, char b ) ;
IDENTIFIERS
Identifiers refer to the names of variables, functions and arrays. These are user-defined names and
consist of a sequence of letters and digits.

Rules for identifiers:


1. First character must be an alphabet.
2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant.
4. Cannot use keyword.
5. Must not contain white space
CONSTANT
Constants are fixed values that cannot be altered by the program and can be numbers, characters or strings.
Some Examples :-
char : 'a', '$', '7'
int : 10, 100, -100
unsigned : 0, 255
float : 12.23456, -1.573765e10, 1.347654E-13
double : 1433.34534545454, 1.35456456456456E-200
long : 65536, 2222222
string : “Hello World\n”

❑ There are also a number of special character constants \n newline


sometimes called Escape Sequences, which are \t tab
preceded by the backslash character '\', and have \b backspace
special meanings in C. \' single quote
\" double quote
\0 null character
\xdd represent as hexadecimal constant
KEYWORD
❖ Keywords are predefined or reserved words that have special meanings to the compiler.
❖ All keywords have fixed meanings and these meanings cannot be changed known as Keywords.
❖ All keywords must be written in lower case. int, float , else, for, getch are the examples of
keywords.
❖ 32 Keywords in C

auto break case char


const continue default do
double else enum extern
float for if int
long register return short
signed sizeof static struct
switch typedef union unsigned
void goto volatile while
CONSOLE INPUT/OUTPUT
• This section introduces some of the more common input and output functions provided in the C
standard library.
• The printf() function is used for formatted output and uses a control string which is made up of a
series of format specifiers to govern how it prints out the
%c character %f floating point
%d signed integer %lf double floating point
%i signed integer %e exponential notation
%u unsigned integer %s string
%ld signed long %x unsigned hexadecimal
%lu unsigned long %o unsigned octal
%% prints a % sign

For Example :-
int i,j ;

printf("%d \n %d", i,j ) ;


CONSOLE INPUT/OUTPUT (CONT.)
scanf()
This function is similar to the printf function except that it is used for formatted input. The format specifiers have
the same meaning as for printf() and the space character or the newline character are normally used as delimiters
between different inputs.
For Example :-
int i, d ;
char c ;
float f ;

scanf( "%d", &i ) ;


scanf( "%d %c %f", &d, &c, &f ) ;
CONSOLE INPUT/OUTPUT (CONT.)
Write a C program to add and display the sum of two integers entered by the user.

#include <stdio.h>
int main( )
{
int num1, num2, sum;
printf("Enter First integer:");
scanf("%d",&num1);
printf("Enter Second integer: ");
scanf("%d",&num2);
sum=num1+num2;
printf("Num1=%d \n Num2=%d \n Sum= %d", num1, num2, sum);
return 0;
}
CONSOLE INPUT/OUTPUT (CONT.)

getchar() and putchar()

The getchar() function reads the ASCII value of a character input at the keyboard and displays the
character while putchar() displays a character on the standard output device i.e. the screen.

For Example :-
char ch1, ch2 ;

ch1 = getchar() ;

ch2 = 'a' ;
putchar( ch2 ) ;
OPERATORS
One of the most important features of C is that it has a very rich set of built in operators including
arithmetic, relational, logical, and bitwise operators.
Arithmetic Operators
+, - , *, / -- same rules as mathematics with * and / being evaluated before + and -.
% -- modulus / remainder operator
Increment and Decrement Operators
There are two special unary operators in C, Increment ++, and Decrement -- , which cause the variable they act on
incremented or decremented by 1 respectively.
For Example :-
x++ ; /* equivalent to x = x + 1 ; */
++ and -- can be used in prefix or postfix notation. In prefix notation the value of the variable is either incremente
decremented and is then read while in postfix notation the value of the variable is read first and is then incremente
decremented.
For Example :-
int i, j = 2 ;
i = ++j ;/* prefix :- i has value 3, j has value 3 */
i = j++ ; /* postfix :- i has value 3, j has value 4 */
OPERATORS (CONT.)
Increment and Decrement Operators

There are two special unary operators in C, Increment ++, and Decrement -- , which cause the variable they act on
to be incremented or decremented by 1 respectively.
For Example :-
x++ ; /* equivalent to x = x + 1 ; */

++ and -- can be used in prefix or postfix notation. In prefix notation the value of the variable is either incremented or
decremented and is then read while in postfix notation the value of the variable is read first and is then incremented
or decremented.

For Example :-
int i, j = 2 ;
i = ++j ;/* prefix :- i has value 3, j has value 3 */
i = j++ ; /* postfix :- i has value 3, j has value 4 */
OPERATORS (CONT.)
Increment and Decrement Operators

Many C operators can be combined with the assignment operator as shorthand notation

For Example :-
x = x + 10 ;
can be replaced by
x += 10 ;

Similarly for -=, *=, /=, %=, etc.


OPERATORS (CONT.)
Relational Operators
The full set of relational operators are provided in shorthand notation
> >= < <= == !=
For Example :-
if ( x == 2 )
printf( “x is equal to 2\n” ) ;

Logical Operators
&& -- Logical AND
| | -- Logical OR
! -- Logical NOT

For Example :-
if ( x >= 0 && x < 10 )
printf( “ x is greater than or equal to zero and less than ten.\n” ) ;
OPERATORS (CONT.)

Bitwise Operators
These are special operators that act on char or int arguments only. They allow the
programmer to get closer to the machine level by operating at bit-level in their arguments.

& Bitwise AND | Bitwise OR


^ Bitwise XOR ~ Ones Complement
>> Shift Right << Shift left

Recall that type char is one byte in size. This means it is made up of 8 distinct bits or binary digits normally
designated as illustrated below with Bit 0 being the Least Significant Bit (LSB) and Bit 7 being the Most
Significant Bit (MSB). The value represented below is 13 in decimal.

Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0


0 0 0 0 1 1 0 1
OPERATORS (CONT.)
Bitwise Operators: Bitwise AND, &

RULE : If any two bits in the same bit position are set then the resultant bit in that position is set
otherwise it is zero.

For Example :-
1011 0010 (178)
& 0011 1111 (63)
= 0011 0010 (50)
Bitwise OR, |

RULE : If either bit in corresponding positions are set the resultant bit in that position is set.

For Example :-
1011 0010 (178)
| 0000 1000 (63)
1011 1010 (186)
OPERATORS (CONT.)
Bitwise XOR, ^

RULE : If the bits in corresponding positions are different then the resultant bit is set.

For Example :-
1011 0010 (178)
^ 0011 1100 (63)
= 1000 1110 (142)
OPERATORS (CONT.)
Sizeof Operator
The sizeof operator gives the amount of storage, in bytes, associated with a variable or a type
Syntax : sizeof ( expression )

For Example :-
int x , size ;

size = sizeof ( x ) ;
printf(“The integer x requires %d bytes on this machine”, size);

printf( “Doubles take up %d bytes on this machine”, sizeof ( double ) ) ;


OVERFLOW AND UNDERFLOW
• When the value to be stored in a variable of a particular type is larger than the range of values that type
can hold we have what is termed type overflow.
• Likewise when the value is smaller than the range of values the type can hold we have type underflow.
PROGRAMMING ERRORS
• Errors are the problems or the faults that occur in the program, which makes the behavior of the
program abnormal, and experienced developers can also make these faults. Programming errors are also
known as the bugs or faults, and the process of removing these bugs is known as debugging.
There are mainly five types of errors exist in C programming:
•Syntax error
•Run-time error
•Linker error
•Logical error
•Semantic error

•Syntax error
• Syntax errors are also known as the compilation errors as they occurred at the compilation time
• These errors are mainly occurred due to the mistakes while typing or do not follow the syntax of the specified
programming language.
PROGRAMMING ERRORS
• Errors are the problems or the faults that occur in the program, which makes the behavior of the
program abnormal, and experienced developers can also make these faults. Programming errors are also
known as the bugs or faults, and the process of removing these bugs is known as debugging.

There are mainly five types of errors exist in C programming:


•Syntax error
•Run-time error
•Linker error
•Logical error
•Semantic error

•Syntax error
• Syntax errors are also known as the compilation errors as they occurred at the compilation time
• These errors are mainly occurred due to the mistakes while typing or do not follow the syntax of the specified
programming language. int a; // this is the correct form
Int a; // this is an incorrect form.
PROGRAMMING ERRORS
•Run-time error
Sometimes the errors exist during the execution-time even after the successful compilation known as run-time
errors.
When the program is running, and it is not able to perform the operation is the main cause of the run-time error.
#include <stdio.h>
int main()
{
int a=2;
int b=2/0;
printf("The value of b is : %d", b);
return 0;
}
PROGRAMMING ERRORS
•Linker error
Linker errors are mainly generated when the executable file of the program is not created. This can be
happened either due to the wrong function prototyping or usage of the wrong header file.
#include <stdio.h>
int Main()
{
int a=78;
printf("The value of a is : %d", a);
return 0;
}
Logical error
The logical error is an error that leads to an undesired output. These errors produce the incorrect output, but they
are error-free, known as logical errors.

for(int i=1;i<=10;i++); // logical error, as we put the semicolon after loop


PROGRAMMING ERRORS
•Semantic error
Semantic errors are the errors that occurred when the statements are not understandable by the compiler.

Use of a un-initialized variable.


int i;
i=i+2;

Array index out of bound


int a[10];
a[10] = 34;
SOURCE CODE & OBJECT CODE
Source code is the original program written by a programmer using a high-level or assembly language
(such as C, C++, Java).
Characteristics:
• Human-readable
• Written using programming language syntax. Saved as .c, .cpp, .java, etc.
• Cannot be executed directly by the computer
Example
int sum = a + b;

Object Code
Object code is the machine-readable code generated after compiling the source code.
Characteristics:
•Written in machine language (binary)
•Not human-readable
•Usually stored as .obj or .o files
•Used as input for the linker to create executable code
Example (conceptual):
10101010 00101101
SOURCE CODE & OBJECT CODE (CONT.)

Feature Source Code Object Code


Written by Programmer Compiler
Readability Human-readable Machine-readable
Language High-level / Assembly Machine language
Executable No No (needs linking)
File Extension .c, .cpp .obj, .o
COMPILER & TRANSLATOR
Translator
A translator is a system software that converts a program written in one language into another
language, usually into machine language, so the computer can execute it.
Types of Translators:
•Compiler
•Interpreter
•Assembler
Example:
C → Compiler → Machine code

Compiler
A compiler is a translator that converts the entire high-level language program into machine (object) code
at once.
Key Points:
Translates the whole program together
Produces object/executable code
Errors are shown after compilation
Program execution is fast after compilation
Example:
C, C++ compiler (GCC)
INTERPRETER & ASSEMBLER
Interpreter
An interpreter is a translator that translates and executes the program line by line.
Key Points:
➢ No object code is generated
➢ Errors are shown immediately (one line at a time)
➢ Execution is slower
➢ Easy to debug
Example:
Python, JavaScript interpreter C Program

Assembler
Compiler
An assembler is a translator that converts assembly language into machine

language.
Assembly Code
Key Points:

•Works with low-level assembly language
Assembler
•Produces machine code

•Machine-dependent
Machine Code (Executable)
•Used in system and embedded programming
Example:
MASM, NASM
COMPUTER PROGRAMMING
LECTURE 3
EXPRESSIONS AND STATEMENTS
PRESENTED BY:
Prof. Dr. Md Abdur Rahim
Chairman
Department of Computer Science and Engineering
&
Director, ICT Cell
Pabna University of Science and Technology, Rajapur, Pabna.
Email: rahim@[Link]
Contact: +8801728548300
EXPRESSION
An expression is a formula in which operands are linked to each other by the use of operators to
compute a value. An operand can be a function reference, a variable, an array element or a constant.

Example: a-b;

An expression into a C statement requires the addition of a terminating semi-colon.

There are four types of expressions exist in C:


STATEMENT
A definition or declaration specifies the data on which a program is to operate, while a statement specifies the
actions to be taken with that data.
CONTROL STATEMENT
❖ The control statements help users specify the order of execution of the instructions present in a
program.
❖ These make it possible for the program to make certain decisions, perform various tasks repeatedly, or
even jump from any one section of the code to a different section.

Control Statements Types Used in C Language

Switch Statement. Conditional Operator Statement. Goto Statement. Loop Statements.


CONTROL STATEMENT
❖ The control statements help users specify the order of execution of the instructions present in a
program.
❖ These make it possible for the program to make certain decisions, perform various tasks repeatedly, or
even jump from any one section of the code to a different section.

Control Statements Types Used in C Language

If Statements
Switch Statement
Conditional Operator Statement
Goto Statement
Loop Statements
CONTROL STATEMENT
If Statements
This type of statement would enable a programmer to choose various instruction
sets on the basis of the available condition.
For Example : Program to perform integer division avoiding the
division by zero case.
#include <stdio.h>
The if statement is the most general method
void main()
for allowing conditional execution in C.
{
int numerator, denominator ;
Syntax : if ( condition )
statement body ;
printf( "Enter two integers as follows numerator, denominator :" );
else
scanf( "%d, %d", &numerator, &denominator ) ;
statement body ;
or just :
if ( denominator != 0 )
if ( condition )
printf( "%d / %d = %d \n", numerator, denominator, numerator /
statement body ;
denominator );
else
printf( "Invalid operation - unable to divide by zero \n” );
return 0;
}
CONTROL STATEMENT
These are also known as decision control
statements. These are of the following types:
➢ Simple else or Null else
➢ Else if ladder
➢ Nested if
➢ If… else
If… Else Statement
there occurs an execution of two different types of statements in a program.
• First, if the available condition in the program is true, then there will be an execution of
the first statement.
• The execution of the second condition will only occur if the condition available to us is
false.
IF..ELSE STATEMENT
The syntax for this statement is as follows: Example:
If (condition 1) height=int (input(“Please enter your height: “))
{ if height>=160:
Statement 1 (s1); qualified=True
} else:
else qualified=False
{ print(“Qualification status: “,qualification)
Statement 2 (s2)
}
Statement
NESTED IF ELSE STATEMENT
In this case, the condition available in the next if statement (the second statement) will only
get evaluated if the evaluation of the condition available in the first statement turns out to
be true. This occurs throughout the program that has a nested statement.
The syntax for this statement is as follows:
If (condition 1)
{
If (condition 2)
{
Statement 1 (s1);
}
Else
{
Statement 2 (s2) For Example :-
if ( x > 0 )
}
if ( x > 10 )
}
puts ( " x is greater than zero and also greater than 10 ");
else
puts ("x is greater than zero but less than or equal to 10");
ELSE IF LADDER
The syntax for this statement is as
In this statement, the execution of an follows:
array of instructions occurs only when If (condition 1)
the available condition is correct. The {
verification of the next condition occurs Statement 1 (s1);
when this first condition is incorrect. In }
case all of the specifications fail even Else if (condition 2)
after the verification, then there will be {
an execution of the default block Statement 2 (s2);
statements. } Example:
else if (condition 3) if scores>=85:
{ result=’A+’
Statement 3 (s3) else if scores>=65:
} result=’B+’
… else if scores>=45:
Else result=’C+’
{ else:
Statement 4 (s4) result=”FAIL”
} print(“Result: “,result)
SWITCH STATEMENT
The switch statement allows us to execute one
How does the switch statement work?
code block among many alternatives.
You can do the same thing with the if...else..if
The expression is evaluated once and compared with the values
ladder. However, the syntax of the switch
of each case label.
statement is much easier to read and write.
• If there is a match, the corresponding statements after the
switch (expression)
matching label are executed. For example, if the value of the
{
expression is equal to constant2, statements after case
case constant1:
constant2: are executed until break is encountered.
// statements
• If there is no match, the default statements are executed.
break;
case constant2:
// statements
break;
.
.
default:
// default statements
}
// Program to create a simple calculator
#include <stdio.h>

SWITCH STATEMENT int main() {


char operation;
double n1, n2;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operation);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);

switch(operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;

case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;

case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;

case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;

Output // operator doesn't match any case constant +, -, *,


/
Enter an operator (+, -, *, /): - default:
Enter two operands: 32.5 printf("Error! operator is not correct");
}
12.4
32.5 - 12.4 = 20.1 return 0;
}
BREAK STATEMENT
The break statement ends the loop immediately when it is encountered.
Its syntax is:
break;
CONTINUE STATEMENT // Program to calculate the sum of numbers (10
numbers max)
// If the user enters a negative number, it's not added to
The continue statement skips the current the result
iteration of the loop and continues with the next
iteration. Its syntax is: #include <stdio.h>
continue; int main() {
int i;
double number, sum = 0.0;

for (i = 1; i <= 10; ++i) {


Output printf("Enter a n%d: ", i);
scanf("%lf", &number);
Enter n1: 1.1
Enter n2: 2.2 if (number < 0.0) {
Enter n3: 5.5 continue;
Enter n4: 4.4 }
Enter n5: -3.4 sum += number; // sum = sum + number;
Enter n6: -45.5 }
Enter n7: 34.5
Enter n8: -4.2 printf("Sum = %.2lf", sum);
Enter n9: -1000
Enter n10: 12 return 0;
Sum = 59.70 }
FOR STATEMENT
for statement
The for statement is most often used in situations where the programmer knows in advance
how many times a particular set of statements are to be repeated. The for statement is
sometimes termed a counted loop.

Syntax : for ( [initialisation] ; [condition] ; [increment] )


int i;
[statement body] ;
for (i = 0; i < 5; i++) {
initialisation :-
printf("%d\n", i);
➢ this is usually an assignment to set a loop counter variable for example.
}
➢ executed (one time) before the execution of the code block.
condition :- determines when loop will terminate.
increment :- defines how the loop control variable will change each time the loop is executed.
statement body :- can be a single statement, no statement or a block of statements.
STATEMENTS (CONT.)
The for statement executes as follows :-
For Example : To print out all numbers from 1 to
100 and calculate their sum.
initialisation
.

test condition
FALSE #include <stdio.h>

TRUE void main()


continue
with next {
iteration int x, sum = 0 ;
statement body
for ( x = 1; x <= 100; x++ )
{
increment printf( "%d\n", x ) ;
sum += x ;
}
end of statement
printf( “\n\nSum is %d\n”, sum ) ;
}
STATEMENTS (CONT.)
Example 1: Half Pyramid of *
Nested Loop
*
• It is also possible to place a loop inside **
another loop. This is called a nested loop. ***
• The "inner loop" will be executed one time ****
for each iteration of the "outer loop" *****

int i, j; #include <stdio.h>


int main() {
// Outer loop int i, j, rows;
for (i = 1; i <= 2; ++i) { printf("Enter the number of rows: ");
printf("Outer: %d\n", i); // Executes 2 times scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
// Inner loop for (j = 1; j <= i; ++j) {
for (j = 1; j <= 3; ++j) { printf("* ");
printf(" Inner: %d\n", j); // Executes 6 times (2 * 3) }
} printf("\n");
} }
return 0;
}
STATEMENTS (CONT.) Example 3: Inverted half pyramid of numbers
Example 2: Half Pyramid of Numbers

1 12345
12 1234
123 123
1234 12
12345 1

#include <stdio.h> #include <stdio.h>


int main() { int main() {
int i, j, rows; int i, j, rows;
printf("Enter the number of rows: "); printf("Enter the number of rows: ");
scanf("%d", &rows); scanf("%d", &rows);
for (i = 1; i <= rows; ++i) { for (i = rows; i >= 1; --i) {
for (j = 1; j <= i; ++j) { for (j = 1; j <= i; ++j) {
printf("%d ", j); printf("%d ", j);
} }
printf("\n"); printf("\n");
} }
return 0; return 0;
} }
#include <stdio.h>
STATEMENTS (CONT.) int main() {
int i, space, rows, k = 0, count = 0, count1 = 0;
printf("Enter the number of rows: ");
Example 7: Full Pyramid of Numbers scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
1 for (space = 1; space <= rows - i; ++space) {
232 printf(" ");
34543 ++count;
4567654 }
567898765 while (k != 2 * i - 1) {
if (count <= rows - 1) {
printf("%d ", i + k);
++count;
} else {
++count1;
printf("%d ", (i + k - 2 * count1));
}
++k;
}
count1 = count = k = 0;
printf("\n");
}
return 0;
}
STATEMENTS (CONT.)
The while statement is typically used in situations where it is not known in advance how
many iterations are required.
The while loop loops through a block of code as long as a specified condition is true:

Syntax : while ( condition ) In the example below, the code in the loop will run, over
statement body ; and over again, as long as a variable (i) is less than 5:

FALSE int i = 0;
test condition
while (i < 5) {
printf("%d\n", i);
TRUE
continue i++;
with next
iteration }
statement body

end of statement

1. do while 2. break statement 3. continue statement


STATEMENTS (CONT.)
Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax : The loop will always be executed at least once, even if


the condition is false, because the code block is executed
do { before the condition is tested:
// code block to be executed
} int i = 0;
while (condition);
do {
printf("%d\n", i);
i++;
}
while (i < 5);
DECISION STATEMENTS
if statement [Link]

The if statement is the most general method for


allowing conditional execution in C.

Syntax : if ( condition )
statement body ;
else
statement body ;
or just :
if ( condition )
statement body ;

if ( denominator != 0 )
printf( "%d / %d = %d \n", numerator, denominator,
numerator / denominator );
else
printf( "Invalid operation - unable to divide by zero \n” );
DECISION STATEMENTS (CONT.)
Write a C program that displays the greater number between two integer numbers.
#include<stdio.h>
#include<conio.h>
int main()
{
int a=15, b=20;

if(b>a)
{
printf("b is greater");
}
return 0;
}
DECISION STATEMENTS (CONT.)
Nested if statements
if - else statements like all other decision or iteration statements in C can be nested to whatever
extent is required. Care should be taken however to ensure that the if and else parts of the
statement are matched correctly -- the rule to follow is that the else statement matches the most
recent unmatched if statement.

Syntax : if ( condition_1 )
statement_1 ;
else if ( condition_2 )
statement_2 ;
else if ( condition_3 )
statement_3 ;
...

else if ( condition_n )
statement_n ;
else
statement_default ;
COMPUTER PROGRAMMING
LECTURE 3
FUNCTIONS
PRESENTED BY:
Prof. Dr. Md Abdur Rahim
Chairman
Department of Computer Science and Engineering
&
Director, ICT Cell
Pabna University of Science and Technology, Rajapur, Pabna.
Email: rahim@[Link]
Contact: +8801728548300
FUNCTIONS
In c, a large program divides into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}.
A function can be called multiple times to provide reusability and modularity to the C program.

Advantage of functions in C
➢ By using functions, we can avoid rewriting same logic/code again and again in a program.
➢ We can call C functions any number of times in a program and from any place in a program.
➢ We can track a large C program easily when it is divided into multiple functions.
➢ Reusability is the main achievement of C functions.
➢ However, Function calling is always a overhead in a C program.
FUNCTIONS ASPECTS
There are three aspects of a C function.
❖ Function declaration A function must be declared globally in a c program to tell the compiler about the
function name, function parameters, and return type.

❖ Function call Function can be called from anywhere in the program. The parameter list must not differ in
function calling and function declaration. We must pass the same number of functions as it is declared in the
function declaration.

❖ Function definition It contains the actual statements which are to be executed. It is the most important
aspect to which the control comes when the function is called. Here, we must notice that only one value can
be returned from the function.

SN C function aspects Syntax


1 Function declaration return_type function_name (argument list);
2 Function call function_name (argument_list)
3 Function definition return_type function_name (argument list) {function body;}
FUNCTIONS DECLARATION
Syntax : type_spec function_name( type_par1, type_par2, etc. );

This declaration simply informs the compiler what type the function returns and what type and how
many parameters it takes.

For Example :- A more complicated “Hello World” program.

#include <stdio.h> /* standard I/O function prototypes */


void hello( void ) ; /* prototype */
void main( void )
{
hello () ; // function call
}
void hello ( ) // function definition
{
printf ( "Hello World \n" ) ;
}
FUNCTIONS DEFINITION
A function definition actually defines what the function does and is essentially a discrete block of code which cannot
be accessed by any statement in any other function except by formally calling the function.

For Example :-
#include <stdio.h>
void hello( void ) ;
void main( )
{
hello () ;
}
void hello ( )
{
int i ; /* local or automatic variable */
for ( i=0; i<10; i++ )
printf( "Hello World \n" );
}
The variable i in the hello() function is private to the hello function i.e. it can only be accessed by code in the
hello() function.
TYPES OF FUNCTIONS
There are two types of functions in C programming:
➢ Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(),
puts(), ceil(), floor() etc.
➢ User-defined functions: are the functions which are created by the C programmer, so that he/she can use it
many times. It reduces the complexity of a big program and optimizes the code.

Return Value Example without return value:


A C function may or may not return a value from the function. If you don't
have to return any value from the function, use void for the return type. void hello(){
printf("hello c");
}
Example with return value:
To return any value from the function, need to use any data type such as int,
long, char, etc. The return type depends on the value to be returned from the
int get(){
function.
return 10;
}
LIBRARY FUNCTIONS
The standard library functions are built-in functions in C programming.

These functions are defined in header files. For example,

The printf() is a standard library function to send formatted output to the screen (display output on the
screen). This function is defined in the stdio.h header file.
Hence, to use the printf()function, we need to include the stdio.h header file using #include <stdio.h>.
The sqrt() function calculates the square root of a number. The function is defined in the math.h header file.
C LIBRARY FUNCTIONS
Library functions are the inbuilt function in C that are grouped and placed at a common place called the library.
SN Header file Description
1 stdio.h This is a standard input/output header file. It contains all the library functions regarding standard
input/output.
2 conio.h This is a console input/output header file.
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(), calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions like sqrt(), pow(), etc.
6 time.h This header file contains all the time-related functions.
7 ctype.h This header file contains all character handling functions.
8 stdarg.h Variable argument functions are defined in this header file.
9 signal.h All the signal handling functions are defined in this header file.
10 setjmp.h This file contains all the jump functions.
11 locale.h This file contains locale functions.
12 errno.h This file contains error handling functions.
13 assert.h This file contains diagnostics functions.
USER DEFINED FUNCTION
Functions created by the user are known as user-defined functions.

❖ The execution of a C program begins from the main()


function.

When the compiler encounters functionName();, control of the


program jumps to
❖ And, the compiler starts executing the codes inside
functionName().

The control of the program jumps back to the main() function


once code inside the function definition is executed.

• Function names are identifiers and should be unique.


USER DEFINED FUNCTION (CONT.)
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, we have created an user-
defined addNumbers().
CALLING A FUNCTION
Control of the program is transferred to the user-defined function by calling it.

Syntax of function call

functionName(argument1, argument2, ...);

In the above example, the function call is made using addNumbers(n1, n2); statement inside the main()
function.
FUNCTION DEFINITION
Function definition contains the block of code to perform a specific task. In our example, adding two
numbers and returning it.

Syntax of function definition


returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}

When a function is called, the control of the program is transferred to the function definition. And, the
compiler starts executing the codes inside the body of a function.
PASSING ARGUMENTS TO A FUNCTION
• In programming, argument refers to the variable passed to
the function.

• two variables n1 and n2 are passed during the function call.


(Previous Example)

• The parameters a and b accepts the passed arguments in


the function definition. These arguments are called formal
parameters of the function.

If n1 is of char type, a also should be of char type. If n2 is of


float type, variable b also should be of float type.
RETURN STATEMENT
The return statement terminates the execution of a function and returns a value to the calling function. The
program control is transferred to the calling function after the return statement.

The return statement is used to return a value to the calling function if necessary.
Syntax of return statement
return (expression);
For example,

return a;
return (a+b);

the value of the result variable is returned to the main function.


The sum variable in the main() function is assigned this value.
C FUNCTION TYPE
Different aspects of function calling
A function may or may not accept any argument. It may or may not return any value. Based on these facts,
There are four different aspects of function calls.
❖ function without arguments and without return value
❖ function without arguments and with return value
❖ function with arguments and without return value Example: Function without argument
❖ function with arguments and with return value and without return value

#include<stdio.h>
void printName();
A function that doesn’t take any input (no arguments) and
void main ()
doesn’t provide an output (no return value).
{
printf("Hello ");
printName();
}
void printName()
{
printf("Javatpoint");
}
FUNCTIONS CALLING
A function that doesn’t take any input but Example for Function without arguments and with return value
provides an output (has a return value).
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
FUNCTIONS CALLING
A function that takes input (arguments) and provides an
A function that takes input (arguments) but doesn’t return a value. output (returns a value).
Example for Function with argument and without a return value Example for Function with argument and with return value
#include<stdio.h>
void sum(int, int); #include<stdio.h>
void main() int sum(int, int);
{ void main()
int a,b,result; {
printf("\nGoing to calculate the sum of two numbers:"); int a,b,result;
printf("\nEnter two numbers:"); printf("\nGoing to calculate the sum of two numbers:");
scanf("%d %d",&a,&b); printf("\nEnter two numbers:");
sum(a,b); scanf("%d %d",&a,&b);
} result = sum(a,b);
void sum(int a, int b) printf("\nThe sum is : %d",result);
{ }
printf("\nThe sum is %d",a+b); int sum(int a, int b)
} {
return a+b;
}
FUNCTION PROTOTYPE
• A function prototype is simply the declaration of a function that specifies function's name, parameters and return
type. It doesn't contain function body.

• A function prototype gives information to the compiler that the function may later be used in the program.

Syntax of function prototype

returnType functionName(type1 argument1, type2 argument2, ...);


int addNumbers(int a, int b); is the function prototype which provides the following information to the
compiler:
➢ name of the function is addNumbers()
➢ return type of the function is int
➢ two arguments of type int are passed to the function
The function prototype is not needed if the user-defined function is defined before the main() function.
FUNCTION ARGUMENTS
Function arguments (or parameters) are values that you provide to a function when you call it.
They serve as inputs to the function, allowing it to perform its operations based on these values.

Types of Arguments

Positional Arguments: Passed in the exact order as the function parameters.

def add(a, b):


return a + b

result = add(5, 3) # 5 and 3 are positional arguments

Keyword Arguments: Explicitly mention the parameter name when passing the argument.
def introduce(name, age):
print(f"Name: {name}, Age: {age}")
introduce(age=25, name="Bob") # Keyword arguments allow changing order
FUNCTION ARGUMENTS
Default Arguments: Parameters that have default values if no argument is provided.

def greet(name="Guest"):
print("Hello, " + name)

greet() # Uses default value "Guest"

Variable-Length Arguments: Functions that accept any number of arguments


using *args for positional and **kwargs for keyword arguments.

def print_numbers(*args):
for number in args:
print(number)

print_numbers(1, 2, 3, 4) # Can take any number of arguments


CALL BY VALUE AND CALL BY
REFERENCE
There are two methods to pass the data into the function in C language, i.e., call by value and call by reference.
CALL BY VALUE AND CALL BY
REFERENCE
Call by Value in C
•Definition: In call by value, a copy of the argument's value is passed to the function. Any changes made to the parameter
within the function do not affect the original variable.
•Behavior: The function works with a separate copy of the data. Modifying the parameter only changes the copy, leaving the
original variable unchanged.
#include <stdio.h>

void increment(int number) {


number += 1;
printf("Inside function: %d\n", number);
}

int main() {
int x = 5;
increment(x);
printf("Outside function: %d\n", x);
return 0;
}
CALL BY VALUE AND CALL BY
REFERENCE
Call by Reference in C
•Definition: In call by reference, the function receives a reference to the original variable, not just a copy. This
allows the function to modify the actual variable's value.
•Behavior: Since C doesn’t support true call by reference, we use pointers to pass the address of the variable.
The function receives this address, enabling it to access and modify the original variable.
#include <stdio.h>
void increment(int *number) {
*number += 1; // Dereference pointer to modify the actual
variable
printf("Inside function: %d\n", *number);
}
int main() {
int x = 5;
increment(&x); // Pass address of x
printf("Outside function: %d\n", x);
return 0;
}
COMPUTER PROGRAMMING
LECTURE 5
ARRAY
PRESENTED BY:
Prof. Dr. Md Abdur Rahim
Chairman
Department of Computer Science and Engineering
&
Director, ICT Cell
Pabna University of Science and Technology, Rajapur, Pabna.
Email: rahim@[Link]
Contact: +8801728548300
ARRAY
An array is a group of similar elements or data items of the same type collected at contiguous
memory locations.
It can be used to store the collection of primitive data types such as int, char, float, etc., and also
derived and user-defined data types such as pointers, structures, etc.
ARRAY (CONT.)
Syntax of Array Declaration
data_type array_name [size];
or
data_type array_name [size1] [size2]...[sizeN];

where N is the number of dimensions.


C ARRAY INITIALIZATION
• Initialization in C is the process to assign some initial value to the variable.
• When the array is declared or allocated memory, the elements of the array contain some garbage
value. So, we need to initialize the array to some meaningful value.
• There are multiple ways in which we can initialize an array in C.

1. Array Initialization with Declaration


In this method, to initialize the array along with its declaration. We use an initializer list to initialize multiple
elements of the array. An initializer list is the list of values enclosed within braces { } separated by comma.
data_type array_name [size] = {value1, value2, ... valueN};
C ARRAY INITIALIZATION
2. Array Initialization with Declaration without Size

data_type array_name[] = {1,2,3,4,5};

The size of the above arrays is 5 which is automatically deduced by the compiler.

3. Array Initialization after Declaration (Using Loops)

We initialize the array after the declaration by assigning the initial value to each element individually. We
can use for loop, while loop, or do-while loop to assign the value to each element of the array.
for (int i = 0; i < N; i++) {
array_name[i] = valuei;
}
C ARRAY INITIALIZATION
// C Program to demonstrate array initialization
#include <stdio.h>
int main()
{

// array initialization using initializer list

int arr[5] = { 10, 20, 30, 40, 50 };

// array initialization using initializer list without


// specifying size

int arr1[] = { 1, 2, 3, 4, 5 };

// array initialization using for loop

float arr2[5];

for (int i = 0; i < 5; i++) {


arr2[i] = (float)i * 2.1;
}

return 0;
}
ACCESS ARRAY ELEMENTS
We can access any element of an array in C using the array subscript operator [ ] and the index value i of
the element.
array_name [index];

the indexing in the array always starts with 0, i.e., the first element is at index 0 and the last element is
at N – 1 where N is the number of elements in the array.
ACCESS ARRAY ELEMENTS (CONT.)
// C Program to illustrate element access using array
// subscript
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 15, 25, 35, 45, 55 };

// accessing element at index 2 i.e 3rd element


printf("Element at arr[2]: %d\n", arr[2]);
// accessing element at index 4 i.e last element
printf("Element at arr[4]: %d\n", arr[4]);
// accessing element at index 0 i.e first element
printf("Element at arr[0]: %d", arr[0]);
return 0;
}
HOW TO USE ARRAY IN C?
// C Program to demonstrate the use of array
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 10, 20, 30, 40, 50 };
// modifying element at index 2
arr[2] = 100;
// traversing array using for loop
printf("Elements in Array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Output
Elements in Array: 10 20 100 40 50
TYPES OF ARRAY
There are two types of arrays based on the number of dimensions it has. They are as follows:
1. One Dimensional Arrays (1D Array)
2. Multidimensional Arrays

One Dimensional Array in C


The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one dimension.
Syntax of 1D Array in C
array_name [size];
1D ARRAY Array of Characters (Strings)

In C, a sequence of characters in the form of an


// C Program to illustrate the use of 1D array
#include <stdio.h> array of characters terminated by a NULL
int main() character. These are called strings in C language.
{
// 1d array declaration
// C Program to illustrate strings
int arr[5];
#include <stdio.h>
// 1d array initialization using for loop
int main()
for (int i = 0; i < 5; i++) {
{
arr[i] = i * i - 2 * i + 1;
}
// creating array of character
printf("Elements of Array: ");
char arr[6] = { 'G', 'e', 'e', 'k', 's', '\0' };
// printing 1d array by traversing using for loop
for (int i = 0; i < 5; i++) {
// printing string
printf("%d ", arr[i]);
int i = 0;
}
while (arr[i]) {
return 0;
printf("%c", arr[i++]);
}
}
return 0;
Output
}
Elements of Array: 1 0 1 4 9
STRING
In C, a sequence of characters in the form of an array of characters terminated by a NULL character. These
are called strings in C language.

In C a string is defined as a character array which is terminated by a special character, the null character '\0', as there is
no string type as such in C.

For Example :- string to hold 5 characters

char s[6] ;

'\0'
A string constant is simply a list of characters within double quotes e.g. "Hello" with the '\0' character being automatically
appended at the end by the compiler.
A string may be initialised as simply as follows

char s[6] = "Hello" ;

'H' 'e' 'l' 'l' 'o' '\0'


MANIPULATING STRINGS
We can print out the contents of a string using printf() as we have seen already or by using puts().
printf( "%s", s ) ;
puts( s ) ;
Strings can be read in using scanf()
scanf( "%s", s ) ;
Where we do not require the familiar & as the name of an array without any index or square braces is also
the address of the array.

A string can also be read in using gets()

gets ( s ) ;
char s1[20] = “String1”, s2[20] = “String2” ;
int i ;
strcpy( s1, s2 ) ; /* copies s2 into s1. */
i = strcmp( s1,s2 ) ; /* compares s1 and s2. It returns zero if
s1 same as s2,-1 if s1 < s2, and +1 if s1 > s2 */
i = strlen( s1 ) ; /* returns the length of s1 */

strcat ( s1, s2 ) ; /* Concatenates


MULTIDIMENSIONAL ARRAY IN C
Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of the popular
multidimensional arrays are 2D arrays and 3D arrays. We can declare arrays with more dimensions than 3d arrays but
they are avoided as they get very complex and occupy a large amount of space.

Syntax of 2D Array in C
array_name[size1] [size2];

Here,
• size1: Size of the first dimension.
• size2: Size of the second dimension.

For Example :- 2D array of dimension 2 X 3.

int d[ 2 ] [ 3 ] ;

d[0][0] d[0][1] d[0][2]


d[1][0] d[1][1] d[1][2]
MULTIDIMENSIONAL ARRAY IN C
Program to fill in a 2D array with numbers 1 to 6 and to print it out row-wise.

#include <stdio.h>
void main( )
{
int i, j, num[2][3] ;

for ( i = 0; i < 2; i++ )


for ( j = 0; j < 3; j ++ )
num[i][j] = i * 3 + j + 1 ;

for ( i = 0; i < 2; i++ )


{
for ( j = 0; j < 3; j ++ )
printf("%d ",num[i][j] ) ;
printf("\n" );
}
} Output
123
456
MULTIDIMENSIONAL ARRAY IN C
Program to fill in a 2D array with numbers 1 to 6 and to print it out row-wise.

#include <stdio.h>
void main( )
{
int i, j, num[2][3] ;

for ( i = 0; i < 2; i++ )


for ( j = 0; j < 3; j ++ )
num[i][j] = i * 3 + j + 1 ;

for ( i = 0; i < 2; i++ )


{
for ( j = 0; j < 3; j ++ )
printf("%d ",num[i][j] ) ;
printf("\n" );
}
} Output
123
456
PASSING ARRAY TO FUNCTION IN C
In C, there are various general problems which requires passing more than one variable of the same type to a function.

For example, consider a function which sorts the 10 elements in ascending order. Such a function
requires 10 numbers to be passed as the actual parameters from the main function. Here, instead of
declaring 10 different numbers and then passing into the function, we can declare and initialize an
array and pass that into the function.

Consider the following syntax to pass an array to the function.

functionname(arrayname);//passing array
There are 3 ways to declare the function which is intended to receive an array as an argument.

return_type function(type arrayname[])


return_type function(type arrayname[SIZE])

return_type function(type *arrayname)


#include<stdio.h>
int main()
{
int a[6]= {12,5,10,9,7,6};
int temp; printf("\nAfter Sorting ");
int i, j; for(i=0; i<6; i++)
printf("Before Sorting "); {
for(i=0; i<6; i++) printf("%d ",a[i]);
{ }
printf("%d ",a[i]); return 0;
} }
for(i=0; i<6; i++)
{
for(j=i+1; j<6; j++) { if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}

You might also like