SlideShare a Scribd company logo
1 of 38
Download to read offline
• Used to execute a set of operations multiple times, with one loop
inside another.
• It allows for iterating over multidimensional data structures,
among other use cases.
• The outer loop completes one full iteration for each single
iteration of the inner loop, creating a loop within a loop.
Nested Loops
for (initialization; condition; increment) {
// Outer loop body
for (initialization; condition; increment) {
// Inner loop body
// Code to be executed for each iteration of the
inner loop
}
// Additional code can be executed in the outer
loop
}
Structure of Nested Loops
#include <iostream>
using namespace std;
int main() {
for(int i = 1; i <= 10; i++) { // Outer loop
for(int j = 1; j <= 10; j++) { // Inner loop
cout << i*j << "t"; // Multiply i and j, separated by a
tab
}
cout << endl;
}
return 0;
}
Multiplication table up to 10 using nested loops.
#include <iostream>
using namespace std;
int main() {
for(int i = 0; i < 5; i++) { // Outer loop for rows
for(int j = 0; j < 5; j++) { // Inner loop for columns
cout << "* ";
}
cout << endl; // Move to the next line after each row
}
return 0;
}
Drawing a square pattern
• Arrays in C++ provide a way to store a collection of variables of the
same type.
• An array can be declared by specifying the type of its elements,
followed by the array name and the number of elements it will hold
inside square brackets.
int numbers [5]
Arrays
#include <iostream>
using namespace std;
int main() {
// Declare and initialize an array of integers with 5 elements
int numbers[5] = {10, 20, 30, 40, 50};
// Access and print each element of the array
for(int i = 0; i < 5; i++) {
cout << "Element at index " << i << ": " << numbers[i] << endl;
}
return 0;
}
An integer array named numbers with 5 elements
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
int sum = 0;
// Calculate sum of array elements
for(int i = 0; i < 5; i++) {
sum += numbers[i];
}
cout << "Sum of array elements: " << sum << endl;
return 0;
}
Calculating the sum of Array elements
#include <iostream>
using namespace std;
int main() {
int matrix[2][2] = {
{1, 2}, // First row
{3, 4} // Second row
};
// Access and print each element of the matrix
// Outer loop for rows
for(int i = 0; i < 2; i++) {
2x2 matrix using array
2x2 matrix using array (contnd)
// Inner loop for columns
for(int j = 0; j < 2; j++) {
cout << "Element at (" << i << ", " << j << "): " << matrix[i][j] << endl;
}
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
// Declare and initialize two 2x2 matrices
int matrixA[2][2] = {{1, 2}, {3, 4}};
int matrixB[2][2] = {{5, 6}, {7, 8}};
int sumMatrix[2][2]; // To store the sum of the matrices
// Calculate the sum of the matrices
for(int i = 0; i < 2; i++) { // Loop over rows
for(int j = 0; j < 2; j++) { // Loop over columns
Calculating the sum of matrices
sumMatrix[i][j] = matrixA[i][j] + matrixB[i][j];
}
}
cout << "Sum of Matrix A and Matrix B is:" << endl;
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
cout << sumMatrix[i][j] << " ";
}
cout << endl; // New line for each row
}
return 0;
}
Calculating the sum of matrices (continued)
Program to Input and Display Array Elements
#include <iostream>
using namespace std;
int main() {
int arr[5]; // Declaring an array of size 5
// Input array elements
cout << "Enter 5 integers:" << endl;
for(int i = 0; i < 5; i++) {
cin >> arr[i];
Program to Input and Display Array Elements (contnd)
}
// Display array elements
cout << "Array elements are:" << endl;
for(int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
return 0;
}
Program to Calculate the Sum and Average of Array Elements
#include <iostream>
using namespace std;
int main() {
int n, sum 0;
float average;
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements:" << endl;
contnd
for(int i = 0; i < n; i++) {
cin >> arr[i];
sum += arr[i]; // Adding elements to sum
}
average = sum / n; // Calculating average
cout << "Sum of array elements is: " << sum << endl;
cout << "Average of array elements is: " << average << endl;
return 0;
}
Program to Find the Largest Element in an Array
#include <iostream>
using namespace std;
int main() {
int n, max;
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array:" << endl;
for(int i = 0; i < n; i++) {
contnd
cin >> arr[i];
}
max = arr[0];
for(int i = 1; i < n; i++) {
if(arr[i] > max)
max = arr[i];
}
cout << “Largest element in the array is: " << max << endl;
return 0;
}
Inputs Elements Of A Matrix Then Displays In Matrix Format
#include <iostream>
using namespace std;
int main() {
int rows, cols;
// Prompt user for the dimensions of the matrix
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter number of columns: ";
cin >> cols;
contnd
// Create a 2D array (matrix) based on the input dimensions
int matrix[rows][cols];
cout << "Enter elements of the matrix:" << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cin >> matrix[i][j];
}
}
contnd
// Display the matrix in matrix format
cout << "The matrix is:" << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cout << matrix[i][j] << " ";
}
cout << endl; // Move to the next line after printing each
row
}
return 0;
}
Sum of Matrix
#include <iostream>
using namespace std;
int main() {
int rows, cols;
// Prompt for matrix size
cout << "Enter the number of rows and columns for the
matrices: ";
cin >> rows >> cols;
int matrix1[rows][cols], matrix2[rows][cols],
sum[rows][cols];
// Input elements for the first matrix
Sum of Matrix (contnd)
cout << "Enter elements of the first matrix:" << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cin >> matrix1[i][j];
}
}
// Input elements for the second matrix
cout << "Enter elements of the second matrix:" << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cin >> matrix2[i][j];
}
}
Sum of Matrix (contnd)
// Calculate the sum of the two matrices
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Display the resulting matrix
cout << "Sum of the two matrices:" << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cout << sum[i][j] << " ";
} cout << endl;
}
return 0;
}
Functions
• Functions are blocks of code designed to perform a specific task.
• Used to structure programs into segments.
Declaration and Definition
• Declaration: Tells the compiler about a function's name, return type,
and parameters (if any). It's also known as a function prototype.
• Definition: Contains the actual body of the function, detailing the
statements that execute when the function is called.
Syntax
return_type function_name(parameter list) {
// function body
}
Syntax
• 'return_type ': The data type of the value the function returns.
'function_name': The name of the function, following the rules for identifiers.
• 'parameter list': A comma-separated list of input parameters that are passed
into the function, each specified with a type and name. If the function takes no
parameters, this can be left empty or explicitly defined with 'void'.
Add function
#include <iostream>
using namespace std;
// Function declaration
int add(int, int);
int main() {
int result;
// Function call
result = add(5, 3);
cout << "The sum is: " << result << endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Find the Maximum of Two Numbers
#include <iostream>
using namespace std;
// Function to find the maximum of two numbers
int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;
cout << "The maximum is: " << max(a, b);
return 0;
}
#include <iostream>
using namespace std;
float PI = 3.14159; // Use float for PI
// Function to calculate the area of a circle
float calculateArea(float radius) {
return PI * radius * radius;
}
Area of a Circle
int main() {
float radius;
cout << "Enter the radius of the circle: ";
cin >> radius;
float area = calculateArea(radius); // Change type to float
cout << "The area of the circle is: " << area;
return 0;
}
Area of a Circle (contd)
#include <iostream>
using namespace std;
// Function to check even or odd
int isEven(int number) {
return (number % 2 == 0); // This still returns 1 (true) for even and 0 (false) for
odd
}
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
Number is even or odd
if (isEven(num))
cout << num << " is even.";
else
cout << num << " is odd.";
return 0;
}
Number is even or odd (contd)
cin >> num;
if (num < 0) {
cout << "Factorial of a negative number doesn't exist.";
} else {
long long result = factorial(num);
cout << "The factorial of " << num << " is: " << result << endl;
}
return 0;
}
Factorial
#include <iostream>
using namespace std;
// Function to add two numbers
int add(int num1, int num2) {
return num1 + num2;
}
int main() {
int a, b;
cout << "Enter first number: ";
cin >> a;
cout << "Enter second number: ";
Add function
cin >> b;
int sum = add(a, b); // Call the add function
cout << "The sum is: " << sum << endl;
return 0;
}
Add function (contnd)
#include <iostream>
using namespace std;
// Function to check if a number is even or odd
int isEven(int num) {
return (num % 2 == 0);
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (isEven(num)) {
Check Even or Odd Using a Function
cout << num << " is even." << endl;
} else {
cout << num << " is odd." << endl;
}
return 0;
}
Check Even or Odd Using a Function (contnd)

