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

Computer Program

The document provides an overview of computer programs, types of programming languages, and the distinction between software and hardware. It covers key concepts such as algorithms, memory types (RAM and ROM), and the structure of a C program, including its history and advantages. Additionally, it explains data types, variable naming rules, operators, and expressions in C programming.

Uploaded by

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

Computer Program

The document provides an overview of computer programs, types of programming languages, and the distinction between software and hardware. It covers key concepts such as algorithms, memory types (RAM and ROM), and the structure of a C program, including its history and advantages. Additionally, it explains data types, variable naming rules, operators, and expressions in C programming.

Uploaded by

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

Chapter 1

Computer Program

To perform a specific task, a computer needs a set of instructions.


These instructions are called a computer program.
They are entered into the computer and stored in its memory.

Types of Computer Programs:

1. Source Program:
o The original program written in a high-level language.
o This is written by the programmer before compilation.
2. Object Program:
o The translated program in machine language after compilation.
o This is what the computer can directly understand and execute.

Languages

1. High-Level Language:
o Written in human-understandable form.
o Examples: C, Java, Python.
2. Machine Language:
o Written in binary (0s and 1s).
o Only the computer understands this language.
3. Assembly Language:
o Uses symbolic names or codes to represent instructions.
o Easier than machine language but harder than high-level languages.

Software vs Hardware

 Software:
o A set of instructions or programs that a computer executes.
o Example: Microsoft Word, AutoCAD.
 Hardware:
o The physical electronic components of a computer.
o Example: Monitor, CPU, keyboard.

Types of Software

1. Application Software:
o Used for specific tasks or applications.
o Example: Microsoft Excel, Photoshop.
2. System Software:
o Supports the basic functions of the computer.
o Provides a platform for running application software.
o Example: Operating System (Windows, Linux).

1
Compiler vs Interpreter

 Compiler:
o Translates the entire high-level program into machine language at once.
o Faster execution after compilation.
 Interpreter:
o Translates high-level language into machine language line by line.
o Slower, but useful for testing and debugging.

Algorithm and Flowchart

 Algorithm:
o A step-by-step procedure to solve a problem or complete a task.
 Flowchart:
o A graphical diagram of the steps in an algorithm.
o Helpful in planning and designing programs.

Bit and Byte

 Bit:
o The smallest unit of data in a computer.
o It can be either 0 or 1.
 Byte:
o A group of 8 bits.
o Represents a single character (letter, number, symbol).

Memory Size Units

 1 Byte = 8 bits
 1 KB (Kilobyte) = 1024 Bytes
 1 MB (Megabyte) = 1024 KB
 1 GB (Gigabyte) = 1024 MB
 1 TB (Terabyte) = 1024 GB
 1 PB (Petabyte) = 1024 TB

Basics of computers

RAM (Random Access Memory)

 RAM is a type of temporary (volatile) memory in a computer.


 It stores data that the computer is using right now.
 RAM needs electricity to keep the data—when power is off, data is lost.
 It is used by the operating system and programs during operation.
 Writing data to RAM is very fast.

In short: RAM is fast, temporary memory used while your computer is working.

ROM (Read-Only Memory)


2
 ROM is permanent (non-volatile) memory.
 It keeps data even when the computer is turned off.

 ROM holds firmware, such as startup instructions (BIOS).


 Data is fixed during manufacturing and hard to change.
 Slower than RAM, but needed to start the computer.

In short: ROM is permanent memory used to store essential startup instructions.

High-Level Language

 These languages are easy to learn and write.


 They are used to create software and applications.
 They are slow in execution compared to low-level languages.
 They don't give much control over hardware.

Examples:

 C
 C++
 Fortran
 Java
 Pascal
 Python

In short: High-level languages are user-friendly and used to make applications.

Low-Level Language

 These are hard to learn and write.


 Programs run faster than high-level ones.
 They are used to write hardware-level code.
 Not easy to change once written.

Examples:

 Machine Language
 Assembly Language

Types of Low-Level Languages:

1. Machine Language

 Written in binary (0s and 1s).


 Directly executed by the CPU.
 Very hard for humans to write or read.
 It is the only language the computer understands.

