Week 12
Week 12
Introduction
#include <stdio.h>
int addNumbers(int *fiveNumber){
int i,sum=0;
for(i=0; i<5; i++, fiveNumbers++){
sum+= *fiveNumbers
}
return sum;
}
Notation for accessing array
element
• int a[10];
• int *p;
• p=a;
• //4 notations are the same
– a[i]
– *(a+i)
– p[i]
– *(p+i)
Exercise 12.1
• Write a function countEven(int*, int)
which receives an integer array and
its size, and returns the number of
even numbers in the array.
Solution
int counteven(int* arr, int size){
int i;
int count =0;
for (i=0; i<size; i++)
if (*(arr+i)%2==0) count++;
return count;
}
int main()
{
float sales[6];
getSales(sales,6);
printf("The total sales for the
year are:
%0.1f\n",totalSales(sales,6));
return 0;
}
Exercise 12.4 (BTVN)
• Write a program to list all the sub array of
an given array. For example the array 1 3
4 2 has the following sub array:
1
1 3
1 3 4
1 3 4 2
3
3 4
3 4 2
4
4 2
2
Solution
#include<stdio.h>
void main()
{
int a[100],n;
printf("n = "); scanf("%d",&n);
for(int i=0;i<n;i++)
{
printf("\na[%d] = ",i);scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
printf("\n%d",a[i]);
for(int j=i;j<n-1;j++)
{
printf("\n");
for(int k=i;k<=j+1;k++)
printf("%d\t",a[k]);
}
}
}
Exercise 12.5
• Write a program to reverse an array
in two different ways: using indexes
and using pointers.
Solution: array
void reversearray(int arr[], int size){
int i, j, tmp;
i=0; j= size -1;
while(i<j){
tmp=a[i];
a[i]=a[j];
a[j]= tmp;
i++; j--;
}
}
Solution: pointer
void reversearray(int *arr, int size){
int i, j, tmp;
i=0; j= size -1;
while(i<j){
tmp=*(a+i);
*(a+i)=*(a+j);
*(a+j)= tmp;
i++; j--;
}
}
Bài tập về nhà: Mô phỏng
trò chơi
• Một game đối kháng cho phép tạo ra các đấu
thủ (mỗi đấu thủ có ba chỉ số sức mạnh,
nhanh nhẹn, và máu)