More Related Content

Similar to C++ Nested loops, matrix and fuctions.pdf

I have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfI have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfshreeaadithyaacellso
 
Modify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdfModify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdfmallik3000
 
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxJumanneChiyanda
 
how to reuse code
how to reuse codehow to reuse code
how to reuse codejleed1
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2Mouna Guru
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - ReferenceMohammed Sikander
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++NUST Stuff
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingMeghaj Mallick
 
Pointers in c++ programming presentation
Pointers in c++ programming presentationPointers in c++ programming presentation
Pointers in c++ programming presentationSourabhGour9
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfHIMANSUKUMAR12
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++NUST Stuff
 
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdfWrite the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdfarihantmum
 

Similar to C++ Nested loops, matrix and fuctions.pdf (20)

I have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdfI have written the code but cannot complete the assignment please help.pdf
I have written the code but cannot complete the assignment please help.pdf
 
Modify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdfModify this code to use multiple threads with the same data1.Modif.pdf
Modify this code to use multiple threads with the same data1.Modif.pdf
 
Array and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptxArray and string in C++_093547 analysis.pptx
Array and string in C++_093547 analysis.pptx
 
how to reuse code
how to reuse codehow to reuse code
how to reuse code
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Oops lab manual2
Oops lab manual2Oops lab manual2
Oops lab manual2
 