3
3. Assembly Language

 Uses symbolic names or codes to represent instructions.


 Easier than machine language but harder than high-level languages.
 Needs an assembler to convert into machine code.

Compiler vs Interpreter
Feature Compiler Interpreter
Input Translates the entire program at once Translates the program line by line
Execution speed Faster execution Slower execution
Memory requirement High Low
Error checking Shows all errors after compiling Stops and shows error immediately
Examples C, C++ (uses compiler) Python, JavaScript (uses interpreter)

CPU (Central Processing Unit)


 The brain of the computer.
 Performs calculations and processing.
 Executes instructions from programs.
 Controls other parts of the computer.

Debugging
 The process of finding and fixing errors (bugs) in a program or hardware.
 Steps in debugging:
1. Identify the problem.
2. Isolate the faulty part.
3. Fix the issue.

Basic Structure of a C Program


A C program is made up of several sections, each serving a specific purpose.

1. Documentation Section

 Includes comments about the program (name, author, purpose).

2. Link Section

 Tells the compiler which libraries to use.


#include<stdio.h> // for input/output
#include<math.h> // for math functions
#include<conio.h> // for console handling

3. Definition Section
4
 Defines constants using #define.

#define PI 3.14

4. Global Declaration Section

 Variables declared here can be used in any function.

int total;

5. Main Function

 The starting point of every C program.


 It has two parts:
o Declaration Part: Declares variables used in the program.
o Executable Part: The actual instructions (statements).
 Must be enclosed within { } (braces).

int main() {
int a, b; // declaration
a = 10; b = 5; // executable
printf("%d", a + b); // output
}
6. Subprogram Section

 Contains user-defined functions.


 These functions are created by the programmer to perform tasks.

void greet() {
printf("Hello!");
}

Functions can be written after or before the main function, but are usually placed after.

The Process of Compiling and Running of a C program

5
Chapter 2
History of C Language (Simplified)
 C is a general-purpose programming language used to create various types of software.
 It was developed by Dennis Ritchie between 1969 and 1973 at Bell Laboratories.
 C was originally created to write the UNIX operating system.
 It was later standardized by ANSI (American National Standards Institute), making it consistent across
platforms.
 Many modern programming languages have been influenced by C.

Examples of languages influenced by C:


Java, JavaScript, Python, PHP, C++, Objective-C, Limbo, LPC

Advantages of C Language
1. Compiler-based:
C is compiled, not interpreted. That means it runs faster than many other languages.
2. Portable:
C programs can be moved from one computer to another with little or no change.
3. Rich in Libraries:
C has a large number of built-in functions, which help in faster development.
4. Easy to Learn:
The basic concepts are simple and ideal for beginners.
5. Supports Graphics:
Can be used for basic graphic programming.
6. Variety of Operators:
Supports many types of operators, such as arithmetic, logical, and relational, making coding flexible.
6
Importance of Learning C for Building Engineers
1. Data Processing:
C helps engineers handle and process large datasets used in building design and analysis.
2. Hardware Control:
Useful for communicating with hardware devices such as sensors, controllers, or automation systems.
3. Career Opportunities:
Skills in C are useful in fields like building automation, energy systems, and smart technologies.
4. Problem-Solving Skills:
Learning C develops logical thinking, which is important for solving engineering problems.
5. Custom Tools:
Engineers can create their own simulation or analysis software.
6. Efficiency:
C makes fast, optimized programs that save energy and boost building system performance.

Character Set in C
The characters you can use to write a C program depend on the computer, but generally, the following types of
characters are used:

1. Letters

 Uppercase letters: A to Z
 Lowercase letters: a to z

2. Digits

 Numbers from 0 to 9

3. Special Characters

These are symbols used for various operations and syntax in C:

