I am a beginner with coding and I got my code to compile but when I input integers, I get segmentation fault. Please help.
The problem is: I need to first get how many students there are then the next inputs will be the marks of those students. So if inputed 3, the next inputs should be 3 marks of the 3 students. Then the input should be either g(girl) or b(boy). From there, if boy, I need to sum up all the odd marks.
THIS IS MY CODE:
#include<stdio.h>
#include<stdlib.h>
int marks_summation(int* marks, int number_of_students, char gender){
int i=0, sum=0;
int marksforGirls=0, marksforBoys=0;
char g;
for(marks = 0; *marks <= number_of_students; marks++){
if(gender == g){
do{
if(marks[i]%2 == 0){
marksforGirls = marks[i];
i++;
sum += marksforGirls;
}
} while(*marks<=number_of_students);
}
else{
do{
if(marks[i]%2 != 0){
marksforBoys = marks[i];
i++;
sum += marksforBoys;
}
} while (*marks<=number_of_students);
}
}
return 0;
}
int main(){
int i=0, number_of_students=0;
int *marks=0;
int sum=0;
char gender;
scanf("%d",&number_of_students);
marks = (int*)malloc(number_of_students * sizeof(int));
for(i=0; i<number_of_students; i++){
scanf(" %d", &marks[i]);//for every marks put in, it will go into marks
}
scanf("%c",&gender);
marks_summation(marks, number_of_students, gender);
printf("%d", sum);
free(marks);
return 0;
}
The following line is not doing what you might think it does:
for(marks = 0; *marks <= number_of_students; marks++)
I believe you'd want to use an index to access each of marks elements.
As others have pointed out, the problem is in the for loop. Besides pointers being wrong, your loop condition is also wrong. Furthermore your function doesn't return anything. Also, both of your do-while loops are infinite loops.
Try this:
int mark_sum(int *marks, int number_of_students, char gender){
int sum = 0;
for(int i = 0; i < number_of_students; ++i){
if(gender = 'g'){
if(marks[i] % 2 == 0)
sum += marks[i];
} else {
if(marks[i] % 2 != 0)
sum += marks[i];
}
}
return sum;
}
Also, in main you need to actually store the value returned by the function:
int sum = mark_sum(marks, number_of_students, gender);
Related
I'm trying to solve a problem (as the title already state). I've actually learned that I can do it with modulo operator (%). But the first code that I wrote is using the while-loop, so I'm trying to finish the code.
This is the code
int main()
{
char arr[1000000];
int i = 0;
int sum = 0;
printf("type the number = ");
scanf("%s", arr);
while(arr[i] != '\0'){
sum = arr[i] + sum;
i++;
}
printf("the total number is = %d", sum);
so the problem is it's actually printing out some huge amount of number.. I guess it's because of the array is in char, can someone help me how do I changed the value into int ?
You need to substract from the digit code the code of '0'.
Here you have the both versions (I have added some logic to accept the numbers with + & - at there beginning):
int sumdigitsStr(const char *num)
{
int sum = 0;
int first = 1;
while(*num)
{
if(isdigit(*num)) {sum += *num - '0'; first = 0;}
else
if(first && (*num == '-' || *num == '+'))
{
first = 0;
num++;
continue;
}
else
{
sum = -1; break;
} //error string contains non digits
num++;
}
return sum;
}
int sumdigits(long long num)
{
int sum = 0;
do
{
sum += abs((int)(num % 10));
}while((num = num / 10));
return sum;
}
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
int d, sum = 0;
while (n != 0)
{
d = n % 10;
sum = sum + d;
n = n / 10;
}
printf("sum of digits is : %d", sum);
return 0;
}
Trying to make a code that gets the factorial of the inputted number.
int factorial(int number, int i)
{
int endval;
for(i = number - 1; i>0; i--){
endval = number * i;
}
if (endval == 0){
printf("1");
}
return endval;
}
int main()
{
int endvalue, numA, numB;
char userchoice[1];
printf("Enter a choice to make (f for factorial): \n");
scanf("%s", userchoice);
if(strcmp(userchoice, "f")== 0){
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA, numB);
printf("%d", endvalue);
return 0;}
getch();
return 0;
}
For some reason the whole for loop doesn't do anything in the function when I set the answer (number*i)= endval. It just prints out the same number I inputted and gives me an absurd answer for 0!.
int factorial(int number, int i)
{
int endval;
for(i = number - 1; i>0; i--){
endval = number * i;
}
if (endval == 0){
printf("1");
}
return endval;
}
However the code works perfectly fine when I remove endval variable entirely (with the exception that it gets 0! = 10)
int factorial(int number, int i)
{
for(i = number - 1; i>0; i--){
number = number * i;
}
if (number == 0) {printf("1");}
return number;
}
Is there anything I missed in the code that's causing these errors?
A definiton of factorial is:
factorial(0) = 1
factorial(n) = n * factorial(n-1)
Note: Factorial is legal only for number >= 0
In C, this definition is:
int factorial(int number)
{
if (number < 0)
return -1;
if (number == 0)
return (1);
/*else*/
return (number * factorial(number-1));
}
#include <stdio.h>
#include <string.h>
int factorial(int number)
{
int endval=1;
for(int i = number ; i>0; i--){
endval *= i;
}
return endval;
}
int main()
{
int endvalue=0;
int numA=0;
char userchoice[1];
printf("Enter a choice to make (f for factorial): ");
int ret=scanf("%s", userchoice);
if (!ret){
printf("Error in scanf: %d", ret);
}
if(strcmp(userchoice, "f")== 0){
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA);
printf("%d", endvalue);
return 0;
}
getchar();
return 0;
}
Code with some changes will work
factorial() function can get only one argument.
As a good habit all variables must be initialized.
Add include statement to source and be explicit not rely on compiler.
As we use strcmp() we must include string.h
use standard getchar() instead of getch()
Also can check return value of library function scanf() to ensure reading is correct or not.
You can use warnings from compiler to get most of above notes. In gcc: gcc -Wall code.c
Use a debugger to run program line by line and monitor variables value in each steps or use as many printf() to see what happens in function call.
There are possibly few things to correct. See please attached code.
int factorial(int number)
{
if (number == 0){ return 1; }
int endval=1, i;
for(i = 1; i<=number; i++) { endval *= i; }
return endval;
}
int main() {
int endvalue, numA;
char userchoice[1];
printf("Enter a choice to make (f for factorial): \n");
scanf("%s", userchoice);
if(strcmp(userchoice, "f")== 0) {
printf("Enter a value to get it's factorial: ");
scanf("%d", &numA);
endvalue = factorial(numA);
printf("%d", endvalue);
return 0;
}
getch();
return 0;
}
I am trying to solve a problem. You can ignore the problem in the code. My doubt is that if I am taking the value of t as 2, still the array outputs 3 strings although I am running the loop only t times for output.
#include<stdio.h>
#include<string.h>
int main(void){
int t;
int i;
int j;
int n;
int c;
int temp;
char result[30][3];
int flag;
scanf("%d", &t);
for(i = 0; i < t; i++){
flag = 0;
scanf("%d", &n);
scanf("%d", &c);
for(j = 0; j < n; j++){
scanf("%d", &temp);
if(c > temp){
c = c - temp;
} else{
flag = 1;
}
}
if(flag == 0){
strcpy(result[i], "Yes");
} else{
strcpy(result[i], "No");
}
}
for(i = 0; i < t; i++){
printf("%s", result[i]);
}
}
Add a \n when you printf a result[i], then you'll find that you actually output 2 strings. For example, if you first strcpy(result[0], "Yes") and then strcpy(result[0], "No"), you'll get the outputs like this:
YesNo
No
In fact, the storage of result is as follows:
result[0]: ['Y']['e']['s']
result[1]: ['N']['o']['\0']
You get "YesNo" when you output result[0], since a two-dimensional array is stored contiguously in the memory and a string ends with \0.
As another example, if you strcpy(result[0], "Hello"), then when you output result[0], you'll get
Hello
and when you output result[1], you'll get
lo
Since the storage in result is as follows:
result[0]: ['H']['e']['l']
result[1]: ['l']['o']['\0']
I have to add two digit strings, meaning 1234 12+34 (at least that's what i gather). I wrote a program that does this expect for one exception, that is when the last number doesn't have a pair it wont add properly.
Here is the code i have:
void main()
{
char string[1000];
int count,sum=0,x,y;
printf("Enter the string containing both digits and alphabet\n");
scanf("%s",string);
for(count=0;count < string[count]; count++)
{
x=(string[count] - '0') * 10;
y=(string[count+1] - '0') + x;
sum += y;
count++;
}
printf("Sum of string in two digit array is =%d\n",sum);
}
so basically if i have 123 the program does 12+(30-48), instead of 12+3. Ive been sitting on it for a while, and cant figure out how to fix that issue, any tips or advice would be welcomed.
(Strings like 1234 or 4567 will do 12+34 and 45+67)
#include <stdio.h>
#include <ctype.h>
int main(void){
char string[1000];
char digits[3] = {0};
int i, j, x, sum = 0;
printf("Enter the string containing both digits and alphabet\n");
scanf("%999s", string);
for(j = i = 0; string[i]; ++i){
if(isdigit(string[i])){
digits[j++] = string[i];
if(j==2){
sscanf(digits, "%d", &x);
sum += x;
j = 0;
}
}
}
if(j==1){
digits[j] = 0;
sscanf(digits, "%d", &x);
sum += x;
}
printf("Sum of string in two digit array is = %d\n", sum);
return 0;
}
I'm trying to print one thing if a certain element is found within a for loop, or print something else if it's not found. This should be simple, but I've tried to do it many different ways, and none of them seem to work.
int squaresArray[1000];
int numberOfSquares = 1000;
int i = 0;
int found = 0;
int number = 100;
for (; i<numberOfSquares; i++)
{
squaresArray[i] = i*i;
if (number==squaresArray[i])
{
found = 1;
}
if (found == 1){
printf("%d is a perfect square", number);
break;}
else {
printf("%d is not a perfect square", number);
break;}
}
There are a couple of problems, the "found" variable goes out of scope outside of the if statement, so I can't do the printf part outside of the if statement, or it just prints "[number] is not a perfect square" dozens of times. How can I do this? I've spent hours on this problem.
The code which you are showing is very time consuming because You need to iterate thousand times if the number is square 999.
Use sqrt() function from math.hto find whether the given number is perfect square are not
Give a try to this.
double param = 1024.0; //read different inputs with the help of scanf().
int i;
if ( ( ( i= (int) (sqrt(param)*10) ) % 10) == 0 )
printf(" is a perfect square");
else
printf(" is not a perfect square");
from #jongware comment, this is tricky than above and easy to understand.
if ( ((int)sqrt(param))*((int)sqrt(param))==param)
printf(" is a perfect square");
else
printf(" is not a perfect square");
int squaresArray[1000];
int numberOfSquares = 1000;
int i = 0;
int found = 0;
int number = 0;
for (; i<numberOfSquares; i++)
{
squaresArray[i] = i*i;
if (number==squaresArray[i]){
found = 1;
break;
}
}
if (found == 1){
printf("%d is a perfect square", number);
break;}
else {
printf("%d is not a perfect square", number);
break;
}
I'm trying to print one thing if a certain element is found within a for loop, or print something else if it's not found
Pseudocode:
int found = 0;
for each element e {
if e is the one I'm looking for {
found = 1
stop the loop
}
}
if (found)
print one thing
else
print something else
Another approach using library functions:
int size = numberOfSquares / sizeof squaresArray[0];
qsort(ints, size, sizeof(int), int_cmp);
int *res = bsearch(&number, squaresArray, size, sizeof(squaresArrays[0]), int_cmp);
if (res == NULL) {
printf("%d not found\n", number);
}
else {
printf("got %d:\n", *res);
}
You also need to provide the comparison function:
int int_cmp(const void* a, const void* b) {
const int *arg1 = a;
const int *arg2 = b;
return *arg1 - *arg2;
}
Try this :
#include <stdio.h>
#include <stdlib.h>
int main(){
int squaresArray[1000];
int numberOfSquares = 1000;
int i;
int found = 0;
int number = 100;
for (i=0; i<numberOfSquares; i++){
squaresArray[i] = i*i;
if (number==squaresArray[i]){
found = 1;
break;
}
}
if (found == 1){
printf("%d is a perfect square of %d\n", number,i);
}else {
printf("%d is not a perfect square", number);
}
return 0;
}
this gives me the following output:
100 is a perfect square of 10
Is this what is desired?
"I was trying to code it without using math.h"
Here is the solution without using <math.h> library.
I suppose, you know that there is the only "perfect square" that your program can find :)
Anyway, see the comments: they will describe something.
Use continue instead of break in order not to break the for-loop.
int squaresArray[1000];
int numberOfSquares = 999;
int i;
int found = 0;
int number = 100;
for ( i = 0 ; i < numberOfSquares; i++ )
{
squaresArray[i] = i*i;
if (number == squaresArray[i])
found = 1;
else
found = 0;
if (found == 1){
printf("%d is a perfect square", number);
continue; // Skipping the current loop and incrementing the `i` variable
}
else {
// printf("%d is not a perfect square", number);
/* If you remove the slashes, you'll see 999 "N is not a perfect square"s,
so you see why I've marked it as comment :) */
continue; // Skipping the current loop and incrementing the `i` variable
}
}