Adding values based on the user's input in array basis - c

I'm stuck with this code:
int main()
{
int a[ ] = {0};
int n,sum = 0;
printf("Enter your element: ");
scanf("%d", &a[n]);
while(n != -1)
{
sum = sum + a[n];
printf("Enter your element: ");
scanf("%d", &n);
}
printf("The sum is %d", sum);
}
My aim is to make a prompt to user to enter his value that will be stored in the elements of the array, then give him the sum of the values that he entered.
However the code does not show any error, but it ends up giving garbage value.

You probably want this:
#include <stdio.h>
int main()
{
int a[100] = { 0 }; // array of 100 numbers all initialized to 0
int sum = 0;
int n = 0;
do
{
printf("Enter your element: ");
int number;
scanf("%d", &number);
if (number == -1)
break;
a[n] = number;
sum += a[n];
n++;
}
while (1);
printf("The sum is %d", sum);
}
Disclaimer: There is no error checking, and there is no check if you entewr more than 100 numbers which results in an index out of range problem.

scanf("%d", &a[n]); accessing array index out of bound if n!=0 this is Undefined Behavior.
And n is uninitialized. So using that as an index is using as index in the array some indeterminate value.
while(n!=1) is not an exhaustive check. better would be n==0 as the array has only 1 element.
Maybe you wanted this
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
printf("Enter no of element: ");
if( scanf("%d", &n) != 1){
fprintf(stderr,"%s","Error in input");
exit(1);
}
if( n <= 0){
fprintf(stderr,"Enter positive number of elements");
exit(1);
}
int a[n];
int sum = 0;
for(size_t i = 0; i < n; i++){
if( scanf("%d",&a[i]) != 1){
fprintf(stderr,"%s","Error in input: give integers");
exit(1);
}
sum+=a[i];
}
printf("The sum is %d", sum);
}
Notice that this program has the following flaws which is difficult to overcome with scanf() - you can try to modify over this using strtol and overflow-checking
If user inputs something other than this range [INT_MIN,INT_MAX], thre will be overflow. (Soln: Use strtol)
Sum can overflow given any large inputs whose sum is not in this range.
(Overflow check:
if ((a[i] > 0 && sum > INT_MAX - a[i]) || (a[i] < 0 && sum < INT_MIN - a[i]))
{
fprintf(stderr,"%s","Sum has overflown");
exit(1);
}

Related

Why doesn't my code work for special cases?

I wrote up a piece of code to find whether a number is prime or not and here it is.
#include <stdio.h>
void main() {
int i, n;
printf("Enter value for n: ");
scanf("%d", &n);
if (n <= 3) {
printf("It is a prime number");
}
for (i = 2; i < n; i++) {
if (n % i == 0) {
printf("It's not prime number \n");
break;
} else {
printf("It is a prime number \n");
break;
}
}
}
However, when my input is 33, instead of the output printing It's not a prime number, since 33 is divisible by 3 and 11, it prints that It is a prime number.
What is the problem with my code here?
In your code, the first time the for loop is executed it immediately triggers either the if condition or else, then breaks, reaches the end and returns. The loop runs a total of 1 iteration max. Change to the following:
for (i = 2; i <= n / i; i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("It is a prime number \n");
Here the for runs correctly. It checks for all dividends, only then it's over and prints the false condition. Note you can optimize your code and only check up to the square root of n, because after that it can't hit true.
And add a return statement here, because the program is already over and doesn't need to continue:
if (n <= 1){
printf("It's not a prime number");
return 0;
}
if (n <= 3){
printf("It is a prime number");
return 0;
}
This also screens off 0, 1, and negative integers which are not prime numbers.
You almost got it right: you just have to make sure the program exits after having established whether a number is prime.
Also, you can stop the loop at n/i.
Last, but not least: main should return a int.
#include <stdio.h>
int main(void){
int i,n;
printf("Enter value for n: \n");
scanf("%d", &n);
if (n <= 3){
printf("It is a prime number\n");
return 0;
}
for (i = 2; i < n/i; i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("It is a prime number \n");
return 0;
}
There are multiple problems:
void main() should be int main()
you should check the return value of scanf and reject negative numbers
0 and 1 are not considered prime numbers.
you should end the program if the number matches the first test.
you output the result after a single test: it is correct if the test if (n % i == 0) is true as you have found a divisor, but if you have not, you should iterate, testing all possible divisors up to and including floor(sqrt(n)).
Here is a modified version:
#include <stdio.h>
int main() {
int i, n;
printf("Enter value for n: ");
if (scanf("%d", &n) != 1) {
printf("input error, not a number\n");
return 1;
}
if (n < 0) {
printf("number should be positive: %d\n", n);
return 1;
}
if (n <= 1) {
printf("%d is not a prime number\n", n);
return 0;
}
for (i = 2; i < n / i; i++) {
if (n % i == 0) {
printf("%d not prime number (divisible by %d)\n", n, i);
return 0;
}
}
printf("%d is a prime number\n", n);
return 0;
}
You might want to try this:
#include <bits/stdc++.h>
int main(){
int i,n;
printf("Enter value for n: ");
scanf("%d", &n);
if (n <= 1){
printf("It is a prime number");
}
for (i = 2; i <= sqrt(n); i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("A prime Number");
return 0;
}
This is happening because in your code for i = 3 and n = 33, if condition is failing which leads to else block directly and hence you are getting output as "It is a prime number".

How to get min/max value from 10 numbers with a loop? (C language)

Hi im fairly new in programming and started with C language and now im stuck with loops.
The problem is that I try to write a program that has to get an input value of 10 INT numbers that are greater than 20, and after that the program has to determine which of the numbers is the maximum and which is minimum. at the end it has to calculate the average of all numbers.
So now I managed to get only the average calculation to work correctly, and the main problem is the max/min values.
#include<stdio.h>
void main()
{
//Variables
int num, i = 1, cnt = 0, sum = 0, max = 0, min = 0;
float average;
printf("Enter 10 int numbers greater than 20:\n");
//Input check
while (i <= 10)
{
printf("\n%d) ", i);
scanf("%d", &num);
max = num;
min = num;
if (num <= 20)
{
printf("Wrong number! enter an integer greater than 20:\n");
continue;
}
i++;
sum += num;
cnt++;
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
//Average calculation and output
average = sum / (float)cnt;
printf("The maximum number is: %d\n", max);
printf("The minimum number is: %d\n", min);
printf("The average of all numbers is: %.2f\n", average);
}
Here is a quick check game in c that asks for few numbers and then when you enter 0 it shows you the lowest and highest number in the array (number collected)
int main(){
int a, max = 0, min;
char answer;
while(answer != 'n')
{
for(int i = 0; i < 100; i++){
printf("Enter Number:");
if (scanf("%d", &a) == 1)
{
if(a == 0) //check if the input value is 0 then break the loop
break;
else
{
if(a > max)
max = a;
if(a < min)
min = a;
}
}
}
printf("lowest: %d, highest: %d", min, max);
printf("\nWould you like to start over? (j/n): ");
scanf("%s", &answer);
max = 0;
//min=0;
if(answer == 'n')
break;
}
return 0;
}

C loop until 0 is given

I'm trying to make a loop that lets the user enter numbers one by each other and calculate the sum of all those numbers until the user enters 0 as an input. However, my code is running only once and then stops.
#include <stdio.h>
int main(void) {
int i = 0;
int num;
int total = 0;
printf("Give me a number \n");
scanf("%d", num);
if(num < 0 && num > 0){
printf("Give me a number \n");
scanf("%d", num);
total = total + num;
i = i + 1;
}
printf("The total is %d", total);
}
There are no loops in your code
The condition (num < 0 && num > 0) is alway false. A number can't be: less than zero AND greater than zero
Wrong call of scanf
You probably want:
printf("Give me a number \n");
if (scanf("%d", &num) != 1) exit(1);
while(num != 0){
total = total + num;
i = i + 1;
printf("Give me a number \n");
if (scanf("%d", &num) != 1) exit(1);
}
The above solution will exit the program if the user inputs a non-integer, e.g. a letter.
An alternative solution that will end the loop on non-integer input is:
printf("Give me a number \n");
while(scanf("%d", &num) == 1 && num != 0){
total = total + num;
i = i + 1;
printf("Give me a number \n");
}
This last solution can even be written a little more compact - like:
while(printf("Give me a number \n"), scanf("%d", &num) == 1 && num != 0){
total = total + num;
i = i + 1;
}
It's a bit harder to read but avoids duplicated lines.
This is the idiomatic way IMO. There is only one scanf call to scanf and we use break to end the loop prematurely if the user has entered 0.
#include <stdio.h>
int main() {
int i = 0;
int num;
int total = 0;
while (1) // loop forever
{
printf("Give me a number \n");
scanf("%d", &num);
if (num == 0) // if the number is 0
break; // we terminate the loop
total = total + num;
i = i + 1;
}
printf("You entered %d numbers, the total is %d", i, total);
}
Disclaimer:
for brevity there is no error check for scanf which IMO is OK for toy programs.
Otherways the remarks provided by 4386427 in his answer are correct.
Make sure to take the address of the variable (&num) in the scanf() call and add a do{ } while() statement.
int main(){
int i = 0;
int num;
int total =0;
do {
printf("Give me a number \n");
scanf("%d", &num);
total = total + num;
i = i + 1;
} while(num != 0);
printf("The total is %d", total);
}
the problem is in the if statement you are trying to check if the given number (num) is at once greater than 0 and less than 0 which is why the if scope won't be accessed u can use the following if statement
if(num!=0)
this will check if the num is different than zero!
and since you are trying to repeat this bloc until 0 is inserted you have to use a while/dowhile instead.
you have also to pay attention to the scanf because you forgot to specify the pointer of the num variable (scanf("%d", &num);)
In your case, use of while (num != 0) would be more suitable.
int main(){
int i = 0;
int num = 1;
int total = -1;
while (num != 0){
printf("Give me a number \n");
scanf("%d", &num);
total = total + num;
i = i + 1;
}
printf("The total is %d", total);
}

Program C counting total number of odd digits

I'm writing a C program that counts the number of odd digits from user input.
Eg.
Please enter the number: 12345
countOddDigits(): 3
int countOddDigits(int num);
int main()
{
int number;
printf("Please enter the number: \n");
scanf("%d", &number);
printf("countOddDigits(): %d\n", countOddDigits(number));
return 0;
}
int countOddDigits(int num)
{
int result = 0, n;
while(num != 0){
n = num % 10;
if(n % 2 != 0){
result++;
}
n /= 10;
}
return result;
}
The code is not working.
Can someone tell me where does it go wrong?
There were a few mistakes in your code. Here is a working version of your code:
#include <stdio.h>
int countOddDigits(int n);
int main()
{
int number;
printf("Please enter the number: \n");
scanf("%d", &number);
printf("countOddDigits(): %d\n", countOddDigits(number));
return 0;
}
int countOddDigits(int n)
{
int result = 0;
while(n != 0){
if(n % 2 != 0)
result++;
n /= 10;
}
return result;
}
You are mixing n and num together - there is no need for two variables.
n%=10 is just causing mistakes - you need to check the last digit if(n%2!=0) and then move to the next one n/=10, that's all.
Looping variable is not correct. Your outer loop is
while (num !=0)
but the num variable is never decremented; the final statement decrements the n variable. My guess is you want to initialize
int n = num;
while (n != 0 )
{ ...
n/= 10;
}

C program for assigning elements of a matrix without letters

I'm having trouble outputting an invalid statement if the user inputs a letter instead of a number into a 2D array.
I tried using the isalpha function to check if the input is a number or a letter, but it gives me a segmentation fault. Not sure what's wrong any tips?
the following code is just the part that assigns the elements of the matrix.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main() {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
scanf("%d", &n);
if (n <= 1 || n >= 11) { // can't be bigger than a 10x10 matrix
printf("Invalid input.");
return 0;
}
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (!isalpha(matrix[i][j])) { // portion I'm having trouble with
continue;
} else {
printf("Invalid input.");
return 0;
}
}
}
...
As the value of n will be number, we can solve it using string instead of int.
char num[10];
int n;
scanf("%s", num);
if(num[0] < '0' || num[0] > '9' || strlen(num) > 2){
printf("invalid\n");
}
if(strlen(num) == 1) n = num[0] - '0';
if(strlen(num) == 2 && num[0] != 1 && num[1] != 0) printf("invalid\n");
else n = 10;
Also we can use strtol() function to convert the input string to number and then check for validity.You can check the following code for it. I have skipped the string input part. Also you have to add #include<stdlib.h> at the start for the strtol() function to work.
char *check;
long val = strtol (num, &check, 10);
if ((next == num) || (*check != '\0')) {
printf ("invalid\n");
}
if(val > 10 || val < 0) printf("invalid\n");
n = (int)val; //typecasting as strtol return long
You must check the return value of scanf(): It will tell you if the input was correctly converted according to the format string. scanf() returns the number of successful conversions, which should be 1 in your case. If the user types a letter, scanf() will return 0 and the target value will be left uninitialized. Detecting this situation and either aborting or restarting input is the callers responsibility.
Here is a modified version of your code that illustrates both possibilities:
#include <stdio.h>
#define MAX 10
void display(int matrix[][MAX], int size);
int main(void) {
int n, degree;
int matrix[MAX][MAX];
printf("Enter the size of the matrix: "); // assigning size of the matrix
if (scanf("%d", &n) != 1 || n < 2 || n > 10) {
// can't be bigger than a 10x10 matrix nor smaller than 2x2
// aborting on invalid input
printf("Invalid input.");
return 1;
}
for (int i = 0; i < n; i++) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; j++) {
if (scanf("%d", &matrix[i][j]) != 1) {
// restarting on invalid input
int c;
while ((c = getchar()) != '\n') {
if (c == EOF) {
printf("unexpected end of file\n");
return 1;
}
}
printf("invalid input, try again.\n");
j--;
}
}
}
...
The isdigit() library function of stdlib in c can be used to check if the condition can be checked.
Try this:
if (isalpha (matrix[i][j])) {
printf ("Invalid input.");
return 0;
}
So if anyone in the future wants to know what I did. here is the code I used to fix the if statement. I am not expecting to put any elements greater than 10000 so if a letter or punctuation is inputted the number generated will be larger than this number. Hence the if (matrix[i][j] > 10000). May not be the fanciest way to do this, but it works and it's simple.
for (int i = 0; i < n; ++i) { // assigning the elements of matrix
printf("Enter the row %d of the matrix: ", i);
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
if (matrix[i][j] > 10000) { // portion "fixed"
printf("Invlaid input");
return 0;
}
}
}
I used a print statement to check the outputs of several letter and character inputs. The lowest out put is around and above 30000. So 10000 I think is a safe condition.

Resources