Character Symbol
Comma ,
Closing bracket ]
Period (dot) .
Number sign (hash) #
Semicolon ;
Vertical bar |
Colon :
Slash /
Question mark ?
Backslash \
Apostrophe '
Underscore _
7
Character Symbol
Exclamation mark !
Dollar sign $
Opening parenthesis (
Percent sign %
Closing parenthesis )
Asterisk *
Opening brace {
Closing brace }
Opening angle bracket <
Closing angle bracket >
Opening bracket [

4. White Spaces

 Blank spaces (spacebar)


 Horizontal tab
 New line (Enter key)

C-Tokens
 The smallest meaningful parts of a C program are called C-tokens.
 Tokens are the basic building blocks used to write a program.
 Types of C-tokens include:
Keywords, Identifiers, Constants, Strings, Special Symbols, Operators

1. Keywords

 Keywords are reserved words in C with special meanings.


 You cannot use keywords as names for variables or functions.
 In ANSI C, there are 47 keywords; in C++, there are 63 keywords.

Examples in C:
int, char, auto, break, do, while, if, printf, scanf

2. Identifiers

 Identifiers are names given to variables, functions, arrays, pointers, classes, or objects.
 Variables are also identifiers because they are names used to store values in memory.
 Identifiers are created by the programmer.

Examples:
i, j, k, abc, totalSum

3. Constants

 Constants are fixed values that do not change during program execution.
8
 Types of constants:
o Integer Constants: Whole numbers without decimals.
Examples: +13, -12, 11
o Real (Floating Point) Constants: Numbers with decimals.
Examples: 0.003, 2.47, 1.0e-4 (scientific notation)

4. Strings

 Strings are sequences of characters enclosed in quotes.

Types of character constants:

 Single character constant: Only one character enclosed in single quotes.


Examples: 'a', 'i'
 String constant: Multiple characters enclosed in double quotes.
Examples: "moment", "shear"
 Backslash character constants: Special escape sequences used in output to format text.

Backslash Sequence Meaning


\n New line
\b Backspace
\t Horizontal tab
\v Vertical tab

Variables
 A variable is a name (identifier) used to store data in a program.
 Unlike constants, the value of a variable can change during program execution.
 Variables represent a memory location where data is stored.
 Every variable must have a data type that tells the kind of data it will store.
 Declaring a variable means specifying its data type and giving it a name.

Variable Declaration Format:


datatype variable_name;

Examples:
int i, j, k; // variables that store integers
float x, y; // variables that store decimal numbers
double shear; // variable that stores double precision decimal number

Rules for Naming Variables


1. Must start with a letter (a–z or A–Z).
2. Can contain letters, digits (0–9), and underscore (_) only.
3. No spaces allowed in variable names.

9
4. Cannot use keywords (reserved words) as variable names.
5. Case sensitive: Variable and variable are different.
6. Length is normally 8 characters, but up to 31 characters allowed.

Data Types in C
There are three main categories of data types:

1. Built-in Data Types: Provided by C language


Examples:
o int (integer)
o char (character)
o float (single precision decimal)
o double (double precision decimal)
2. User-Defined Data Types: Created by the programmer
Examples:
o struct (structure)
o union
o (in C++)
class
3. Derived Data Types: Built from other types
Examples:
o array
o function
o pointer

Integer Type
 Integers are whole numbers without fractions or decimals.
 The range of integers depends on the machine and word size.
 Typically, integer values range from -32768 to +32767 (for 16-bit machines).
 Integers usually occupy one word of storage in memory.
 Larger machines may support larger integer ranges.

Floating Point Type


 Floating point numbers are used to represent decimal numbers (numbers with fractions).
 They are stored using 32 bits (4 bytes) in memory.
 Floating point numbers provide about 6 digits of precision, meaning they can accurately represent
numbers with up to 6 significant digits.
 Example of floating point numbers: 3.14159, 0.00025, -12.345

Void Types
 The void type means no value.
 It is commonly used to specify that a function does not return any value.
 When a function’s return type is void, it performs its task but does not send any result back to where it
was called from.

10
Example:

c
CopyEdit
void displayMessage() {
printf("Hello, World!");
}

This function prints a message but returns nothing.

Character Types
 The char type is used to store a single character.
 Characters usually take 8 bits (1 byte) of memory.
 A character is enclosed in single quotes ' '.

Examples:

char letter = 'A'; // Stores the character 'A'


char digit = '5'; // Stores the character '5', not the number 5
char symbol = '!'; // Stores the symbol '!'

Operators and Expressions (Easy Explanation)

An operator is a symbol that tells the computer to do a specific task like a calculation or decision-making. It
works on data or variables, and these data are called operands. For example, in a + b, the + is the operator,
and a and b are operands.

Types of Operators

Operators are mainly divided into Unary and Binary types.

1. Unary Operator

Unary operators work with only one operand.


Examples:

 +x means the value is positive


 -x means the value is negative
 x++ or ++x increases the value of x by 1
 x-- or --x decreases the value of x by 1

These are often used to increase or decrease a number by 1 or to show positive/negative value.

2. Binary Operator

Binary operators work with two operands. There are several types:

11
(a) Arithmetic Operators

These are used for basic mathematical calculations like:

 + for addition (A + B)
 - for subtraction (A - B)
 * for multiplication (A * B)
 / for division (A / B)
 % for remainder/modulus (A % B)

(b) Relational Operators

Used to compare values. These give either true or false.

 > means greater than


 < means less than
 >= means greater than or equal to
 <= means less than or equal to
 == means equal to
 != means not equal to

Example: A > B checks if A is greater than B.

(c) Logical Operators

Used when we want to check more than one condition at once.

 && means AND (both conditions must be true)


 || means OR (at least one condition must be true)
 ! means NOT (reverses the result)

Example: A > B && A > C is true only if A is greater than both B and C.

(d) Assignment Operators

Used to store a value into a variable.

 = assigns value (A = 10 means 10 is stored in A)


 += adds and stores (A += 5 means A = A + 5)
 -= subtracts and stores
 *= multiplies and stores
 /= divides and stores
 %= modulus and stores

These make calculations and assignments shorter.

(e) Conditional Operator

Also called the ternary operator, it is used to make decisions in one line.

12
Format: condition ? true_result : false_result

Example: 17 > 7 ? a : b
Here, if 17 is greater than 7 (which is true), then it returns the value of a, otherwise it returns b.

Algebraic Expressions and Their C Programming Equivalents

Algebraic Equation C Expression


y = 2x + 4 y = 2 * x + 4
ax / rz a * x / (r * z)
y = sin(x) y = sin(x)
y = cos(x) y = cos(x)
y = tan(x) y = tan(x)
y = sin⁻¹x (inverse sine) y = asin(x)
y = cos⁻¹x (inverse cosine) y = acos(x)
y = tan⁻¹x (inverse tan) y = atan(x)
y = eˣ y = exp(x)
y= x
y = log x y = log(x) (natural log)
y = log₁₀ x y = log10(x)
y = √x y = sqrt(x)
z = xʸ z = pow(x, y)
x roundup ceil(x)
x round down floor(x)

Chapter 3
C Programs and Decision Making
A C program is a set of instructions executed one after another in the order they appear. This works fine when
no special conditions or repeated calculations are needed.
However, sometimes we need to change the order of execution based on certain conditions. This is called
decision making, where the program checks whether a condition is true or false and then decides what to do
next.
These types of statements are called decision-making statements or control statements, because they control
the flow of the program.
Types of decision-making statements in C:
1. if statements
2. switch
3. Conditional operator (?:)

13
4. goto
Decision Making with if Statements
The if statement is a powerful decision-making tool. It evaluates a test expression (true or false) and then
decides which path the program should follow:
 True path: Executes statements when the condition is true.
 False path: Executes statements when the condition is false (if else is used).
General Form of if Statement:
if (test_expression) {
statement-block ;
}
statement-x;
Types of if Statements
1. Simple if statement
2. if...else statement
3. Nested if...else statement
4. else if ladder
1. Simple if Statement
 Executes a block of statements only if the condition is true.
 If the condition is false, the block is skipped.
Example:
#include<stdio.h>
int main() {
float a,b,c,d,A,B,ratio;
printf("Enter the value of a, b, c, d: ");
scanf("%f %f %f %f", &a, &b, &c, &d);

A = a + b;
B = c - d;

14
if(B != 0) {
ratio = A / B;
printf("The ratio is = %f", ratio);
}

return 0;
}
 Here, the ratio is calculated only if B is not zero.
2. if...else Statement
 Used when there are two possible paths: one if the condition is true, another if it is false.
 It is also called two-way conditional branching.
General Form:
if (test_condition) {
True block statements;
} else {
False block statements;
}
statement-x;
Example:
#include<stdio.h>
int main() {
float a,b,c,d,A,B,ratio;
printf("Enter the value of a, b, c, d: ");
scanf("%f %f %f %f", &a, &b, &c, &d);

A = a + b;
B = c - d;

if(B != 0) {
15
ratio = A / B;
printf("The ratio is = %f", ratio);
} else {
printf("The value of (c-d) is zero");
}

return 0;
}
 If B is zero, the program does not calculate the ratio but shows a message instead.

3. Nested if...else Statement


 A nested if...else is when an if...else statement is used inside another if...else.
 It is useful when multiple conditions need to be tested.
General Form:
if (condition1) {
if (condition2) {
// statement-block executed if both conditions are true
} else {
// executed if condition1 is true but condition2 is false
}
} else {
// executed if condition1 is false
}
statement-x; // executed in all cases
Example: Find the largest of three numbers
#include<stdio.h>
int main() {
int A, B, C;
printf("Enter the value of A, B, C: ");
16
scanf("%d%d%d", &A, &B, &C);

if(A > B) {
if(A > C)
printf("The largest number is A");
else
printf("The largest number is C");
} else {
if(B > C)
printf("The largest number is B");
else
printf("The largest number is C");
}

return 0;
}
 Here, we compare numbers step by step to find the largest.

4. else if Ladder
 The else if ladder tests conditions one by one from top to bottom.
 The first true condition executes its block, and the rest are skipped.
General Form:
if(condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
...
17
else
default statement;
statement-x; // executed in all cases
Example: Grading system
#include<stdio.h>
int main() {
int marks;
printf("Enter the value of marks: ");
scanf("%d", &marks);

if(marks > 79)


printf("Honors");
else if(marks > 59)
printf("First Division");
else if(marks > 49)
printf("Second Division");
else if(marks > 39)
printf("Third Division");
else
printf("Fail");

return 0;
}
 Here, marks are checked in order, and only the matching grade is printed.
5. switch Statement
 The switch statement compares a variable or expression with a list of case values.
 When a match is found, the corresponding block of statements is executed.
 The break statement ends that case and prevents the next cases from running.
General Form:
18
switch(expression) {
case value1:
block1;
break;
case value2:
block2;
break;
...
default:
default block;
break;
}
statement-x; // executed in all cases
Example: Print a character based on a number
#include<stdio.h>
int main() {
int num = 1;

switch(num) {
case 1:
printf("A");
break;
case 2:
printf("B");
break;
case 3:
printf("C");
break;
default:
19
printf("D");
}

return 0;
}
 Here, since num = 1, only case 1 is executed, printing A.

✅ Summary of Decision-Making Statements in C

Statement Use Notes

if Execute block if condition is true Simple decision

if...else Two paths: true/false Two-way branching

Nested if...else Test multiple conditions If inside another if

else if ladder Multiple conditions in sequence First true condition executes

switch Compare variable to fixed values Use break to exit each case

6. Conditional Operator (?:)


 The conditional operator is a shortcut for if...else when you have a simple two-way decision.
 It uses the symbols ? and : to decide which statement to execute.
General Form:
condition ? true_statement : false_statement;
Example:
int x = -5;
int flag;

flag = (x < 0) ? 0 : 1;
 Here, if x is less than 0, flag becomes 0; otherwise, it becomes 1.
 It’s shorter and simpler than using a full if...else.

7. goto Statement

20
 The goto statement is used to jump directly to another part of the program marked by a label.
 It is rarely used because it can make programs confusing and hard to read.
General Form:
goto label_name;

...

label_name:
statement-block;
Example:
#include<stdio.h>
int main() {
int x = 5;

if(x == 5) {
goto skip;
}

printf("This will be skipped\n");

skip:
printf("Program jumped to this line using goto\n");

return 0;
}
 When goto skip; is executed, the program jumps directly to the skip label, skipping other statements.

✅ Summary of Conditional and Goto Statements

21
Statement Use Notes

Conditional (?:) Short two-way decision Replacement for simple if...else

goto Jump to a labeled statement Rarely used; can make code confusing

Chapter 4
Decision Making & Looping

Looping in C
A loop is a set of instructions that repeats until a specific condition is met. Loops are useful when we want to
perform a task multiple times.
Parts of a Loop
1. Body of the loop: The statements that are executed repeatedly.
2. Control statement: The condition that decides whether the loop will run or stop.
Types of Loops by Control Position
1. Entry Control Loop
 The condition is checked first, before executing the body.
 If the condition is true, the loop runs.
 If the condition is false, the loop never runs.
 Example: while loop, for loop
2. Exit Control Loop
 The body executes first, then the condition is checked.
 Even if the condition is false initially, the body executes at least once.
 Example: do...while loop

Looping Process
Every loop generally follows these steps:
1. Initialization: Set the starting value.
2. Condition check: Test whether the loop should run.
3. Execution: Run the statements in the loop body.

22
4. Increment/Decrement: Update variables to eventually stop the loop.
Types of Loops in C

1. The while Loop


 The while loop is an entry-controlled loop.
 The condition is checked before each iteration.
 The body executes repeatedly as long as the condition is true.
Syntax:
while (condition) {
// body of the loop
}
Example:
#include <stdio.h>

int main() {
int a = 5;

while(a <= 10) {


printf("Value of a: %d\n", a);
a++; // increment a
}

return 0;
}
 Output:
Value of a: 5
Value of a: 6
Value of a: 7
Value of a: 8
23
Value of a: 9
Value of a: 10
 The loop runs as long as a <= 10.
2. The do...while Loop
 The do...while loop is an exit-controlled loop.
 The body executes first, then the condition is checked.
 Useful when you want the loop to run at least once, even if the condition is initially false.
Syntax:
do {
// body of the loop
} while (condition);
Example:
#include <stdio.h>
int main() {
int a = 11;

do {
printf("Value of a: %d\n", a);
a++;
} while(a <= 10);

return 0;
}
 Output:
Value of a: 11
 Even though a > 10 initially, the loop runs once before checking the condition.

3. The for Loop


 The for loop is an entry-controlled loop.
24
 It combines initialization, condition check, and increment/decrement in one line.
 Ideal for loops where the number of iterations is known.
Syntax:
for(initialization; condition; increment/decrement) {
// body of the loop
}
Example:
#include <stdio.h>
int main() {
for(int a = 5; a <= 10; a++) {
printf("Value of a: %d\n", a);
}
return 0;
}
 Output:
Value of a: 5
Value of a: 6
Value of a: 7
Value of a: 8
Value of a: 9
Value of a: 10

4. Nesting of Loops
 Nesting means placing one loop inside another loop.
 Any type of loop (for, while, do...while) can be nested.
 The inner loop runs completely for each iteration of the outer loop.
Example:
for(int i = 5; i < 20; i++) {
for(int j = 5; j < 20; j++) {
25
// inner loop statements
}
// outer loop statements
}
 Here, for each value of i (5 to 19), the inner loop runs completely for j = 5 to 19.

✅ Summary of Loops in C

Loop Type Control Runs at least once? Syntax Notes

while Entry No Condition checked before execution

do...while Exit Yes Body executes first, condition checked later

for Entry No Initialization, condition, increment in one line

Nested loops Any Depends on outer/inner loops Inner loop completes for each outer loop iteration

Jump Statements in C
Sometimes, while executing a loop, we need to skip certain statements or exit the loop early. This is called
jumping out of a loop.
C provides three types of jump statements:
1. break
2. continue
3. goto
1. break Statement
 The break statement immediately exits the loop.
 The program then continues with the statement after the loop.
Example:
#include <stdio.h>
int main() {
for(int i = 1; i <= 10; i++) {
if(i == 5) {
break; // exit loop when i is 5
26
}
printf("%d\n", i);
}
return 0;
}
 Output:
1
2
3
4
 The loop stops when i == 5.

2. continue Statement
 The continue statement skips the rest of the loop body and goes directly to the next iteration.
 Often used with a condition inside the loop.
Example:
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
if(i == 3) {
continue; // skip printing 3
}
printf("%d\n", i);
}
return 0;
}
 Output:
