Small c programming help needed - c

I have this problem I've been trying to get this done for last 7 hours, but I'm not getting anywhere. I have tried many options but I seem to fail all time. I'd be delighted if someone helped me out with this so I could see where I'm going wrong. I have made small attempt but the further I go to worst I get. I'd be happy if someone gave me some guidance please. Here is what the program should be like.
I have to enter integer numbers only if it's a floating number than it should display an error and that I need to try again. The minimum amount of numbers are 10.
Once all the numbers are entered it should display what the percentage of the numbers are even numbers.
At any time i can exit the program by typing "exit"
int i;
for(i=1; i<=10; ++i)
printf("Enter 10 integers: ");
scanf("%d",&i);
printf("Enter the next integer or type exit to end the program: %d",i);
system("PAUSE");
return (printf);

Since you asked for guidance rather than a full working solution, here goes.
First you currently have
for(i=1; i<=10; ++i)
printf("Enter 10 integers: ");
scanf("%d",&i);
The for will just loop around the next line, unless you use braces, i.e. it will print "Enter..." 10 times:
for(i=1; i<=10; ++i)
printf("Enter 10 integers: ");
scanf("%d",&i);
It may help to get used to putting everything you want to loop (even a one-liner) in braces:
for(i=1; i<=10; ++i)
{
printf("Enter 10 integers: ");
scanf("%d",&i);
//...
}
Often people (with good reason) start at 0 in C:
for(i=0; i<10; ++i)
{
printf("Enter 10 integers: ");
scanf("%d",&i);
//...
}
If you structure your code like that it may help to pull out a get_valid_input function
for(i=0; i<10; ++i)
{
printf("Enter 10 integers: ");
get_valid_input(); //what do you intend to do with this?
//...
}
with
int get_valid_input()
{
int i;
scanf("%d",&i); //how do they type "exit"?
//..
}
This needs thought though - should it return an int?
You could then store them somewhere.
But you could keep track of percentage of even numbers as you go.
Also, at any time you can press "exit" (type in the string or press a key?) so you need to be able to indicate that.
Don't forget to print the result, once you have worked it out. (Left as an exercise for the reader)

int i, v, n=0, even;
int array[10] = {0};
char buff1[32], buff2[32];
printf("Enter 10 integers: \n");
for(i=1; i<=10; ++i){
printf("Enter the next integer or type exit to end the program %d:\n", i);
fgets(buff1, sizeof buff1, stdin);
strcpy(buff2, strtok(buff1, " \t\n"));//trim
if(strcmp(buff2, "exit")==0)
break;
if(1!=sscanf(buff2, "%d%s", &v, buff1)){
printf("invalid input\n");
--i;
continue;
}
array[n++] = v;
}
for(even=i=0;i<n;++i){
printf("%d ", array[i]);
if((array[i] & 1) == 0)
++even;
}
printf("\n");
if(n)
printf("Even proportions : %.1f%%\n", 100.0*even / n);
system("PAUSE");
return 0;

Related

Understanding the arrays in C

I'm new to C and need some help to understand how this piece of code works. I know that it reads the values that the user writes, puts them into an array, and then prints them out.
But I don't understand why I need two "counters" (i and j) to do this. Can someone help me to figure it out?
#include<stdio.h>
int main ()
{
int A[5];
int i=0;
int j=0;
while (i < 5)
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}
while (j < 5)
{
j++;
printf ("\n%d\n", A[j]);
}
}
Technically, what you have aren't two counters, but two loops. If you wanted, to, you could just reuse i for the second loop as well, by doing something like this:
while (i < 5)
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}
i = 0;
while (i < 5)
{
i++;
printf ("\n%d\n", A[i]);
}
As for why you have two loops, the reason is simple. The first loop (using i in your code), reads the 5 integers into the array A. After the first loop concludes, your array A holds the 5 int values, which you could've used however you wanted. In your case, you want to print those values. So what you do is use a loop for looping over the array elements and printing the values to the screen, one by one.
You don't need it, you can simply reset the first and reuse it. However you must increment your index only after having using it otherwise you will overflow the limit of the array :
#include<stdio.h>
int main ()
{
int A[5];
int i=0;
while (i < 5) {
printf("Enter your %d number\n", i);
scanf("%d", &A[i]); // the last must be 4 not 5
i++; //<== increment here
}
i=0;
while (i < 5)
{
printf ("\n%d\n", A[i]); //idem
i++;
}
}

