Jump to content

A few (basic) questions

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
Razzie89

Razzie89

    Newbie

  • Members
  • Pip
  • 1 posts
I want to help a friend of mine who just started learning programming in C, but has problems catching up because he doesn't have any previous knowledge of it. I myself know vb.NET but never programmed in C, so I can't help. :(

Some things that are asked:

- A program which counts vowels in a given text using switch.case.
(Similar to VB's "select case"? How to write this?)

- A program that calculates powers (ex. 3^4 when 3 and 4 are given by the user) without using pow(a,b).
I was thinking of writing something like A*((B-1)* "*A"), which would probably work in VB but how do you write this correctly in C?

- A program in which the user enters an amount of numbers, then it returns the minimum, maximum and average value when -1 is entered.
I asked another friend of me about this and he wrote down the following code, but we were unable to test it. Would it work?

#include <stdio.h>
int main(void)
{
int min = 0;
int max = 0;
int sum = 0;
int count_numbers = 0;

int read_number = -1;
scanf(“%d”, &read_number);

int min = read_number;
int max = read_number;
int sum = read_number

while (read_number != -1){
if(read_number < min)
min = read_number;
else if(read_number> max)
max = read_number;
sum+= read_number;
count_numbers++;
scan
f(“%d”, &read_number);
}
printf(“min %d”, min);
printf(“max %d”, max);
printf(“average %d”, sum/count_numbers);
}
scanf

If there is anyone who would be willing to help in any way, by writing down the code (and if possible a little bit of explanation) I would be really grateful. Thanks a lot in advance!

#2
G_Morgan

G_Morgan

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 537 posts
The power is easy using recursion

[HIGHLIGHT="C"]float power(float base, int index){
assert(index >= 0);
if(index == 0)
return 1;
return base * power(base, index - 1);
}[/HIGHLIGHT]

This only works for an integer index greater than or equal to 0.

As for switch statements. They can be done as follows

[HIGHLIGHT="C"]
switch(current_char){
case('a'):
/*action*/
break;
case('e'):
/*action*/
break;
...
default:
/*default action*/
break;
}
[/HIGHLIGHT]

The breaks ensure that only one case is executed.