1
2
27
4
5
 The value 3 is skipped.
⚠ Note: continue must be inside a loop (for, while, do...while), otherwise it may cause an infinite loop.

3. goto Statement
 The goto statement jumps unconditionally to a labeled statement in the same function.
 Labels are identifiers (not keywords) placed anywhere in the function.
Example:
#include <stdio.h>
int main() {
int x = 1;

goto skip; // jump to label skip

printf("This will be skipped\n");

skip:
printf("Jumped to this line using goto\n");

return 0;
}
 Output:
Jumped to this line using goto
⚠ Warning: Using goto is not recommended because it can make programs confusing and hard to modify.

✅ Summary of Jump Statements

Statement Use Notes

break Exit the loop immediately Works with for, while, do...while, switch
28
Statement Use Notes

continue Skip current iteration and go to next Must be inside a loop; needs a condition

goto Jump to a labeled statement Makes code hard to read; use sparingly

Chapter 5
ARRAYS IN C
An array is a collection of variables of the same data type stored under a single name.
Arrays are useful when we want to store multiple values without declaring separate variables.
Types of Arrays
1. One-dimensional array (1D): Single row of elements.
2. Two-dimensional array (2D): Matrix or table of elements.
3. Multi-dimensional array: More than two dimensions (e.g., 3D arrays).

