How to count the number of repetitions that while does? - objective-c

I am doing a year of college and am having MUCH difficulty at a specific point ....
I need to make a code that reads the population of the U.S. and Brazil, knowing that the population of the U.S. is higher than in Brazil.
The issue is I need to count the number of the while loop, after all if 1 means 1 more year if it is 2 years older is 2 and so on. the code is here and is objective-c...
int pAmericana, pBrasileira, ano;
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSLog(#"What year is it?");
scanf("%i", &Ano);
NSLog(#"which the American people?");
scanf("%i", &pAmericana);
NSLog(#"which the Brazilian people?");
scanf("%i", &pBrasileira);
while (pAmericana >= pBrasileira) {
pAmericana=(pAmericana*0.2)+pAmericana;
pBrasileira=(pBrasileira*0.4)+pBrasileira;
}
//FAILURE TO KNOW HOW TO COUNT HOW OFTEN HAPPENS THE LOOP .....
}
return 0;
}

You can use a counter inside the loop:
int i = 0;
while (pAmericana >= pBrasileira) {
pAmericana=(pAmericana*0.2)+pAmericana;
pBrasileira=(pBrasileira*0.4)+pBrasileira;
i++;
}
NSLog(#"Loop count %i", i);

Adding a count variable to the while loop works. But you can also use a for loop:
int i = 0;
for (; pAmericana >= pBrasileira; i++) {
pAmericana=(pAmericana*0.2)+pAmericana;
pBrasileira=(pBrasileira*0.4)+pBrasileira;
}
NSLog(#"Loop executed %d times", i);
You must declare the variable before the for loop so its value is available after the loop.
Note - you can change the calculations to:
int i = 0;
for (; pAmericana >= pBrasileira; i++) {
pAmericana *= 1.2;
pBrasileira *= 1.4;
}

int i = 0 before the while, i++; in the while loop, NSLog(#"Loops: %d", i); after the loop.

You can declare an integer variable outside the while loop then increment it within the loop, like this:
int i = 0; // Initialise the counter
while (pAmericana >= pBrasileira) {
...
i++; // Increment the counter
}

Related

How do I call functions within this code? Im using the visual studio software. keep getting errors that array1 and 2 are undefined

enter image description here
Sorry im new to coding . I have searched up possible solutions for this on here but they didnt work. Im also confused on why some code appears grey compared to the rest.
https://1drv.ms/w/s!Ag8vVFKVPyOg6HeYLehGjQKdvl_3?e=QHY6t9
#include <stdio.h>
// initialised variables
int i = 0;
int count = 0;
void displayfunction(void);
int month = 0;
void highervalues(float array1[12], float array2[12]);
void highervalues(float array1[12], float array2[12]) {
for (i = 12; i > 0; i--) {
if (array2[i] > array1[i]) {
count = count + 1;
}
}
}
//Reading values for array1 and array2
void displayfunction(void) {
highervalues(array1[12] , array2[12]);
for (i = 0; i < 12; i++)
{
month = month + 1; // month increases by 1 after each input
printf_s("enter values for year 1 month %d", month);
scanf_s("%f", &array1[i]);
}
for (month = 12; month > 0; month--) {
}
for (i = 0; i < 12; i++) {
month = month + 1;
printf_s("enter values for year 2 month %d", month);
scanf_s("%f", &array2[i]);
}
}
/*comapring 2 arrays and increasing count value if there are any value in array2
are greater than array1*/
int main() {
displayfunction();
int array1[12];
int array2[12];
}
You have a fundamental misunderstanding of variable scope
int main() {
displayfunction();
int array1[12];
int array2[12];
}
Those arrays are only available in main. If you want other functions to operate on them you have to pass them as paramters to those functions. Plus they dont exist at the point where you try to call displayFunction
So change
void displayfunction(void)
to
void displayfunction(float array1[12], float array2[12])
then in main do
int main() {
int a1[12];
int a2[12];
displayfunction(a1, a2);
}
Note that I have changed the names here just to emphasise that its the not the fact that the names are the same thats important.

Confusion about my QuickSort algorithm & Mergesort algorithm

I am currently conducting empirical studies to evaluate the run-time complexities of the quicksort, and mergesort algorithms. To do this I run a random number generator that stores whatever amount of numbers I specify in a binary file. The ranges of those numbers are from 1-1,000,000.I then run tests of each algorithm starting from 100,000 numbers, incrementing by 50,000 each time, until 1,000,000 numbers are sorted on the last run. So 20 tests each. I have successfully completed each algorithm but my results are kind of puzzingly. This is a graph showing my results.
I understand that quicksort has a worst case of O(n2) time, but typically O(n·lg(n)) time. Mergesort has Θ(n·lg(n)) time.
Also I would like to note that when I started the timer I just used clock() from time.h, and calculated the time elapsed. I started my timer one line of code before I called my sorting function.
What I dont understand is how my graph shows mergesort is always double the time, and reaching triple the time to sort numbers compared to quicksort.
My only thought is that for my mergesort algorithm every time I divide my array in half I use malloc to create a new integer array for each half. Of course this means a large amount of calls are made to malloc considering the number sizes I am sorting.
int* mergeSort(int* nums, int size){
int* left;
int* right;
int middle = size/2;
if(size <= 1)
return nums;
split(nums, size, &left, &right, middle);
//I dont understand why the code below wouldnt work in place of the split()
//when i run it, in main, nothing gets printed out. I guess i lose my pointer to the beginning of my array.
//left = nums;
//right = nums+middle;
left = mergeSort(left, middle);
right = mergeSort(right, size - middle);
merge(nums,left,right,middle,size - middle);
free(left);
free(right);
return nums;
}
void split(int* nums, int size, int** left, int** right, int middle){
int *lft = (int*) malloc ((sizeof(int) * middle));
int *rght = (int*) malloc ((sizeof(int) * size - middle));
int mid = middle;
int upMid = size - middle;
int i;
for(i=0; i < mid; i++)
lft[i] = nums[i];
for(i=0; i < upMid; i++)
rght[i] = nums[i+middle];
*left = lft;
*right = rght;
}
void merge(int* num, int* left, int* right, int sizeLeft, int sizeRight){
int i,j,k,n;
i=j=k=0;
n=sizeLeft + sizeRight;
while(k < n){
if(i< sizeLeft){
if(j<sizeRight){
insert(num,left,right,&i,&j,&k);
}
else{
append(num, left, sizeLeft, &i, &k);
}
}
else{
append(num,right,sizeRight,&j,&k);
}
}
}
void insert(int* num, int* left, int* right, int* i, int* j, int* k){
/*int i,j,k,n;*/
if(left[*i]<right[*j]){
num[*k] = left[*i];
(*i)++;
}
else{
num[*k] = right[*j];
(*j)++;
}
(*k)++;
}
void append(int* num, int* half, int sizeHalf, int* i, int* k){
while(*i < sizeHalf){
num[*k]= half[*i];
(*i)++; (*k)++;
}
}
I would greatly appreciate any feedback on this question of mine, and any advice on maybe making my mergesort function more efficient. Thanks!!
I have implemented a merge sort algorithm, you can have a look. I malloc a bak array at the beginning of mergeSort and every merge use the it afterwards.
#include <string>
#include <stdlib.h>
void _mergeSort(int *array, int *bakArray, int len) ;
void mergeSort(int *array, int len)
{
int *bak = (int *)malloc(sizeof(int)*len) ;
_mergeSort(array, bak, len) ;
free(bak) ;
}
void _mergeSort(int *array, int *bakArray, int len)
{
if (len >= 2) {
int leftLen = len/2 ;
_mergeSort(array, bakArray, leftLen) ;
_mergeSort(array+leftLen, bakArray, len-leftLen) ;
int *pa = array ;
int *pb = array+leftLen ;
int aIndex = 0 ;
int bIndex = 0 ;
while (aIndex < leftLen && bIndex < len-leftLen) {
int a = pa[aIndex] ;
int b = pb[bIndex] ;
if (a < b) {
bakArray[aIndex+bIndex] = a ;
++aIndex ;
} else if (a == b) {
bakArray[aIndex+bIndex] = a ;
bakArray[aIndex+bIndex+1] = a ;
++aIndex ;
++bIndex ;
} else {
bakArray[aIndex+bIndex] = b ;
++bIndex ;
}
}
if (aIndex < leftLen) {
memcpy(bakArray+aIndex+bIndex, pa+aIndex, sizeof(int)*(leftLen-aIndex)) ;
} else if (bIndex < len-leftLen) {
memcpy(bakArray+aIndex+bIndex, pb+bIndex, sizeof(int)*(len-leftLen-bIndex)) ;
}
memcpy(array, bakArray, sizeof(int)*len) ;
}
}
static const int MaxArraySize = 100 ;
int main()
{
srand(time(NULL)) ;
int array[MaxArraySize] ;
for (int i = 0 ; i < MaxArraySize; ++i) {
array[i] = rand() % 10000 ;
}
mergeSort(array, MaxArraySize) ;
for (int i = 0 ; i < MaxArraySize; ++i) {
printf("%d ", array[i]) ;
}
printf("\n") ;
return 0 ;
}

Prime number algorithm Objective C explanation please

Hi sorry for my bad english, i have a question guys, i'm learning objective c and i'm learning booleans right now, my question is: why when running the second loop in the code, the number 2 is taken as prime, i mean, as i see it p takes the value 2 in the first loop, then d start at 2 but then it says d < p, i think that's p-1 (2-1 = 1), so how that code works, it doesn't make sense, i understand why it works with any other number greater than 2 but i don't get it why it works with the number 2!
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
#autoreleasepool
{
int p, d;
BOOL isPrime;
for (p = 2; p <= 50; p++)
{
isPrime = true;
for (d = 2; d < p; d++)
{
if (p % d == 0)
isPrime = false;
}
if (isPrime == true)
NSLog(#"%i", p);
}
}
return 0;
}
The first loop starts p=2, then the inner loop take d=2 and then check if d<p. This condition is false because d=2 P=2. This means the first inner loop doesn't run and isPrime is always true at the first loop of p.
A prime number is divisible by 1 or itself.
So we check divisibility for all the numbers between 1 and the number.
That is why we start we 2 and till number-1
for(d = 2; d < p; d++ )
Prime numbers are the numbers which are not divisible by any other number.They are divisible by itself only (eg 2,3,5,7)
If we will only check till the half of number, since more than half of number will not divide it.
-(BOOL)checkNumberPrimeNumber:(int)number{
int i; BOOL flag=false;
for (i=2; i<number/2; i++) {
if (number%i==0) {
flag=true;
break;
}
}
if (flag==true) {
NSLog(#"%d is Not Prime Number",number);
}
else{
NSLog(#"%d is Prime Number",number);
}
return YES;
}

Beginner: Can't figure out how to find the min and max values of user inputs from a do...while statement

I'm fairly new to Objective C and have got an assignment that requires me to accept a series of integers from the user and give 5 pieces of information from it:
Number of inputs
Sum of the inputs
Average of the inputs
Smallest of the inputs
Largest of the inputs
I've figured out the first 3 parts, but cannot think of a way to get the min/max numbers. The only way I know how to get min/max is with "if" statements, but not sure how to incorporate them into my code. Any help would be appreciated!
#include <stdio.h>
int main(int argc, const char * argv[])
{
//variables
int input;
int count = -1;
int sum = 0;
float average = 0;
do
{
printf("Enter a number.\n");
scanf("%i", &input);
count++;
sum += input;
average = sum / count;
} while (input != 0);
printf("You entered %i numbers.\n", count);
printf("The sum of your numbers are %i.\n", sum);
printf("The average of your numbers is %f.\n", average);
return 0;
}
Edit: Created a new variable "prevnum" at the front of the "do...while" loop to equal the preceeding input. Used the "prevnum" variable to compare against new inputs and saved min/max values using "if...else" statements. Not sure if it's the most efficient or 'correct' way to do it, but it's functional and gives the right output. Code is as follows:
include
int main(int argc, const char * argv[])
{
//variables
int input = 0;
int count = -1;
int sum = 0;
int average = 0;
int max = 0;
int min = 0;
int prevnum;
do
{
prevnum = input;
printf("Enter a number.\n");
scanf("%i", &input);
count++;
sum += input;
average = sum / count;
if(input >= prevnum && input >= max)
max = input;
else if(input < max)
max = max;
if(input <= min && input <= max)
min = input;
else if(input > min)
min = min;
} while (input != 0);
printf("You entered %i numbers.\n", count);
printf("The sum of your numbers are %i.\n", sum);
printf("The average of your numbers is %i.\n", average);
printf("The largest number entered was %i.\n", max);
printf("The smallest number entered was %i.\n", min);
return 0;
}
Well you could definitely do it with if statements as you explained and just have variables that track the lowest and highest values they have seen so far and update them if the current value is more appropriate.
You can also use a macro. See this answer: How would you define a simple "min" method in obj-c

Codility extreme large Number error

I have a Codility test to take soon.
I was trying to find a modification in the code to avoid EXTREME LARGE NUMBERS ERROR by using LONG instead of INT... but this did not work.
Has anybody tried using CODILITY demo test and get a 100?
I went through previous posts but no solution to this particular problem.
MY CODE: COMPLEXITY O(N)... Still I got 94.
// you can also use includes for example:
// #include <algorithm>
#include<iostream>
#include<vector>
#include<math.h>
int equi ( const vector<int> &A ) {
if((int)A.size()==0)
return -1;
long int sum_l = A[0];
long int total_sum =0;
for(int i =0; i<(int)A.size();i++){
total_sum = total_sum + A[i];
}
int flag =0;
total_sum = total_sum -A[0];
if(total_sum == 0)
return 0;
for(int i=1; i<(int)A.size()-1;i++){
total_sum = total_sum - A[i];
if(sum_l ==total_sum){
flag=1;
return i;
}
sum_l= sum_l + A[i];
}
if(sum_l ==0)
return (int)A.size()-1;
if(flag ==0)
return -1;
}
I used long long, and I had not problem.
Try this one.
int left = A[0];
int right = 0;
for(int i: A){
right += i;
}
right -= left;
int diff = Math.abs(left - right);
for (int i = 1; i < A.length-1; i++) {
left += A[i];
right -= A[i];
int a = Math.abs(left - right);
if(diff > a){
diff = a;
}
}
return diff;