Sorting inputted integers into odd and even arrays

I'm a beginner to C, and am trying to sort user inputted numbers into odd and even arrays. I don't understand why my code isn't working.
Cheers.
This is my code, I don't understand my mistake.
int x[]= {};
int i=0;
int d=0;
int j=0;
int even[12]={};
int odd[12]={};
printf("Enter amount of numbers: "); // asking user for amount of numbers
scanf("%d", &d);
for (j=0; j<d; j++){
printf("Enter number %d: ", i+1); // scanning input into 'x' array
scanf("%d", x[i]);
}
printf("Even numbers: ");
for (i=0; i<d; i++) {
if (x[i] % 2 == 0) { // sorting into even array
even[i]=x[i];
printf("%d \n", even[i]);
}
}
printf("\n Odd numbers: ");
for (i=0; i<d;i++){
if (x[i] % 2 != 0) { // sorting into odd array
odd[i]=x[i];
printf("%d \n", odd[i]);
}
}
This error message keeps coming up:
$ ./main
Enter amount of numbers: 4
Enter number 1: 6
Segmentation fault (core dumped)
int x[]= {}; doesn't work because it would hold no elements. But initializing it with {} doesn't work in C anyway, do this instead:
int x[24] = {0}; // first element explicitely set to 0, the rest default-initialized to 0
You also need to put {0} for even and odd. If it's compiling for you with {} then it's possible that you're compiling it as a C++ program, or perhaps your compiler just tolerates it anyway (but it won't work on every C compiler).
scanf needs the address of the int, so instead of scanf("%d", x[i]); you need scanf("%d", &x[i]);. But i is the wrong iterator for this for (j = 0; j < d; j++) loop. Instead do this:
for (j = 0; j < d; j++) {
printf("Enter number %d: ", j + 1); // scanning input into 'x' array
scanf("%d", &x[j]);
}
Also note that the way you're doing this, half the array will be left at 0. So for instance if I imputted the values 1 through 6, then odd contains the values 1 0 3 0 5 0.

C: Array of Structs (Input into int array within array of structs)

Hi I have to create a database that stores students number, name and also stores an array of course marks (1-N) in C Programming Language.
Everything worked until I started coding for the array of course marks. Then every time I compiled the code it kept crashing as soon as it asked to input the course marks.
Can you please tell me where I'm going wrong in my programming for this task? I have attached it to this message.
The program worked for inputting the name, student number, however I could not get the program to input array of marks. I have asked how many course marks to be entered and then used a for loop within the "void insert(void)" function to keep inputting the course marks into the array *marks. I am referring specifically to lines 24 to 30 in my programming code.
Always at this point the program kept crashing and I could not proceed further to enter more names or print the stored student details.
I think there is a problem with this part:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n");
scanf("%d", &(list[num_students].marks[num_marks]));
}
Anyway here is the full code:
#include <stdio.h>
#include <string.h>
struct student{
int number;
char name[10];
int marks[5];
};
struct student list[10];
int num_students = 0;
int num_marks = 0;
int *p;
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++; // HOW DO WE INPUT ARRAY MARKS??? MARK1: , MARK2: , MARK3 ,
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
int main(void)
{
int code;
int opt1;
int courses, i, k, j, counter;
for (;;){
printf("Enter operation code: \n");
printf("(1) ADD NEW STUDENT DETAILS: \n");
printf("(2) DISPLAY REPORT OF ALL STUDENTS: \n");
scanf(" %d", &code);
switch (code){
case 1 :
insert();
break;
case 2 :
printtest();
break;
default:
printf("Illegal code\n");
printf("\n");
}
}
}
Apart from what others pointed out, I'd like to draw your attention towards the following:
void insert(void)
{
int student_number;
int i;
printf("Enter number: \n");
scanf("%d", &list[num_students].number);
printf("Enter NAME: \n");
scanf("%s", &list[num_students].name);
printf("Enter NO of courses: \n");
scanf("%d", num_marks);
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
num_students++;
}
void printtest(void)
{
int i;
for (i=0; i < num_students; i++)
{
printf("Name: \n");
puts(list[i].name);
printf("Number: %d \n", list[i].number);
printf("Mark: %d /100 \n", list[i].marks);
printf("\n");
}
}
There are three problematic statements:
scanf("%s", &list[num_students].name); This is why beginners should use compilers with all warnings enabled.
printf("Mark: %d /100 \n", list[i].marks); What did you declare marks as in the first place?
scanf("%d", num_marks); Seems like you put & operator where not needed and ignore where needed. Read your textbook before asking a question next time.
Seems like you're having a tough time understanding the concept of arrays and pointers. Read your text book thoroughly before venturing into the world of pointers. If you don't use them correctly, even compiler can't help you.
Also, even if I don't expect your program to have a robust input mechanism, at least array bounds checking is expected. Learn good habits from the beginning. They'll save a lot of your time while debugging later.
Seems to be an error in:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[num_marks]));
}
The crash is probably because num_marks as index indexes beyond the array. Change to:
for (i= 0; i < num_marks; i++)
{
printf("Enter Course Mark: \n" );
scanf("%d", &(list[num_students].marks[i]));
}

