i wrote this code that asks to the user to input how many numbers wants to input, then asks for the numbers and from this creates an array then:
call the function VerificaSequenza
checks that the sum of the first two is equal to the third one
if yes does this again with the second and the third equal to the forth and so on
returns back 1 if is true false if not
the Question is: why i can't even see on the screen the printf messages? it just finishes immediately without asking for numbers and without printing
#include<stdio.h>
int VerificaSequenza(int lunghezza, int sequenza[])
{
int ContoSomma = lunghezza - 1;
int casella1 = 0;
int casella2 = 1;
int risultato = 2;
int controllo;
int i;
int messaggio;
for(i=0; i<ContoSomma; i++)
controllo = sequenza[casella1] + sequenza[casella2];
++casella1;
++casella2;
if (controllo == sequenza[risultato])
{
messaggio = 1;
++risultato;
}
else
{
messaggio = 0;
return messaggio;
}
}
int main()
{
int lunghezza;
int sequenza[lunghezza];
printf("Da quanti numeri รจ composta la sequenza?");
scanf("%d", &lunghezza);
printf("scrivi la sequenza");
for(int i=0; i<lunghezza; i++)
scanf("%d", &sequenza[i]);
int messaggio = VerificaSequenza(lunghezza, sequenza);
printf("%d", messaggio);
}
Related
I want the sum of the numbers in the matrix in each column to add up, tried doing this using different variation's of the same music[i+1][j]+=music[i][j], but its not working, so basically what the program does, it assigns 3 points to the first number the user inputs as his favorite song, the second song get 2 points and the third 1 point, i want the matrix at the end to sum up all the points from the participants and give me the total.
#include <stdio.h>
#include <stdlib.h>
int main()
{ int num=0, pers=0;
int i,j, k;
int votos=0;
printf("Digite la cantidad de personas:");
scanf("%d", &pers);
float music[pers+1][10];
for(i=0;i<pers+1;i++){
for(j=0;j<10;j++){
music[i][j]=0;
}
}
for(i=0;i<pers;i++){
printf("Participante %d :\n",i+1);
for(k=1;k<=3;k++){
printf("Digite el numero de sus 3 canciones favoritas %d:\n",k);
scanf("%d",&num);
for(j=0;j<9;j++){
if (k==1){
music[i][num-1]=3;
}
if (k==2){
music[i][num-1]=2;
}
if (k==3){
music[i][num-1]=1;
}
music[10][j]+=music[i][j];
}
}
}
for(i=0;i<pers+1;i++){
for(j=0;j<10;j++){
printf("%.2f\t",music[i][j]);
}
printf("\n");
}
return 0;
}
GDB is your friend for these sorts of problems. You can install an interactive debugger and step through your code line by line to see what values your matrix takes on certain input.
If you did that, you may have saw that you're accessing the 10th row of your matrix. Even if pers is initialized to three.
There's also an issue where you begin summing music values as they're being initialized (leading to over counting).
for (i = 0; i < pers; i++)
{
printf("Participante %d :\n", i + 1);
for (k = 1; k <= 3; k++)
{
printf("Digite el numero de sus 3 canciones favoritas %d:\n", k);
scanf("%d", &num);
if (k == 1)
{
music[i][num - 1] = 3;
}
if (k == 2)
{
music[i][num - 1] = 2;
}
if (k == 3)
{
music[i][num - 1] = 1;
}
}
}
for(j = 0 ; j < 10; j++)
{
for (i = 0; i < pers+1; i++)
music[pers][j] += music[i][j];
}
I'm hoping this code doesn't fully solve your problem since it'll be good for you to look into gdb and learn how to interact with your code and understand where its deviating from your expectations.
It'll also help to do as paddy suggested and explain what your input and output is supposed to look like.
Try This Code It working and sum up
#include <stdio.h>
#include <stdlib.h>
int main(){
int num=0, pers=0;
int i,j, k;
int votos=0;
printf("Digite la cantidad de personas:");
scanf("%d", &pers);
float music[100][100];
float sum[100][100];
for(i=0;i<pers+1;i++){
for(j=0;j<10;j++){
music[i][j]=0;
}
}
for(i=0;i<pers;i++){
printf("Participante %d :\n",i+1);
for(k=1;k<=3;k++){
printf("Digite el numero de sus 3 canciones favoritas %d:\n",k);
scanf("%d",&num);
for(j=0;j<9;j++){
if (k==1){
music[i][num-1]=3;
}
if (k==2){
music[i][num-1]=2;
}
if (k==3){
music[i][num-1]=1;
}
sum[i][j]+=music[i][j];
}
}
}
for(i=0;i<pers+1;i++){
for(j=0;j<10;j++){
printf("%.2f\t",sum[i][j]);
}
printf("\n");
}
return 0;
}
I'm just learning programming with c.
I wrote a program in c that had a bug in the body of the while loop
I did not put {}.
The program is as follows, but the question that came to me later is how to run the program in c? Why does error 2 not print while it is before the start of the while loop? If the c language is a compiler, why is it that the error of the whole program is not specified first, and up to line 15 the program is executed without any problems?
int main()
{
int n ,k;
float d ;
printf("please write your arithmetic sequence sentences ");
scanf("%d",&n);
printf("\n");
printf("please write your common differences");
scanf("%d",&k);
printf("\n");
printf("please write your initial element ");
scanf("%f",&d);
printf("error 1");
printf("\n");
printf("error 2");
printf("number \t sum");
printf("erorr 3");
int i = 0;
int j = 0;
int sum = 0;
while (i < n)
j = d + i*k;
sum += j;
printf("%d\t%d",j,sum);
i++;
return 0;
}
Firstly, the program enters an infinite loop:
while (i < n)
j = d + i*k;
Since the values of i and n do not change, the condition never becomes false.
Secondly, the printing sequence:
printf("error 2");
printf("number \t sum");
printf("erorr 3");
does not display a line break at the end. The output is buffered (stored internally) waiting for the line break to be printed, which, naturally, never happens. Add \n at the end of "erorr 3" to see the difference.
#include <stdio.h>
int main()
{
int n ,k;
int i = 0;
int j = 0;
int sum = 0;
float d ;
// If the given values are not an integer, it wouldn't continue the sequence and end as an "error"
printf("please write your arithmetic sequence sentences ");
if(scanf("%d",&n)){
printf("please write your common differences");
if(scanf("%d",&k)){
printf("please write your initial element ");
if(scanf("%f",&d)){
printf("Number \tSum\n");
} else {
printf("error");
}
} else{
printf("error");
}
} else{
printf("error");
}
// This is where the values get solved
// You also forgot to add {} in your while statement
while (i < n){
j = d + i*k;
sum += j;
printf("%d\t%d",j,sum);
i++;
}
return 0;
}
The code I have so far for setting up my array is this:
#include <stdio.h>
void printArray(float myArray[4][3]);
int main(void)
{
};
printArray(sides);
return 0;
}
void printArray(float passedArray[4][3])
{
printf("Side A\tSideB\tSide C\n");
for (int x = 0; x < 4; x++)
{
for (int y = 0; y < 3; y++)
{
printf("%.3f \t", passedArray[x][y]);
}
printf("\n");
}
}
I've also created a way to evaluate the hypotenuse in a previous code if I was given an input from the user:
#include <stdio.h>
#include <math.h>
double hypotenuse(double lengtha, double lengthb);
int main() // Start of main function
{
double lengtha, lengthb; //storing variables for later use
printf("Enter the length of side A: \n"); //Prompt user for input of A
scanf("%lf", &lengtha); //Stores input from user
printf("Enter the length of side B: \n\n"); // Prompt user for input of B
scanf("%lf", &lengthb); //Stores input from user
return 0; // terminate
} /* End function main */
double hypotenuse(double sidea, double sideb)
{
return sqrt(pow(sidea, 2) + pow(sideb, 2));
} /* End function */
The main issue that' I'm running into however though, is I'm unsure how to take the pre stored values from my first code/arrays, throw them into the equation, then have them output into side c into the table. I know there has a to be a way, but it's really hard to find too much info since C is a bit older. Any suggestions or help would be greatly appreciated!
If i understood you correctly, you could just iterate over every row of your array and assign the result of the function call to the last column:
for (int i = 0; i < 4; ++i) {
array[i][2] = hypotenuse(array[i][0], array[i][1]);
}
With the code below, I'd always run into "Stack around the variable 'UserCode' was corrupted.
If I'm not mistaken, when I do userCode = (char*)malloc(sizeof(char)*N);, shouldn't it create an "array" with size of char*n ? I'm guessing my issue is either with my declaration of an array, or my pointer arithmetic.
Any help would be highly appreciated.
#include "stdafx.h"
#include <math.h>
int userPrompt1() {
int numOfAlphabets = 0;
printf("Please enter a number from 1 to 8 to choose how many alphabets you want\n");
scanf_s(" %d", &numOfAlphabets);
if (numOfAlphabets > 8 || numOfAlphabets < 0) {
printf("Sorry! Invalid number entered. Try again. \n");
numOfAlphabets = userPrompt1();
}
return numOfAlphabets;
}
int userPrompt2() {
int numOfLetters = 0;
printf("Please enter the number of letters you want to guess\n");
scanf_s(" %d", &numOfLetters);
if (numOfLetters < 0) {
printf("Sorry! Invalid number entered. Try again. \n");
numOfLetters = userPrompt2;
}
return numOfLetters;
}
int tryCalculator(int K, int N) {
int tries = 0;
tries = 1 + ceil(N * log2(K));
return tries;
}
void codeGenerator(char codeGuessIn[], char letters[], int size) {
for (int i = 0; i < size; i++) {
int rando = rand() % size;
codeGuessIn[i] = letters[rando];
printf(" %c", codeGuessIn[i]);
}
printf("\n");
}
void codeChecker(char codeGuessIn[], char generatedCode[], int size) {
int correctAlphabets = 0;
for (int i = 0; i < size; i++) {
if (codeGuessIn[i] == generatedCode[i]) {
correctAlphabets++;
}
}
printf(" %d in correct place \n", correctAlphabets);
}
void getUserCode(int size, char *userCode[]) {
for (int i = 0; i < size; i++) {
printf("Please enter letter #%d \n", i+1);
getchar();
scanf_s(" %c", &userCode[i]);
}
}
int main(void)
{
char letters[8] = { 'A','B','C','D','E','F','G','H' };
char *generatedCode; //array to hold generated code
char *userCode; // array to hold generated code.
int K = userPrompt1(); //how many different alphabets in code
int N = userPrompt2(); //how many letters in code
int tries = tryCalculator(K, N);
//int gameEnd = 1;
userCode = (char*)malloc(sizeof(char)*N);
generatedCode = (char*)malloc(sizeof(char)*N);
codeGenerator(generatedCode, letters, N);
getUserCode(N, &userCode);
//codeChecker(userCode, generatedCode, N);
return 0;
}
void getUserCode(int size, char *userCode[]) {
scanf_s(" %c", &userCode[i]);
Here, userCode[i] is a char * (pointer-to-char), &userCode[i] is a char ** (pointer-to-pointer-to-char), and scanf("%c") expects a char *. A good compiler would warn about that.
I think what you meant to do here is something like:
void getUserCode(int size, char *userCode) {
scanf_s(" %c", &userCode[i]);
}
int main(void) {
char *userCode = malloc(N);
getUserCode(N, userCode);
}
The printf(), getchar(), scanf() combination here reeks of the bad habits created by scanf: you're discarding the first character entered by the user because you're relying on an extra character in the input buffer.
See http://c-faq.com/stdio/scanfprobs.html and read full lines of input with fgets() instead of using scanf().
Also,
int userPrompt2() {
int numOfLetters = 0;
...
numOfLetters = userPrompt2;
}
You're assigning a function pointer to an int. (A normal compiler should warn about this.) If the idea here is to call the function again to repeat the prompt in case the user enters something silly, it's probably a better idea to use a loop instead of a recursive call anyway.
I am trying to copy the array winner from my function 'enter', so that i am able to just output it on the 'previous' function. When picking the option for the previous option I have gotten nothing outputting. Its only the last function named 'previous' that is not working, but to produce the problem the majority of the code is needed.
#include <stdio.h>
#include <string.h>
char enter(char names[][20]);
void menu();
void previous(char winner[][8]);
int main()
{
char names[16][20];
int i;
printf("Please enter the names of the players:\n");
/*Making the user enter 16 times*/
for (i = 0; i < 16; i++)
{
scanf("%9s", &names[i]);
fflush(stdin);
}
/*Clearing Screen*/
system("cls");
menu(names);
return names[16][20];
}
void menu(char names[][20], char winner[][8])
{
int choice;
printf("Please select one of the following options:\n\n"
"Press 1 to enter game results\n"
"Press 2 to display the current round\n"
"Press 3 to display the players advancing to the next round\n"
"Press 4 to display the previous round\n"
"Press 5 to exit the program\n");
scanf("%d", &choice);
if(choice == 1)
{
enter(names);
}
system("cls");
if(choice == 3)
{
previous(winner);
}
}
char enter(char names[][20])
{
int result;
int score1;
int score2;
int p, c, j, l, i;
char winner[8][8];
system("cls");
for(i = 0; i < 8; i++)
{
printf("\n\n%s vs %s",names[i],names[i+8]);
score1 = 0;
score2 = 0;
for(j = 0; j < 5; j++)
{
printf("\n\nEnter game %d results, press 1 if %s won or"
" 2 if %s won :\n",(j+1), names[i], names[i+8]);
scanf("%d", &result);
if(result == 1)
{
score1++;
}
if(result == 2)
{
score2++;
}
printf("\n\n1Current score is %d-%d", score1, score2);
if(score1 == 3)
{
printf("\n\n%s adavances to the next round!",names[i]);
strncpy(winner[i], names[i], 10);
printf("\n\nPress Enter to Continue");
getch();
system("cls");
break;
}
if(score2 == 3)
{
printf("\n\n%s adavances to the next round!",names[i+8]);
strncpy(winner[i], names[i+8], 10);
printf("\n\nPress Enter to Continue");
getch();
system("cls");
break;
}
}
}
system("cls");
printf("The players advancing to the next round are:\n\n");
for(p = 0; p < 8; p++)
{
for(c = 0; c < 8; c++)
{
printf("%c",winner[p][c]);
}
printf("\n");
}
printf("\n\nPress Enter to Continue");
getch();
system("cls");
menu(names, winner);
return winner[8][8];
}
void previous(char winner[][8])
{
int i, j;
for(i = 0; i < 8; i++)
{
for(j = 0; j < 8; j++)
{
printf("%c",winner[i][j]);
}
printf("\n");
}
}
There is no data for the array winner in your program! At least not when you call it for the first time.
The signature for the menu function is:
void menu(char names[][20], char winner[][8]);
but you call it from main like this:
menu(names);
The winner parameter is missing. This shouldn't happen, but you have declared a prototype for this function, namely:
void menu();
Unfortunately, C treats the empty parens as meaning "whatever parameters you pass", not as function that takes no parameters. That means that your function call slips by. The fix is to provide the correct signature for the prototype and also to pass a suitable winner array from main.
Strangely, your enter function provides a local array winner. This array will always be a new array when you call enter. That's probably not what you want. As is, your program should have one names and one winner array. (You can pass these arrays around, but you should make sure that tese arrays are consistent. Don't create new arrays when you really want to operate on existing ones.)
You also call your menu recursively. That means the you go ever deeper into the call structure without real benefit. Dont do that; use a loop instead: do display the menu while the user hasn't chosen "quit". (There are applications for recursive functions, but this isn't one.)