1. One-Dimensional Array
 Basic format:
datatype ArrayName[N];
 Example:
int m[4];
float shear[4];
 Assigning values:
1. At declaration:
int a[5] = {10, 20, 30, 40, 50};
2. After declaration:
a[0] = 10;
a[1] = 20;
3. During program execution:
for(i = 0; i < 100; i++) {
if(i < 50)
29
sum[i] = 0.0;
else
sum[i] = 1.0;
}
Example: Input and print 5 numbers
#include <stdio.h>
int main() {
int i, a[5];
for(i = 0; i < 5; i++)
scanf("%d", &a[i]);

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


printf("%d\t", a[i]);

return 0;
}

2. Two-Dimensional Array
 Used to store data in a matrix form (rows × columns).
 Basic format:
datatype ArrayName[row_size][column_size];
 Example:
int a[3][4];
 Initialization methods:
1. Direct initialization:
int shear[2][2] = {{1,2},{2,3}};
int shear[2][2] = {0}; // all elements = 0
2. During program execution:
#include <stdio.h>
30
int main() {
int arr[3][3], i, j;
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++) {
printf("Enter arr[%d][%d]: ", i, j);
scanf("%d", &arr[i][j]);
}
}

printf("\nPrinting the elements:\n");


for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++)
printf("%d\t", arr[i][j]);
printf("\n");
}
return 0;
}

