Computer Programming
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
• 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
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.)
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
Input/output Symbol: The symbol given below is used for representing the Input/output symbol.
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.
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.
• 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
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.
For Example :-
int i,j ;
#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.)
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 ;
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.
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.
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);
•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.
•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.
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.)
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;
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(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;
test condition
FALSE #include <stdio.h>
1 12345
12 1234
123 123
1234 12
12345 1
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
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.
This declaration simply informs the compiler what type the function returns and what type and how
many parameters it takes.
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.
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.
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.
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.
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);
#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.
Types of 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)
def print_numbers(*args):
for number in args:
print(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];
The size of the above arrays is 5 which is automatically deduced by the compiler.
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()
{
int arr1[] = { 1, 2, 3, 4, 5 };
float arr2[5];
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 };
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
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.
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
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 */
Syntax of 2D Array in C
array_name[size1] [size2];
Here,
• size1: Size of the first dimension.
• size2: Size of the second dimension.
int d[ 2 ] [ 3 ] ;
#include <stdio.h>
void main( )
{
int i, j, num[2][3] ;
#include <stdio.h>
void main( )
{
int i, j, num[2][3] ;
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.
functionname(arrayname);//passing array
There are 3 ways to declare the function which is intended to receive an array as an argument.