Lab 13
Lab 13Lab 13
Lab 13
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++
 
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
Chapter1.pptx
Chapter1.pptxChapter1.pptx
Chapter1.pptx
 
Pointers in c++ programming presentation
Pointers in c++ programming presentationPointers in c++ programming presentation
Pointers in c++ programming presentation
 
Computer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdfComputer_Practicals-file.doc.pdf
Computer_Practicals-file.doc.pdf
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
 
C++ TUTORIAL 3
C++ TUTORIAL 3C++ TUTORIAL 3
C++ TUTORIAL 3
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
 
Lecture2.ppt
Lecture2.pptLecture2.ppt
Lecture2.ppt
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdfWrite the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
Write the code above and the ones below in netbeans IDE 8.13. (Eli.pdf
 

Recently uploaded

FREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naFREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naJASISJULIANOELYNV
 
Solution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutionsSolution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutionsHajira Mahmood
 
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)Columbia Weather Systems
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPirithiRaju
 
preservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptxpreservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptxnoordubaliya2003
 
User Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather StationUser Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather StationColumbia Weather Systems
 
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)riyaescorts54
 
Scheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxScheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxyaramohamed343013
 
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxLIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxmalonesandreagweneth
 
Pests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdfPests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdfPirithiRaju
 
Transposable elements in prokaryotes.ppt
Transposable elements in prokaryotes.pptTransposable elements in prokaryotes.ppt
Transposable elements in prokaryotes.pptArshadWarsi13
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxNandakishor Bhaurao Deshmukh
 
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxMicrophone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxpriyankatabhane
 
Environmental Biotechnology Topic:- Microbial Biosensor
Environmental Biotechnology Topic:- Microbial BiosensorEnvironmental Biotechnology Topic:- Microbial Biosensor
Environmental Biotechnology Topic:- Microbial Biosensorsonawaneprad
 
User Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather StationUser Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather StationColumbia Weather Systems
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRlizamodels9
 
TOPIC 8 Temperature and Heat.pdf physics
TOPIC 8 Temperature and Heat.pdf physicsTOPIC 8 Temperature and Heat.pdf physics
TOPIC 8 Temperature and Heat.pdf physicsssuserddc89b
 
Topic 9- General Principles of International Law.pptx
Topic 9- General Principles of International Law.pptxTopic 9- General Principles of International Law.pptx
Topic 9- General Principles of International Law.pptxJorenAcuavera1
 
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.PraveenaKalaiselvan1
 

Recently uploaded (20)

FREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naFREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by na
 
Solution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutionsSolution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutions
 
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
User Guide: Pulsar™ Weather Station (Columbia Weather Systems)
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdf
 
preservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptxpreservation, maintanence and improvement of industrial organism.pptx
preservation, maintanence and improvement of industrial organism.pptx
 
User Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather StationUser Guide: Capricorn FLX™ Weather Station
User Guide: Capricorn FLX™ Weather Station
 
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
 
Scheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxScheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docx
 
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxLIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
 
Pests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdfPests of soyabean_Binomics_IdentificationDr.UPR.pdf
Pests of soyabean_Binomics_IdentificationDr.UPR.pdf
 
Transposable elements in prokaryotes.ppt
Transposable elements in prokaryotes.pptTransposable elements in prokaryotes.ppt
Transposable elements in prokaryotes.ppt
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
 
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptxMicrophone- characteristics,carbon microphone, dynamic microphone.pptx
Microphone- characteristics,carbon microphone, dynamic microphone.pptx
 
Environmental Biotechnology Topic:- Microbial Biosensor
Environmental Biotechnology Topic:- Microbial BiosensorEnvironmental Biotechnology Topic:- Microbial Biosensor
Environmental Biotechnology Topic:- Microbial Biosensor
 
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort ServiceHot Sexy call girls in  Moti Nagar,🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Moti Nagar,🔝 9953056974 🔝 escort Service
 
User Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather StationUser Guide: Magellan MX™ Weather Station
User Guide: Magellan MX™ Weather Station
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
 
TOPIC 8 Temperature and Heat.pdf physics
TOPIC 8 Temperature and Heat.pdf physicsTOPIC 8 Temperature and Heat.pdf physics
TOPIC 8 Temperature and Heat.pdf physics
 
Topic 9- General Principles of International Law.pptx
Topic 9- General Principles of International Law.pptxTopic 9- General Principles of International Law.pptx
Topic 9- General Principles of International Law.pptx
 
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
 