Matrix Operations with 2D Arrays


1. Adding two matrices:
#include <stdio.h>
int main() {
int a[2][2], b[2][2], c[2][2], i, j;

printf("Enter matrix A:\n");


for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
scanf("%d", &a[i][j]);

31
printf("Enter matrix B:\n");
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
scanf("%d", &b[i][j]);

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


for(j = 0; j < 2; j++)
c[i][j] = a[i][j] + b[i][j];

printf("Sum of matrices C:\n");


for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++)
printf("%d\t", c[i][j]);
printf("\n");
}

return 0;
}
2. Matrix multiplication (with dimension check):
#include <stdio.h>
int main() {
int i, j, k, m, n, o, p, sum;
printf("Enter rows and columns of first matrix: ");
scanf("%d%d", &m, &n);
printf("Enter rows and columns of second matrix: ");
scanf("%d%d", &o, &p);

if(n != o) {
printf("Matrix multiplication not possible!\n");
32
return 0;
}

int a[m][n], b[o][p], c[m][p];

printf("Enter matrix A:\n");


for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
scanf("%d", &a[i][j]);

printf("Enter matrix B:\n");


for(i = 0; i < o; i++)
for(j = 0; j < p; j++)
scanf("%d", &b[i][j]);

// Multiplication
for(i = 0; i < m; i++) {
for(j = 0; j < p; j++) {
c[i][j] = 0;
for(k = 0; k < n; k++)
c[i][j] += a[i][k] * b[k][j];
}
}

printf("Result matrix C:\n");


for(i = 0; i < m; i++) {
for(j = 0; j < p; j++)
printf("%d\t", c[i][j]);
printf("\n");
33
}

return 0;
}

