I need to make a C program to read the number of students(1<=students<=25) in a class and for every student to read his exam score ex 10/20 15/20 etc(1<=score<=20) and print the max and the max score of students and the average score of class.
I made the program but it performs the for loop only once for some reason.
Can you please help me understand why?
here is the code :
#include <stdio.h>
int main(void) {
int m,i,b,sum,min,max,mo;
sum=0;
while (m<1 || m>25) {
printf("give number of students ");
scanf("%d",&m);
}
for (i=1; i<(m+1); i++) {
while (b<1 || b>20) {
printf("give score of %d student",i);
scanf("%d",&b);
}
if(i==1) {
min=b;
max=b;
}
else {
if(b<min) min=b;
if(b>max) max=b;
}
sum=sum+b;
}
mo=sum/m;
printf("max is %d and min is %d and avg is %d",max,min,mo);
}
First - initialize your variables:
int m,i,b,sum,min,max,mo; // these are declared and uninitialized
m = 0; // now it's initialized to 0
i = 0;
...
If you don't initialize them to something, you don't know what they are to start with.
Second - You need to change the value of b:
for (i=1; i<(m+1); i++) {
while (b<1 || b>20) { <-- here you're checking for b being valid
printf("give score of %d student",i);
scanf("%d",&b);
}
So the first time in b will be between 1 and 20, if you don't reset it to something invalid you'll never get here again. After you record the value of b:
sum=sum+b;
b = 0; // we're done with b for now, set it to something invalid for the while()
}
Not initialized the m and using in while condition
It is undefined behaviour using uninitialized local variable in conditon
Want to implement the same
use
do
{
printf("give number of students ");
scanf("%d",&m);
}
while(m<1 || m>25);
for (i=1; i<(m+1); i++) change the condition as i<=m It's the good technique rather < and then adding 1
Inside this loop use the same do while loop
You forgot to initialize the B variabkle, so it loops m times, never asking you to insert a score!
1. You initialize 'm' here, without any prior value
int m,i,b,sum,min,max,mo;
2. Without a value, you check for this condition. Which means, a garbage value would be used. (May/May not fulfill your condition)
while (m<1 || m>25) {
3. The crucial scanf for m is inside the previous while. Without which your FOR would run for a basic i=1 and stop.
for (i=1; i<(m+1); i++) {
You need to understand about Garbage Values in C and vital step of initializing a variable to an initial value before using it.
You may read more on this link:
What is a garbage value/How does it occur in C
Related
So I'm trying to make an array with multiple values.
However, I want the user to be able to not only decide each value, but how many values are in the array itself.
The program doesn't seem to work, though.
Issue at hand is that every time I run my code it runs just fine until it gets to the for loop. The code allows me to input one value but then just exits with the following message:
Process returned 5 (0x5) execution time : 2.656 s
I've tried a couple of other methods but none of them seem to work.
Here's my latest attempt
// Initiate variable
int iterations;
printf("Input amount of values: ");
scanf("%d",&iterations);
fflush(stdin);
int listOfValues[iterations];
fflush(stdin);
int i;
int tempvar;
printf("Input values in order: ");
for (i = 0; i < iterations; i++);
{
scanf("%d",&tempvar);
fflush(stdin);
listOfValues[i] = tempvar;
}
What am I doing wrong here?
Please keep in mind I'm still in the stage of learning C and programming in general, so be gentle!
it a small mistake just remove the semicolon after the for loop.
like this:
// Initiate variable
int iterations;
printf("Input amount of values: ");
scanf("%d",&iterations);
fflush(stdin);
int listOfValues[iterations];
fflush(stdin);
int i;
int tempvar;
printf("Input values in order: ");
for (i = 0; i < iterations; i++)
{
scanf("%d",&tempvar);
fflush(stdin);
listOfValues[i] = tempvar;
}
if we put a semicolon after the for statement it will run just once
hope this helped
I've started learning C. I'm doing functions right now.
In these exercise they want me to ask for a value that means an error. If they input the number 8, it means that it's error "8", if value 6 error is "6"(the error part don't matter). I should call a fuction to store this error and other functio to go trought it and see if any value ("error"), Was stored more than once.
I started by asking for how many errors the user will introduce, soo I could run a loop "N" times to ask for the value.
Then I made a function called aviso(means warning ~ error), to store them in a array.
When the function reaches the last value of "error" it calls other function to count if the numbers are repeated .
My main problem right now is how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output is like array[0] = -32134123.
So my function is not storing any value in the array.
My code is very messy right now, please any suggestions are welcome since I'm clearly very new at C.
Excuse my code I just "try" to translate some names to english.
`
#include <stdio.h>
#include <stdlib.h>
// Function Incomplete since my array is not sotring values
int alertwarning(int array[]){
for(int i = 0; i < sizeof(array)/sizeof(int); i++){
}
}
int warning(int num , int n, int count){
int check = count - 1 , array[n];
if(count <= n){
array[check] = num;
}
if(count == n){
alertwarning(array);
for(int i = 0; i < sizeof(array)/sizeof(int); i++){
}
}
return 0;
}
int main(int argc, char *argv[]) {
int num, count, n;
printf("|Warning System!|(Only values equal or above 0 are acepted!)\n");
printf("\nIntroduce how many warnings are being stored: ");
scanf("%d", &n);
fflush(stdin);
int array[n];
do{
printf("\nIntroduce a value equal or bigger then 0: ");
scanf("%d", &num);
fflush(stdin);
//system("cls");
if(num < 0){
printf("|Please introduce a valuer equal or above 0!|\n");
system("pause");
}
else if(num >= 0){
count++;
}
warning(num, n, count);
}while( count < n);
return 0;
}
`
I tried to store the array inside the main() and it worked but it was required to do it in other function to complete this exercise. I don't know if the function just don't save the values of the last time it was called.
how to store the values in the array and keeping them. Every time I introduce a value in the array it happear other like: array[0] = 7 the output is like array[0] = -32134123.
So my function is not storing any value in the array.
I tried printf to see where I go wrong with the few knowledge I own. When they are called they work but the next time they are called I think they reset the values of the array.
I'm trying to solve Star problem. And I always thought it's good practice not to declare empty variable in the beginning.
when I declare variables and assign some value at the beginning it doesn't work
here is the code where i=1,j=1,space=1
#include<stdio.h>
int main()
{
int i=1,space=1,j=1,rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i;i<=rows;i++)
{
for(space;space<=rows-i;space++)
{
printf(" ");
}
for(j;j<=2*i-1;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
BUT when I only declare variables and assign value in for loop it does work
#include<stdio.h>
int main()
{
int i,space,j,rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1;i<=rows;i++)
{
for(space=1;space<=rows-i;space++)
{
printf(" ");
}
for(j=1;j<=2*i-1;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Why it's happening? I always thought it's a good practice to declare variables and assign some value to them
In first case space and j doesn't reinit in parent for loop, while in the second example every parent loop iteration you reassign j = 1 and space = 1
So, on start of second iteration j and space will be the same as were on the finish of first iteration, so nested loops won't work
I'm writing a program that requires me to do a union of two arrays. Here is my code so far.
I get Segmentation fault as an error after I enter set A.
#include <stdio.h>
void Union(int a[], int b[], int set1, int set2)
{
int u[20], i, j, unionIndex=0,trigger;
for(i=0; i<set1; i++)
{
u[unionIndex] = a[i];
unionIndex++;
}
for(i=0; i<set2; i++)
{
trigger=0;
for(j =0; j<set1; j++)
{
if(b[i] == u[j])
{
trigger =1;
break;
}
}
if(trigger =0)
{
u[unionIndex]=b[i];
unionIndex++;
}
}
for(i=0;i<unionIndex;unionIndex++)
{
printf(" %d",u[i]);
}
}
int main(void) {
int N=0;
int M=0;
int i;
int j;
printf("Please enter the number of elements in set A: ");
scanf("%d",N );
int a[N];
printf("Enter the numbers in set: ");
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
printf("Please enter the number of elements in set B: ");
scanf("%d",M );
int b[M];
printf("Enter the numbers in set: ");
for(j=0;i<M;i++)
{
scanf("%d",&b[i]);
}
Union(a,b,N,M);
return 0;
}
I'm pretty sure the issue has something to do with arrays because the program will compile but i get the error right after the user enters set A. I'm a beginner at C but I know a lot more about Java, so I'm thinking this has something to do with memory allocation. I'm not really sure how to solve the issue, so if you could point me in the right direction that would be helpful.
You need to pass the address of the variable to scanf()
Change
printf("Please enter the number of elements in set A: ");
scanf("%d",N );
to
printf("Please enter the number of elements in set A: ");
scanf("%d", &N);
Same goes for other place
printf("Please enter the number of elements in set B: ");
scanf("%d", &M);
There is another possible mistake
Its here
for(j =0; j<set1; j++)
{
if(b[i] == u[j])
In this set1 is equal to N, so j will go from 0 to N-1. And array u[] has only 20 elements. There is a possibility of array access out of bound if some user enter value more then 20 for N.
The problem, as I see it is in
scanf("%d",N );
and
scanf("%d",M );
It invokes undefined behavior as scanf() needs the argument to a format specifier to be a pointer to the type.
Just to clarify, you're essentially passing the address as 0 (value of the variable), which is not a valid addres, anyway.
You need to pass the address there, like
scanf("%d", &N );
and
scanf("%d", &M );
That said, in your Union() function, you're using a user-defined value to limit the for loop, against a constant value 20. In case the user input is more than 20, you'll be overrunning the memory which invokes undefined behavior.
The reason you're getting the segmentation fault is because of how you're calling scanf when reading in N and M. The %d format specifier for scanf expects an int *, i.e. the address of an int, but you're passing in an int. This is undefined behavior.
So you can fix them like this:
scanf("%d",&N );
....
scanf("%d",&M );
Some addtional bugs:
When looping to read in the values for b:
for(j=0;i<M;i++)
{
scanf("%d",&b[i]);
}
You have the wrong loop indexes:
for(j=0;j<M;j++)
{
scanf("%d",&b[j]);
}
When checking trigger:
if(trigger =0)
This is an assignment, not a comparison:
if(trigger == 0)
When looping to print out u:
for(i=0;i<unionIndex;unionIndex++)
You're incrementing the wrong variable:
for(i=0;i<unionIndex;i++)
Finally, u need to have a length of at least set1 + set2, otherwise you risk writing off the end of the array:
int u[set1+set2];
Fix those and you should get the desired results.
I'm trying to write a simple program that'll prompt the user to enter N numbers, store them in an array, then just sum them all up
I understand I can just do this with a recursion but I'm trying to learn how array works
Example:
1 (hit enter)
2 (hit enter)
...
10 (hit enter)
Expected output: 55
#include <stdio.h>
int main (void){
int n;
int a[n];
int counter;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
printf("OK! now enter your number: \n");
for (int i = 0; i <= n; i++){
scanf("%d", &a[i]);
counter =+ a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
Right now there's no error message, no output, just the standard windows error message
"scanner.exe has stopped working..."
I'm using Win8 and GCC compiler
First of all, you can't create an static array without first knowing its size. You first need to ask the user for the "n" variable and then declare your array.
You also need to explicitly initialize your counter variable to be zero before you start counting. In C, variables don't default to 0 when you declare them.
The operator "=+" doesn't exist AKAIK, change it to "+=".
Last but not least, the limit in your loops is a little off, you're asking for 11 values ;)
(I edited this post, I was wrong about only asking for 9 values. I tend to confuse that sort of stuff)
#include <stdio.h>
int main (void){
int n;
int counter = 0;
printf("How many numbers do you want to enter? \n");
scanf("%d", &n);
int a[n];
printf("OK! now enter your number: \n");
for (int i = 0; i < n; i++){
scanf("%d", &a[i]);
counter += a[i];
}
printf("The answer is: %d\n", counter);
return 0;
}
You are using variable length arrays. At run time the value of n must be known. Place the declaration
int a[n];
after taking input for n, i.e, after scanf("%d", &n); and initialize counter to zero before using it otherwise you will get garbage value (because of undefined behavior).
Also change the for loop condition from i <= n to i < n.
After this line:
int n;
What do you think the value of n is?
Now go to the next line:
int a[n];
How big is this array?
Can you access it properly?