L-29 MCS 260 Fri 26 Oct 2001
/* L-29 MCS 260 Fri 26 Oct 2001 : counting positive and negative numbers
The program below reads a sequence of integer numbers from input
and counts the number of positive and negative numbers.
Zeros are ignored. The reading stops when a character or
EOF is encountered (either this happens when the program
runs with redirection or when the user hits return followed
by control d on UNIX, or a control z in MS-DOS).
We use a function with call-by-reference to do the counting.
Besides another good use of call-by-reference, we emphasize
the precedence of operators :
*pos++ is equivalent to *(pos++), which is not what we
want in this application. Therefore we must use brackets to
update the counter for positive numbers and write (*pos)++. */
void count ( int n, int *pos, int *neg );
/* increments *pos when n > 0, or *neg when n < 0 */
#include<stdio.h>
int main ( void )
{
int a, pos_cnt = 0, neg_cnt = 0;
printf("Give a sequence of integers : ");
while (scanf("%d", &a) > 0)
count(a,&pos_cnt,&neg_cnt);
printf("Number of positive numbers read : %d\n", pos_cnt);
printf("Number of negative numbers read : %d\n", neg_cnt);
return 0;
}
void count ( int n, int *pos, int *neg )
{
if (n > 0)
(*pos)++; /* we must use brackets ! */
else if (n < 0)
(*neg)++;
else
; /* we do not count zero */
}
/* L-29 MCS 260 Fri 26 Oct 2001 : variables inside a block
Sometimes we wish to declare and use a variable only when we really
need it. The program below is an illustration of such a use. */
#include<stdio.h>
int main ( void )
{
int n, sum = 0;
printf("Summing a sequence of integers.\n");
printf("Give the number of integers in the sequence : ");
scanf("%d", &n);
{
int i; /* here we need i for the loop */
printf("Give %d numbers : ", n);
for (i = 0; i < n; i++)
{
int nb; /* nb exists only inside the loop */
scanf("%d", &nb);
sum += nb; /* we do not need nb after the loop */
}
}
printf("The sum of the numbers : %d\n", sum);
return 0;
}
/* L-29 MCS 260 Fri 26 Oct 2001 : scope rules
The program below is a slight modification of the previous program:
the variable "nb" declared inside the for loop has now name "i",
just like the "i" outside the for loop. Although this is really not
a good coding practice, the program works just as well.
Inside the for loop, we use the inner "i" as a local variable,
the outer "i" is not visible inside the loop, but that does not
matter since the outer "i" is only used to control the loop. */
#include<stdio.h>
int main ( void )
{
int n, sum = 0;
printf("Summing a sequence of integers.\n");
printf("Give the number of integers in the sequence : ");
scanf("%d", &n);
{
int i; /* outer i controls the loop */
printf("Give %d numbers : ", n);
for (i = 0; i < n; i++)
{
int i; /* this i is different for the other i */
scanf("%d", &i);
sum += i; /* here we lose the inner i */
}
}
printf("The sum of the numbers : %d\n", sum);
return 0;
}