✅ Summary of Arrays

Type Description Example

1D Array Single row of elements int a[5];

2D Array Matrix (rows × columns) int a[3][4];

Multi-D Array More than 2 dimensions int a[2][3][4];

 Assigning values:
1. At declaration
2. After declaration
3. During program execution
 Operations: Input/output, addition, multiplication, etc.

1. Matrix Multiplication Program (C)


This program:
1. Checks if matrix multiplication is possible.
2. Scans and prints matrices A and B.
3. Computes and displays the resulting matrix C.
Key steps:
1. Initialize matrix C to zero.
2. Multiply matrices using three nested loops (row × column).
3. Print matrix C.
Example Code:
#include <stdio.h>
int main() {
int i, j, k, m, n, o, p, sum;
34
printf("Enter rows and columns of first matrix: ");
scanf("%d%d", &m, &n);
printf("Enter rows and columns of second matrix: ");
scanf("%d%d", &o, &p);

if(n != o) {
printf("Matrix multiplication not possible!\n");
return 0;
}

int a[m][n], b[o][p], c[m][p];

printf("Enter matrix A:\n");


for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
scanf("%d", &a[i][j]);

printf("Enter matrix B:\n");


for(i = 0; i < o; i++)
for(j = 0; j < p; j++)
scanf("%d", &b[i][j]);

// Initialize matrix C
for(i = 0; i < m; i++)
for(j = 0; j < p; j++)
c[i][j] = 0;

// Matrix multiplication
35
for(i = 0; i < m; i++) {
for(j = 0; j < p; j++) {
sum = 0;
for(k = 0; k < n; k++)
sum += a[i][k] * b[k][j];
c[i][j] = sum;
}
}

// Print matrix C
printf("The New Matrix C is:\n");
for(i = 0; i < m; i++) {
for(j = 0; j < p; j++)
printf("%d\t", c[i][j]);
printf("\n");
}

return 0;
}