C++ Nested loops, matrix and fuctions.pdf

  • 1. • Used to execute a set of operations multiple times, with one loop inside another. • It allows for iterating over multidimensional data structures, among other use cases. • The outer loop completes one full iteration for each single iteration of the inner loop, creating a loop within a loop. Nested Loops
  • 2. for (initialization; condition; increment) { // Outer loop body for (initialization; condition; increment) { // Inner loop body // Code to be executed for each iteration of the inner loop } // Additional code can be executed in the outer loop } Structure of Nested Loops
  • 3. #include <iostream> using namespace std; int main() { for(int i = 1; i <= 10; i++) { // Outer loop for(int j = 1; j <= 10; j++) { // Inner loop cout << i*j << "t"; // Multiply i and j, separated by a tab } cout << endl; } return 0; } Multiplication table up to 10 using nested loops.
  • 4. #include <iostream> using namespace std; int main() { for(int i = 0; i < 5; i++) { // Outer loop for rows for(int j = 0; j < 5; j++) { // Inner loop for columns cout << "* "; } cout << endl; // Move to the next line after each row } return 0; } Drawing a square pattern
  • 5. • Arrays in C++ provide a way to store a collection of variables of the same type. • An array can be declared by specifying the type of its elements, followed by the array name and the number of elements it will hold inside square brackets. int numbers [5] Arrays
  • 6.
  • 7. #include <iostream> using namespace std; int main() { // Declare and initialize an array of integers with 5 elements int numbers[5] = {10, 20, 30, 40, 50}; // Access and print each element of the array for(int i = 0; i < 5; i++) { cout << "Element at index " << i << ": " << numbers[i] << endl; } return 0; } An integer array named numbers with 5 elements
  • 8. #include <iostream> using namespace std; int main() { int numbers[5] = {10, 20, 30, 40, 50}; int sum = 0; // Calculate sum of array elements for(int i = 0; i < 5; i++) { sum += numbers[i]; } cout << "Sum of array elements: " << sum << endl; return 0; } Calculating the sum of Array elements
  • 9. #include <iostream> using namespace std; int main() { int matrix[2][2] = { {1, 2}, // First row {3, 4} // Second row }; // Access and print each element of the matrix // Outer loop for rows for(int i = 0; i < 2; i++) { 2x2 matrix using array
  • 10. 2x2 matrix using array (contnd) // Inner loop for columns for(int j = 0; j < 2; j++) { cout << "Element at (" << i << ", " << j << "): " << matrix[i][j] << endl; } } return 0; }
  • 11. #include <iostream> using namespace std; int main() { // Declare and initialize two 2x2 matrices int matrixA[2][2] = {{1, 2}, {3, 4}}; int matrixB[2][2] = {{5, 6}, {7, 8}}; int sumMatrix[2][2]; // To store the sum of the matrices // Calculate the sum of the matrices for(int i = 0; i < 2; i++) { // Loop over rows for(int j = 0; j < 2; j++) { // Loop over columns Calculating the sum of matrices
  • 12. sumMatrix[i][j] = matrixA[i][j] + matrixB[i][j]; } } cout << "Sum of Matrix A and Matrix B is:" << endl; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { cout << sumMatrix[i][j] << " "; } cout << endl; // New line for each row } return 0; } Calculating the sum of matrices (continued)
  • 13. Program to Input and Display Array Elements #include <iostream> using namespace std; int main() { int arr[5]; // Declaring an array of size 5 // Input array elements cout << "Enter 5 integers:" << endl; for(int i = 0; i < 5; i++) { cin >> arr[i];
  • 14. Program to Input and Display Array Elements (contnd) } // Display array elements cout << "Array elements are:" << endl; for(int i = 0; i < 5; i++) { cout << arr[i] << " "; } return 0; }
  • 15. Program to Calculate the Sum and Average of Array Elements #include <iostream> using namespace std; int main() { int n, sum 0; float average; cout << "Enter the number of elements in the array: "; cin >> n; int arr[n]; cout << "Enter the elements:" << endl;
  • 16. contnd for(int i = 0; i < n; i++) { cin >> arr[i]; sum += arr[i]; // Adding elements to sum } average = sum / n; // Calculating average cout << "Sum of array elements is: " << sum << endl; cout << "Average of array elements is: " << average << endl; return 0; }
  • 17. Program to Find the Largest Element in an Array #include <iostream> using namespace std; int main() { int n, max; cout << "Enter the number of elements in the array: "; cin >> n; int arr[n]; cout << "Enter the elements of the array:" << endl; for(int i = 0; i < n; i++) {
  • 18. contnd cin >> arr[i]; } max = arr[0]; for(int i = 1; i < n; i++) { if(arr[i] > max) max = arr[i]; } cout << “Largest element in the array is: " << max << endl; return 0; }
  • 19. Inputs Elements Of A Matrix Then Displays In Matrix Format #include <iostream> using namespace std; int main() { int rows, cols; // Prompt user for the dimensions of the matrix cout << "Enter number of rows: "; cin >> rows; cout << "Enter number of columns: "; cin >> cols;
  • 20. contnd // Create a 2D array (matrix) based on the input dimensions int matrix[rows][cols]; cout << "Enter elements of the matrix:" << endl; for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { cin >> matrix[i][j]; } }
  • 21. contnd // Display the matrix in matrix format cout << "The matrix is:" << endl; for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { cout << matrix[i][j] << " "; } cout << endl; // Move to the next line after printing each row } return 0; }
  • 22. Sum of Matrix #include <iostream> using namespace std; int main() { int rows, cols; // Prompt for matrix size cout << "Enter the number of rows and columns for the matrices: "; cin >> rows >> cols; int matrix1[rows][cols], matrix2[rows][cols], sum[rows][cols]; // Input elements for the first matrix
  • 23. Sum of Matrix (contnd) cout << "Enter elements of the first matrix:" << endl; for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { cin >> matrix1[i][j]; } } // Input elements for the second matrix cout << "Enter elements of the second matrix:" << endl; for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { cin >> matrix2[i][j]; } }
  • 24. Sum of Matrix (contnd) // Calculate the sum of the two matrices for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { sum[i][j] = matrix1[i][j] + matrix2[i][j]; } } // Display the resulting matrix cout << "Sum of the two matrices:" << endl; for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { cout << sum[i][j] << " "; } cout << endl; } return 0; }
  • 25. Functions • Functions are blocks of code designed to perform a specific task. • Used to structure programs into segments. Declaration and Definition • Declaration: Tells the compiler about a function's name, return type, and parameters (if any). It's also known as a function prototype. • Definition: Contains the actual body of the function, detailing the statements that execute when the function is called.
  • 27. Syntax • 'return_type ': The data type of the value the function returns. 'function_name': The name of the function, following the rules for identifiers. • 'parameter list': A comma-separated list of input parameters that are passed into the function, each specified with a type and name. If the function takes no parameters, this can be left empty or explicitly defined with 'void'.
  • 28. Add function #include <iostream> using namespace std; // Function declaration int add(int, int); int main() { int result; // Function call result = add(5, 3); cout << "The sum is: " << result << endl; return 0; } // Function definition int add(int a, int b) { return a + b; }
  • 29. Find the Maximum of Two Numbers #include <iostream> using namespace std; // Function to find the maximum of two numbers int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; } int main() { int a, b; cout << "Enter two integers: "; cin >> a >> b; cout << "The maximum is: " << max(a, b); return 0; }
  • 30. #include <iostream> using namespace std; float PI = 3.14159; // Use float for PI // Function to calculate the area of a circle float calculateArea(float radius) { return PI * radius * radius; } Area of a Circle
  • 31. int main() { float radius; cout << "Enter the radius of the circle: "; cin >> radius; float area = calculateArea(radius); // Change type to float cout << "The area of the circle is: " << area; return 0; } Area of a Circle (contd)
  • 32. #include <iostream> using namespace std; // Function to check even or odd int isEven(int number) { return (number % 2 == 0); // This still returns 1 (true) for even and 0 (false) for odd } int main() { int num; cout << "Enter an integer: "; cin >> num; Number is even or odd
  • 33. if (isEven(num)) cout << num << " is even."; else cout << num << " is odd."; return 0; } Number is even or odd (contd)
  • 34. cin >> num; if (num < 0) { cout << "Factorial of a negative number doesn't exist."; } else { long long result = factorial(num); cout << "The factorial of " << num << " is: " << result << endl; } return 0; } Factorial
  • 35. #include <iostream> using namespace std; // Function to add two numbers int add(int num1, int num2) { return num1 + num2; } int main() { int a, b; cout << "Enter first number: "; cin >> a; cout << "Enter second number: "; Add function
  • 36. cin >> b; int sum = add(a, b); // Call the add function cout << "The sum is: " << sum << endl; return 0; } Add function (contnd)
  • 37. #include <iostream> using namespace std; // Function to check if a number is even or odd int isEven(int num) { return (num % 2 == 0); } int main() { int num; cout << "Enter a number: "; cin >> num; if (isEven(num)) { Check Even or Odd Using a Function
  • 38. cout << num << " is even." << endl; } else { cout << num << " is odd." << endl; } return 0; } Check Even or Odd Using a Function (contnd)