SlideShare a Scribd company logo
1 of 38
Download to read offline
Computing Fundamentals
Dr. Muhammad Yousaf Hamza
Deputy Chief Engineer, PIEAS
Compute the average marks
Dr. Yousaf, PIEAS
Suppose there are 3 students in a class. Compute
the average marks of these students in a test.
For the solution, what we
need?
3 variables to store three
values of the marks.
Name these as marks1,
marks2, marks3.
Add all these values.
Divide this sum by 3.0.
The average value may
contain decimal point.
Compute the average marks
Dr. Yousaf, PIEAS
Suppose there are 3 students in a class. Compute
the average marks of these students in a test.
For the solution, what we
need?
3 variables to store three
values of the marks.
Name these as marks1,
marks2, marks3.
Add all these values.
Divide this sum by 3.0.
The average value may
contain decimal point.
#include<stdio.h>
int main ()
{
float marks1, marks2, marks3;
float avg;
marks1 = 34.5;
marks2 = 56;
marks3 = 83.5;
avg =
(marks1+marks2+marks3)/3.0;
printf("The average marks are:
%f", avg);
getchar(); return 0;}
Compute the average marks
Dr. Yousaf, PIEAS
Suppose there are ten students in a class. Compute
the average marks of these students in a test.
For the solution, what we need?
10 variables to store ten values of the
marks. Name these as marks1, marks2, …
marks 10.
Add all these values. Divide this sum by
10. The average value may contain
decimal point.
Compute the average marks
Dr. Yousaf, PIEAS
#include<stdio.h>
int main ()
{
float marks1, marks2,
marks3, marks4,
marks5,marks6, marks7,
marks8, marks9, marks10;
float avg;
marks1 = 56.5;
marks2 = 78.0;
marks3 = 23.2;
marks4 = 89.1;
marks5 = 43.7;
marks6 = 91.6;
marks7 = 57.3;
marks8 = 33.6;
marks9 = 66.2;
marks10 = 85.8;
avg = (marks1 + marks2 +
marks3 + marks4 + marks5 +
marks6 + marks7 + marks8
+marks9 + marks10)/10.0;
printf("The average marks
are: %f", avg);
getchar();return 0; }
Suppose there are ten students in a class. Compute
the average marks of these students in a test.
Compute the average marks
Dr. Yousaf, PIEAS
What’s about if there are 30 students?
30 variables would be needed to store values of the
marks. marks1, marks2, … marks 30.
What’s about if there are 100 (or 500) students?
100 (or 500) variables would be needed to store
values of the marks. marks1, marks2, … marks 100
(or 500).
Is it practical approach? Can we handle it using just
ONE variable?
Solution is: Arrays
Compute the average marks
Dr. Yousaf, PIEAS
What’s about if there are 30 students?
30 variables would be needed to store values of the
marks. marks1, marks2, … marks 30.
What’s about if there are 100 (or 500) students?
100 (or 500) variables would be needed to store
values of the marks. marks1, marks2, … marks 100
(or 500).
Is it practical approach? Can we handle it using just
ONE variable?
Solution is: Arrays
Arrays
Dr. Yousaf, PIEAS
Introduction to Arrays
int marks = 70; // single value
int marks[6]={36,78,29,36,7,99};
Dr. Yousaf, PIEAS
Introduction to Arrays
#include<stdio.h>
int main()
{
int marks = 70; // single value
printf("Marks are %d",marks);
/* single value will be printed */
getchar();
return 0;
}
Dr. Yousaf, PIEAS
#include<stdio.h>
int main()
{
int marks[6]={36,78,29,89,7,99}; // array
printf("Marks are %dn",marks); // error
getchar();
return 0;
}
Dr. Yousaf, PIEAS
Arrays
#include<stdio.h>
int main()
{
int marks[6]={36,78,29,89,7,99};
int i;
for (i = 0; i <6;i++)
printf("Marks are %dn",marks[i]);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
How to Print Arrays?
#include<stdio.h>
int main()
{
int marks[6];
int i;
for (i = 0; i <6;i++)
{
printf(“Please enter the marks of studentsn”);
scanf(“ %d",&marks[i]);
}
getchar();
return 0; } Dr. Yousaf, PIEAS
How to read values of Arrays?
Single-Dimensional Arrays
Generic declaration:
typename variablename[size]
– typename is any type
– variablename is any legal variable name
– size of array
– For example
int a[10];
– Defines an array of ints with subscripts ranging from 0 to
9
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
– There are 10*sizeof(int) bytes of memory reserved for
this array.
– You can use a[0]=10; x=a[2]; a[3]=a[2]; etc.
Dr. Yousaf, PIEAS
Initializing Arrays
• Initialization of arrays can be done by a comma
separated list following its definition.
• For example:
int array [4] = { 100, 200, 300, 400 };
– This is equivalent to:
int array [4];
array[0] = 100;
array[1] = 200;
array[2] = 300;
array[3] = 400;
Dr. Yousaf, PIEAS
A Simple Example
#include <stdio.h>
int main()
{
float expenses[12]={10.3, 9, 7.5, 4.3, 10.5, 7.5, 7.5, 8, 9.9, 10.2,
11.5, 7.8};
int count, month;
float total;
for (month=0, total=0.0; month < 12; month++)
{
total+=expenses[month];
}
for (count=0; count < 12; count++)
printf ("Month %d = %.2f Rupeesn", count+1, expenses[count]);
printf("Total = %.2f Rupeesn Average = %.2f Rupeesn", total,
total/12.0);
getchar(); return 0; } Dr. Yousaf, PIEAS
Arrays
• Array
– Structures of related data items
– Group of consecutive memory locations
– Same name and type
• To refer to an element, specify
– Array name
– Position number
• Format:
arrayname[ position number ]
– First element at position 0
– n element array named c:
• c[ 0 ], c[ 1 ]...c[ n – 1 ]
Name of array (Note
that all elements of this
array have the same
name, c)
Position number of
the element within
array c
c[6]
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
Dr. Yousaf, PIEAS
Arrays
Array elements are like normal variables
c[0] = 3;
printf( "%d", c[ 0 ] );
– Perform operations inside brackets.
If x = 3, then the following comparisons are same.
c[5 - 2] or c[ 3 ] or c[ x ]
Dr. Yousaf, PIEAS
Declaring Arrays
• When declaring arrays, specify
– Type of array
– Name
– Number of elements
arrayType arrayName[numberOfElements];
– Examples:
int c[ 10 ];
float myArray[ 32 ];
• Declaring multiple arrays of same type
– Format similar to regular variables
– Example:
int b[ 100 ], x[ 27 ];
Dr. Yousaf, PIEAS
Using Constants to Define Arrays
It is useful to define arrays using #define:
#define MONTHS 12
int array [MONTHS];
Dr. Yousaf, PIEAS
Important Points
• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements
become 0
int n[ 5 ] = { 1 }
• All other elements would be 0
(Example on next slide)
Dr. Yousaf, PIEAS
#include<stdio.h>
int main()
{
int marks[6]={36,78};
int i;
for (i = 0; i <6;i++)
printf(“%dn",marks[i]);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
If not enough initializers, rightmost
elements become 0
Important Points
//C arrays have no bounds checking
Dr. Yousaf, PIEAS
#include<stdio.h>
int main()
{
int marks[6]={10,20,30,40,50,60};
int i;
for (i = 0; i <8;i++)
printf(“%dn",marks[i]);
getchar();
return 0;
}
Important Points
If more values are provided than the size of the array as:
Dr. Yousaf, PIEAS
#include<stdio.h>
int main()
{
int marks[6]={10,20,30,40,50,60,70,80};
int i;
for (i = 0; i <8;i++)
printf(“%dn",marks[i]);
getchar();
return 0;
}
This program
will give error
and will not
run.
Error: Too many
intializers
#include<stdio.h>
int main()
{
int marks[6]; // no initialization
int i;
for (i = 0; i <2; i++) //scanning lesser values than the size of array
{
printf("Please enter the marks of studentsn");
scanf("%d",&marks[i]); // suppose we enter 1 and 2.
}
for (i = 0; i <6;i++)
printf(“%dn",marks[i]); // printing 6 values
getchar(); return 0;}
// First two values will be 1 and 2. Rest will be garbage (not
zeroes), as shown in the next slide.
Dr. Yousaf, PIEAS
Important Points
Dr. Yousaf, PIEAS
Important Points
So if values (lesser than the size of array) are initialized at
the time of declaration) then rest of the values are set to
zeros, however if values (lesser than the size of array) are
initialized through scanf then rest of the values are
garbage values (not zeros).
#include<stdio.h>
int main()
{
int marks[6]; // no initialization
int i;
for (i = 0; i <8; i++) //scanning more values than the size of array
{
printf("Please enter the marks of studentsn");
scanf("%d",&marks[i]);
}
for (i = 0; i <6;i++)
printf(“%dn",marks[i]); // printing 6 values
getchar(); return 0;}
This program will run (no error). It will take 8 values. When
scanning loop will terminate, you will get message: “A buffer
over run has occuered”. It will not show any output.
Dr. Yousaf, PIEAS
Important Points
Some Examples of Arrays
Dr. Yousaf, PIEAS
#include<stdio.h>
int main()
{
int marks[6]={36,78,7,99,43,29};
int i, sum;
sum = 0;
/* Complete It */
printf("Sum of Marks are %dn", sum);
getchar(); return 0; }
Dr. Yousaf, PIEAS
Summation of Marks
Summation of Marks
#include<stdio.h>
int main()
{
int marks[6]={36,78,7,99,43,29};
int i, sum;
sum = 0;
for (i = 0; i <6;i++)
{
sum = sum + marks[i];
}
printf("Sum of Marks are %dn", sum);
getchar(); return 0; }
Dr. Yousaf, PIEAS
#include<stdio.h>
int main()
{
int marks[6]={36,78,7,99,43,29};
int i, sum;
sum = 0;
i = 0;
while (i <6)
{
sum = sum + marks[i];
i++;
}
printf("Sum of Marks are %dn", sum);
getchar(); return 0; }
Dr. Yousaf, PIEAS
Summation of Marks
#include<stdio.h>
int main()
{
int marks[6] =
{36,78,7,99,43,29};
int i, sum;
sum = 0;
i = 0;
do
{
sum = sum + marks[i];
i++;
}
while (i <6);
printf("Sum of Marks are
%dn",sum);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
Summation of Marks
#include<stdio.h>
int main()
{
int marks[6] =
{36,78,7,99,43,29};
int i, Maximum;
/* Complete It */
Dr. Yousaf, PIEAS
To Find the Maximum Marks
#include<stdio.h>
int main()
{
int marks[6] =
{36,78,7,99,43,29};
int i, Maximum;
Maximum = marks[0];
for (i = 1; i <6;i++)
{
if (Maximum <marks[i])
{
Maximum = marks[i];
}
}
printf("Maximum Marks are
%dn",Maximum);
getchar(); return 0; }
Dr. Yousaf, PIEAS
To Find the Maximum Marks
The following program declares an array of 5 integers,
initializes the array using an initializer list (complete) and
displays the values stored in array elements
#include<stdio.h>
int main()
{
int A[5]={1,2,3,4,5};
int index=0;
while(index<5)
{
printf(“%d n”,A[index]);
index=index+1;
}
}
Dr. Yousaf, PIEAS
Write a complete and an efficient C-Program in which
declare two arrays of 5 integers each, initialize the arrays
from user, and displays the sum of these two arrays.
Write a program that declares two integer arrays of 10
elements each, name the arrays as even and odd. The
program should allow the user to enter 10 numbers, all
even numbers should be stored in array even while all odd
numbers should be stored in array odd, finally the
program should display the contents of the two arrays.
(Yourself)
Dr. Yousaf, PIEAS
Write a program that creates an integer array A of 5
elements, initialize the array with a list. The task is to
re‐order this array as specified by user. Ask the user to
enter new order for array elements one by one. For
example if the first number entered by user is 4 for
element 1, this means A[4] should now be the first
element in the array.
Write a program that creates an array of 10 elements,
let the user enter the values, the program should find
the two array elements whose sum is the largest of sum
of any two array elements. For example for an array A
consisting of 20,5,13,7,11 the sum of 20 and 13 is largest
of sum of any two numbers.
(Yourself)
Dr. Yousaf, PIEAS
Write program in which declare an array of size 10. Initialize
the elements from the user. Find largest and smallest numbers
in this array. After the smallest and largest numbers are found,
the program should store the largest number at the beginning
of the array and smallest number at the end of the array . For
example if the name of your array is A, A[0] should contain the
largest number and A[N] should contain the smallest number.
Write a program in which declare two arrays A and B for 3
integers each, initialize the arrays from the user. The program
should display the values of these two arrays and later should
exchange the values of A with B i.e. values stored in array A
should be replaced by values stored in array B and values
stored in array B should be replaced by values stored in array A.
It is called swapping. Finally the program should display the
new values of A and B. (Hint , for swapping you might need a
third array ).
(Yourself)
Dr. Yousaf, PIEAS

More Related Content

Similar to C Language Lecture 9

Similar to C Language Lecture 9 (20)

Array in C.pdf
Array in C.pdfArray in C.pdf
Array in C.pdf
 
Array.pdf
Array.pdfArray.pdf
Array.pdf
 
C Language Lecture 8
C Language Lecture 8C Language Lecture 8
C Language Lecture 8
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
Array-part1
Array-part1Array-part1
Array-part1
 
CHAPTER 5
CHAPTER 5CHAPTER 5
CHAPTER 5
 
Lecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptxLecture_3.5-Array_Type Conversion_Math Class.pptx
Lecture_3.5-Array_Type Conversion_Math Class.pptx
 
Arrays
ArraysArrays
Arrays
 
Array notes
Array notesArray notes
Array notes
 
MEASURE OF CENTRAL TENDENCY
MEASURE OF CENTRAL TENDENCY  MEASURE OF CENTRAL TENDENCY
MEASURE OF CENTRAL TENDENCY
 
C_Arrays.pptx
C_Arrays.pptxC_Arrays.pptx
C_Arrays.pptx
 
3 descritive statistics measure of central tendency variatio
3 descritive statistics measure of   central   tendency variatio3 descritive statistics measure of   central   tendency variatio
3 descritive statistics measure of central tendency variatio
 
Statistics Notes
Statistics NotesStatistics Notes
Statistics Notes
 
Array i imp
Array  i impArray  i imp
Array i imp
 
C Language Lecture 19
C Language Lecture 19C Language Lecture 19
C Language Lecture 19
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
lab program 6.pdf
lab program 6.pdflab program 6.pdf
lab program 6.pdf
 
358 33 powerpoint-slides_5-arrays_chapter-5
358 33 powerpoint-slides_5-arrays_chapter-5358 33 powerpoint-slides_5-arrays_chapter-5
358 33 powerpoint-slides_5-arrays_chapter-5
 
Data structures Lecture 5
Data structures Lecture 5Data structures Lecture 5
Data structures Lecture 5
 

More from Shahzaib Ajmal

More from Shahzaib Ajmal (14)

C Language Lecture 22
C Language Lecture 22C Language Lecture 22
C Language Lecture 22
 
C Language Lecture 21
C Language Lecture 21C Language Lecture 21
C Language Lecture 21
 
C Language Lecture 17
C Language Lecture 17C Language Lecture 17
C Language Lecture 17
 
C Language Lecture 16
C Language Lecture 16C Language Lecture 16
C Language Lecture 16
 
C Language Lecture 15
C Language Lecture 15C Language Lecture 15
C Language Lecture 15
 
C Language Lecture 14
C Language Lecture 14C Language Lecture 14
C Language Lecture 14
 
C Language Lecture 13
C Language Lecture 13C Language Lecture 13
C Language Lecture 13
 
C Language Lecture 12
C Language Lecture 12C Language Lecture 12
C Language Lecture 12
 
C Language Lecture 7
C Language Lecture 7C Language Lecture 7
C Language Lecture 7
 
C Language Lecture 6
C Language Lecture 6C Language Lecture 6
C Language Lecture 6
 
C Language Lecture 4
C Language Lecture  4C Language Lecture  4
C Language Lecture 4
 
C Language Lecture 3
C Language Lecture  3C Language Lecture  3
C Language Lecture 3
 
C Language Lecture 2
C Language Lecture  2C Language Lecture  2
C Language Lecture 2
 
C Language Lecture 1
C Language Lecture  1C Language Lecture  1
C Language Lecture 1
 

Recently uploaded

diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....Ritu480198
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSean M. Fox
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital ManagementMBA Assignment Experts
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhleson0603
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMELOISARIVERA8
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17Celine George
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi RajagopalEADTU
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxMohamed Rizk Khodair
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFVivekanand Anglo Vedic Academy
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...Gary Wood
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024Borja Sotomayor
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...Nguyen Thanh Tu Collection
 
Climbers and Creepers used in landscaping
Climbers and Creepers used in landscapingClimbers and Creepers used in landscaping
Climbers and Creepers used in landscapingDr. M. Kumaresan Hort.
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxMarlene Maheu
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 

Recently uploaded (20)

Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptx
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
BỘ LUYỆN NGHE TIẾNG ANH 8 GLOBAL SUCCESS CẢ NĂM (GỒM 12 UNITS, MỖI UNIT GỒM 3...
 
Climbers and Creepers used in landscaping
Climbers and Creepers used in landscapingClimbers and Creepers used in landscaping
Climbers and Creepers used in landscaping
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 

C Language Lecture 9

  • 1. Computing Fundamentals Dr. Muhammad Yousaf Hamza Deputy Chief Engineer, PIEAS
  • 2. Compute the average marks Dr. Yousaf, PIEAS Suppose there are 3 students in a class. Compute the average marks of these students in a test. For the solution, what we need? 3 variables to store three values of the marks. Name these as marks1, marks2, marks3. Add all these values. Divide this sum by 3.0. The average value may contain decimal point.
  • 3. Compute the average marks Dr. Yousaf, PIEAS Suppose there are 3 students in a class. Compute the average marks of these students in a test. For the solution, what we need? 3 variables to store three values of the marks. Name these as marks1, marks2, marks3. Add all these values. Divide this sum by 3.0. The average value may contain decimal point. #include<stdio.h> int main () { float marks1, marks2, marks3; float avg; marks1 = 34.5; marks2 = 56; marks3 = 83.5; avg = (marks1+marks2+marks3)/3.0; printf("The average marks are: %f", avg); getchar(); return 0;}
  • 4. Compute the average marks Dr. Yousaf, PIEAS Suppose there are ten students in a class. Compute the average marks of these students in a test. For the solution, what we need? 10 variables to store ten values of the marks. Name these as marks1, marks2, … marks 10. Add all these values. Divide this sum by 10. The average value may contain decimal point.
  • 5. Compute the average marks Dr. Yousaf, PIEAS #include<stdio.h> int main () { float marks1, marks2, marks3, marks4, marks5,marks6, marks7, marks8, marks9, marks10; float avg; marks1 = 56.5; marks2 = 78.0; marks3 = 23.2; marks4 = 89.1; marks5 = 43.7; marks6 = 91.6; marks7 = 57.3; marks8 = 33.6; marks9 = 66.2; marks10 = 85.8; avg = (marks1 + marks2 + marks3 + marks4 + marks5 + marks6 + marks7 + marks8 +marks9 + marks10)/10.0; printf("The average marks are: %f", avg); getchar();return 0; } Suppose there are ten students in a class. Compute the average marks of these students in a test.
  • 6. Compute the average marks Dr. Yousaf, PIEAS What’s about if there are 30 students? 30 variables would be needed to store values of the marks. marks1, marks2, … marks 30. What’s about if there are 100 (or 500) students? 100 (or 500) variables would be needed to store values of the marks. marks1, marks2, … marks 100 (or 500). Is it practical approach? Can we handle it using just ONE variable? Solution is: Arrays
  • 7. Compute the average marks Dr. Yousaf, PIEAS What’s about if there are 30 students? 30 variables would be needed to store values of the marks. marks1, marks2, … marks 30. What’s about if there are 100 (or 500) students? 100 (or 500) variables would be needed to store values of the marks. marks1, marks2, … marks 100 (or 500). Is it practical approach? Can we handle it using just ONE variable? Solution is: Arrays
  • 9. Introduction to Arrays int marks = 70; // single value int marks[6]={36,78,29,36,7,99}; Dr. Yousaf, PIEAS
  • 10. Introduction to Arrays #include<stdio.h> int main() { int marks = 70; // single value printf("Marks are %d",marks); /* single value will be printed */ getchar(); return 0; } Dr. Yousaf, PIEAS
  • 11. #include<stdio.h> int main() { int marks[6]={36,78,29,89,7,99}; // array printf("Marks are %dn",marks); // error getchar(); return 0; } Dr. Yousaf, PIEAS Arrays
  • 12. #include<stdio.h> int main() { int marks[6]={36,78,29,89,7,99}; int i; for (i = 0; i <6;i++) printf("Marks are %dn",marks[i]); getchar(); return 0; } Dr. Yousaf, PIEAS How to Print Arrays?
  • 13. #include<stdio.h> int main() { int marks[6]; int i; for (i = 0; i <6;i++) { printf(“Please enter the marks of studentsn”); scanf(“ %d",&marks[i]); } getchar(); return 0; } Dr. Yousaf, PIEAS How to read values of Arrays?
  • 14. Single-Dimensional Arrays Generic declaration: typename variablename[size] – typename is any type – variablename is any legal variable name – size of array – For example int a[10]; – Defines an array of ints with subscripts ranging from 0 to 9 a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] – There are 10*sizeof(int) bytes of memory reserved for this array. – You can use a[0]=10; x=a[2]; a[3]=a[2]; etc. Dr. Yousaf, PIEAS
  • 15. Initializing Arrays • Initialization of arrays can be done by a comma separated list following its definition. • For example: int array [4] = { 100, 200, 300, 400 }; – This is equivalent to: int array [4]; array[0] = 100; array[1] = 200; array[2] = 300; array[3] = 400; Dr. Yousaf, PIEAS
  • 16. A Simple Example #include <stdio.h> int main() { float expenses[12]={10.3, 9, 7.5, 4.3, 10.5, 7.5, 7.5, 8, 9.9, 10.2, 11.5, 7.8}; int count, month; float total; for (month=0, total=0.0; month < 12; month++) { total+=expenses[month]; } for (count=0; count < 12; count++) printf ("Month %d = %.2f Rupeesn", count+1, expenses[count]); printf("Total = %.2f Rupeesn Average = %.2f Rupeesn", total, total/12.0); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 17. Arrays • Array – Structures of related data items – Group of consecutive memory locations – Same name and type • To refer to an element, specify – Array name – Position number • Format: arrayname[ position number ] – First element at position 0 – n element array named c: • c[ 0 ], c[ 1 ]...c[ n – 1 ] Name of array (Note that all elements of this array have the same name, c) Position number of the element within array c c[6] c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4] Dr. Yousaf, PIEAS
  • 18. Arrays Array elements are like normal variables c[0] = 3; printf( "%d", c[ 0 ] ); – Perform operations inside brackets. If x = 3, then the following comparisons are same. c[5 - 2] or c[ 3 ] or c[ x ] Dr. Yousaf, PIEAS
  • 19. Declaring Arrays • When declaring arrays, specify – Type of array – Name – Number of elements arrayType arrayName[numberOfElements]; – Examples: int c[ 10 ]; float myArray[ 32 ]; • Declaring multiple arrays of same type – Format similar to regular variables – Example: int b[ 100 ], x[ 27 ]; Dr. Yousaf, PIEAS
  • 20. Using Constants to Define Arrays It is useful to define arrays using #define: #define MONTHS 12 int array [MONTHS]; Dr. Yousaf, PIEAS
  • 21. Important Points • Initializers int n[ 5 ] = { 1, 2, 3, 4, 5 }; – If not enough initializers, rightmost elements become 0 int n[ 5 ] = { 1 } • All other elements would be 0 (Example on next slide) Dr. Yousaf, PIEAS
  • 22. #include<stdio.h> int main() { int marks[6]={36,78}; int i; for (i = 0; i <6;i++) printf(“%dn",marks[i]); getchar(); return 0; } Dr. Yousaf, PIEAS If not enough initializers, rightmost elements become 0
  • 23. Important Points //C arrays have no bounds checking Dr. Yousaf, PIEAS #include<stdio.h> int main() { int marks[6]={10,20,30,40,50,60}; int i; for (i = 0; i <8;i++) printf(“%dn",marks[i]); getchar(); return 0; }
  • 24. Important Points If more values are provided than the size of the array as: Dr. Yousaf, PIEAS #include<stdio.h> int main() { int marks[6]={10,20,30,40,50,60,70,80}; int i; for (i = 0; i <8;i++) printf(“%dn",marks[i]); getchar(); return 0; } This program will give error and will not run. Error: Too many intializers
  • 25. #include<stdio.h> int main() { int marks[6]; // no initialization int i; for (i = 0; i <2; i++) //scanning lesser values than the size of array { printf("Please enter the marks of studentsn"); scanf("%d",&marks[i]); // suppose we enter 1 and 2. } for (i = 0; i <6;i++) printf(“%dn",marks[i]); // printing 6 values getchar(); return 0;} // First two values will be 1 and 2. Rest will be garbage (not zeroes), as shown in the next slide. Dr. Yousaf, PIEAS Important Points
  • 26. Dr. Yousaf, PIEAS Important Points So if values (lesser than the size of array) are initialized at the time of declaration) then rest of the values are set to zeros, however if values (lesser than the size of array) are initialized through scanf then rest of the values are garbage values (not zeros).
  • 27. #include<stdio.h> int main() { int marks[6]; // no initialization int i; for (i = 0; i <8; i++) //scanning more values than the size of array { printf("Please enter the marks of studentsn"); scanf("%d",&marks[i]); } for (i = 0; i <6;i++) printf(“%dn",marks[i]); // printing 6 values getchar(); return 0;} This program will run (no error). It will take 8 values. When scanning loop will terminate, you will get message: “A buffer over run has occuered”. It will not show any output. Dr. Yousaf, PIEAS Important Points
  • 28. Some Examples of Arrays Dr. Yousaf, PIEAS
  • 29. #include<stdio.h> int main() { int marks[6]={36,78,7,99,43,29}; int i, sum; sum = 0; /* Complete It */ printf("Sum of Marks are %dn", sum); getchar(); return 0; } Dr. Yousaf, PIEAS Summation of Marks
  • 30. Summation of Marks #include<stdio.h> int main() { int marks[6]={36,78,7,99,43,29}; int i, sum; sum = 0; for (i = 0; i <6;i++) { sum = sum + marks[i]; } printf("Sum of Marks are %dn", sum); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 31. #include<stdio.h> int main() { int marks[6]={36,78,7,99,43,29}; int i, sum; sum = 0; i = 0; while (i <6) { sum = sum + marks[i]; i++; } printf("Sum of Marks are %dn", sum); getchar(); return 0; } Dr. Yousaf, PIEAS Summation of Marks
  • 32. #include<stdio.h> int main() { int marks[6] = {36,78,7,99,43,29}; int i, sum; sum = 0; i = 0; do { sum = sum + marks[i]; i++; } while (i <6); printf("Sum of Marks are %dn",sum); getchar(); return 0; } Dr. Yousaf, PIEAS Summation of Marks
  • 33. #include<stdio.h> int main() { int marks[6] = {36,78,7,99,43,29}; int i, Maximum; /* Complete It */ Dr. Yousaf, PIEAS To Find the Maximum Marks
  • 34. #include<stdio.h> int main() { int marks[6] = {36,78,7,99,43,29}; int i, Maximum; Maximum = marks[0]; for (i = 1; i <6;i++) { if (Maximum <marks[i]) { Maximum = marks[i]; } } printf("Maximum Marks are %dn",Maximum); getchar(); return 0; } Dr. Yousaf, PIEAS To Find the Maximum Marks
  • 35. The following program declares an array of 5 integers, initializes the array using an initializer list (complete) and displays the values stored in array elements #include<stdio.h> int main() { int A[5]={1,2,3,4,5}; int index=0; while(index<5) { printf(“%d n”,A[index]); index=index+1; } } Dr. Yousaf, PIEAS
  • 36. Write a complete and an efficient C-Program in which declare two arrays of 5 integers each, initialize the arrays from user, and displays the sum of these two arrays. Write a program that declares two integer arrays of 10 elements each, name the arrays as even and odd. The program should allow the user to enter 10 numbers, all even numbers should be stored in array even while all odd numbers should be stored in array odd, finally the program should display the contents of the two arrays. (Yourself) Dr. Yousaf, PIEAS
  • 37. Write a program that creates an integer array A of 5 elements, initialize the array with a list. The task is to re‐order this array as specified by user. Ask the user to enter new order for array elements one by one. For example if the first number entered by user is 4 for element 1, this means A[4] should now be the first element in the array. Write a program that creates an array of 10 elements, let the user enter the values, the program should find the two array elements whose sum is the largest of sum of any two array elements. For example for an array A consisting of 20,5,13,7,11 the sum of 20 and 13 is largest of sum of any two numbers. (Yourself) Dr. Yousaf, PIEAS
  • 38. Write program in which declare an array of size 10. Initialize the elements from the user. Find largest and smallest numbers in this array. After the smallest and largest numbers are found, the program should store the largest number at the beginning of the array and smallest number at the end of the array . For example if the name of your array is A, A[0] should contain the largest number and A[N] should contain the smallest number. Write a program in which declare two arrays A and B for 3 integers each, initialize the arrays from the user. The program should display the values of these two arrays and later should exchange the values of A with B i.e. values stored in array A should be replaced by values stored in array B and values stored in array B should be replaced by values stored in array A. It is called swapping. Finally the program should display the new values of A and B. (Hint , for swapping you might need a third array ). (Yourself) Dr. Yousaf, PIEAS