2. Multi-Dimensional Array
 Format:
datatype ArrayName[Size1][Size2]...[SizeN];
 Example:
int shear[3][3]; // 3×3 matrix → 9 elements
 Elements are accessed as:
shear[0][0], shear[0][1], shear[0][2]
shear[1][0], shear[1][1], shear[1][2]
shear[2][0], shear[2][1], shear[2][2]
36
3. Shear, Moment, and Stress Calculation
This program calculates shear force, bending moment, shearing stress, and flexural stress at intervals along
a beam.
Key steps:
1. Input values: load p, uniform load w, length L, width b, height h.
2. Compute moment of inertia I, centroid c, and section modulus Q.
3. Loop over the beam from x = 0 to x = L in steps of L/10.
4. Calculate:
o Shear force v = p + w*x

o Moment m = p*x + w*x*x/2

o Shearing stress ss = (v*Q)/(I*b)

o Flexural stress sf = (m*c)/I

5. Print results at each step.


Example Code:
#include <stdio.h>
#include <math.h>

int main() {
float p, w, L, b, h, c, I, Q;

printf("Enter p, w, L, b, h: ");
scanf("%f%f%f%f%f", &p, &w, &L, &b, &h);

c = h / 2.0;
I = b * pow(h, 3) / 12.0;
Q = b * 8 * h * h / 8.0; // Section modulus (example formula)

printf("\nResults at each L/10 interval:\n");

37
for(float x = 0.0; x <= L; x += L/10.0) {
float v = p + w*x;
float m = p*x + w*x*x / 2.0;
float ss = (v * Q) / (I * b);
float sf = (m * c) / I;

printf("x = %.2f: Shear = %.2f, Moment = %.2f, Shear Stress = %.2f, Flexural Stress = %.2f\n",
x, v, m, ss, sf);
}

return 0;
}

✅ Summary

Concept Description

Multi-dimensional array Array with 2 or more dimensions, e.g., matrix

Matrix multiplication Uses three nested loops (i, j, k)

Shear & Moment program Computes structural properties along beam using formulas and loops

38

You might also like