how can i insert no more than 5 sentences and no more than 50 letters per each sentence in C

before each sentence it needs to say the number of the sentence im writing. starting the count from one.
what i mean is:
How many sentences you want to enter [1-5]?
2
sentence 1: write what you want
sentence 2: here as long as its less then 50 letters
my problem is that i dont know how to limit the number of letters, without needing to insert them all.
if i write
for(i=0; i<50; i++)
i will need to enter all the 50 letters, but if i want i need to be able to write even only 1.
so that is what i have done so far: (note that i dont need to ask the user how many letters he wants to enter)
char text[5][50]={0};
int x=0, i=0, n=0, m=0;
printf("How many sentences you want to enter [1-5]?\n");
scanf("%d", &n);
printf("how many letters [1-50]?\n");
scanf("%d", &m);
for (x=1; x<=n; x++)// will print max of 5 sentences
{
printf("Sentence %d: \n", x);
for(i=0; i<m; i++)// will print max of 50 letters
{
scanf(" %c", &text[x][i]);
}
}
thanks a lot for the help!
for(i=0;i<n;i++)
{
if(fgets(text,50,stdin) != NULL) /* Read just 50 character */
{
// Do your stuff
}
}
PS: fgets() comes with a newline character
There is still an error.
for (x=1; x<=n; x++)
will cause an indexing error when x==5. Always maintain your indexing to suit the language. Use
for (x=0; x<n; x++)
Add 1 for human information
printf("Sentence %d: \n", x + 1);
And as #cmatsuoka wrote, the array should be
char text[5][51]={0};

C program with two dimensional arrays?

in a two dimensional array there are kept the working hours for N workers and M projects,the names of the workers are kept in an array with the name Worker and the name of the projects in an array with the name "Project".Write a program which reads the data and displays the worker with more working hours.So I tried this,but everytime I ran it,it seems to be a logical error,because it says :Give the number of the project,and If I type "2" this is also the number of the workers according to my program,and then it asks for the hours for each worker..
#include<stdio.h>
#include<conio.h>
int main()
{
int i, j, n, worker[100][10], hours[30][100];
printf("The number of the project: ");
scanf("%d", &n);
for (i=0; i<n; i++)
{
printf("Give the worker %d: ", i+1);
scanf("%s", &worker[i]);
}
for (i=0; i<n; i++)
{
printf("\n The worker %s\n", worker[i]);
for (j=0; j<30; j++)
{
printf("The number of the hours for the day %d: ", j+1);
scanf("%d", &hours[i][j]);
}
}
for (i=0; i<n; i++)
{
for (j=0; j<30; j++)
if (hours[i][j]==0)
break;
if (j==30)
printf("%s\n", worker[i]);
}
getch();
return 0;
}
You seem to be taking the input incorrectly.
scanf("%s", &worker[i]);
worker is a 2D array of type int. So, you need to have another index while taking input. Also the format specifier for int is %d. Any decent compiler should have given you warnings during compilation.
Seems to me that you first must ask how many workers (N) and how many projects (M) with something like:
int ii, m, n;
char **worker;
char **project;
printf("How many workers? ");
scanf("%d", &n);
printf("How many projects? ");
scanf("%d", &m);
Then ask for the names of the workers:
// Allocate space for n worker string pointers
worker = (char **)malloc(n * sizeof(char *));
for (ii = 0; ii < n; ++ii)
{
char bufname[1024]; // danger here if input too long
printf("Name of worker[%d]? ", ii + 1);
scanf("%s", bufname);
worker[ii] = strdup(bufname);
}
Then ask for the names of the projects, similarly. Then get the hours, then calculate the max, then free up the dynamically allocated worker & project strings (and the two array of pointers).

Resources