im trying to do a programa in C. Capture name, age, album number, names and songs withing each album. Im ok but it only prints the last albums name. Lets say i input 3 albums, "a", "b" and "c". It would only print c 3 times. And it should be a,b and c. Thank you.
#include <stdio.h>
int main() {
//variables
int edadCantante;
int x,numeroCanciones[x];
char nombreCantante;
char nombreDiscos[30][x];
printf("Introduzca el nombre del artista: ");
scanf(" %[^\n]",nombreCantante);
printf("Introduzca edad del artista: ");
scanf("%d", &edadCantante);
printf("Introduzca número de discos: ");
scanf("%d\n",&x );
// taking input and storing it in an array
for(int i = 0; i < x; ++i) {
scanf("%[^\n]%*c", nombreDiscos[i]);
}
printf("Desplegando albumes:\n ");
// printing elements of an array
for(int i = 0; i < x; ++i) {
printf("%s\n", nombreDiscos[i]);
}
printf("Número de canciones por album respectivamente:\n ");
for(int i = 0; i < x; ++i) {
scanf("%d", &numeroCanciones[i]);
}
printf("Desplegando número de canciones:\n ");
// printing elements of an array
for(int i = 0; i < x; ++i) {
printf("Número de canciones en album %d = %d\n",i+1,numeroCanciones[i]);
}
return 0;
}
You need to move the declaration of numeroCanciones and nombreDiscos. Like this:
int x;
scanf("%d\n",&x );
int numeroCanciones[x];
But don't forget to check the return value of scanf in case a reading failed.
Related
I want to make a program that returns the average of the numbers entered but i get this error:
incompatible types when assigning to type ‘float *’ from type ‘float’
#include <stdio.h>
#include <stdlib.h>
#define CANT ((int)99)
float* promedio (float *dataPtr, int dataCant)
{
float *p;
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
*dataPtr +=1;
}
p = total / dataCant;
return (p);
}
int main (void)
{
float v[CANT],*q;
int i;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) || (v [i] != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &v[i]);
i++;
}
q = promedio (&v[0], i);
printf ("El promedio vale %f\r\n", *q);
free (v);
return (0);
}
Your approach of returning a pointer from promedio doesn't make much sens.
You probably want this:
void promedio (float *dataPtr, int dataCant, float *result)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
dataPtr +=1; // remove the *, you want to increment the pointer
} // not the thing it points to
*result = total / dataCant;
}
int main (void)
{
float v[CANT],*q;
int i;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) || (v [i] != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &v[i]);
i++;
}
float q;
promedio (&v[0], i); // you should write `v` innstead of the cumbersome `&v[0]`
printf ("El promedio vale %f\r\n", q); // q is a float, removge the *
// remove free (v), you can only free stuff allocated via malloc and friends
return (0);
}
Anyway, I have the strong impression you should read again the chapter dealing with pointers in your learning material.
It turns out you rather need this:
float promedio (float *dataPtr, int dataCant)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
dataPtr +=1; // remove the *, you want to increment the pointer
} // not the thing it points to
return = total / dataCant;
}
#Jabberwocky
Thank you for your answer, thanks it I managed to solve the exercise. This is the answer (works)
#include <stdio.h>
#include <stdlib.h>
#define CANT ((int)99)
float promedio (float *dataPtr, int dataCant)
{
int a;
float total;
for ( a = dataCant; a >= 0; a--) {
total += *dataPtr;
dataPtr +=1;
}
return (total / dataCant);
}
int main (void)
{
float v[CANT], q, a;
int i=0;
printf ("Ingrese numeros para calcular el promedio\r\n");
printf ("Use -1 para ver el promedio\r\n");
while ((i < CANT) && (a != -1)) {
printf(" Ingrese un numero: \r \n");
scanf ("%f", &a);
if (a != -1) {
v[i]=a;
i++;
}
}
q = promedio (&v[0], i);
printf ("El promedio vale %0.2f\r\n", q);
return (0);
}
I have to make a program that reads an integer (N+) and then read a series of other integers (N+), but the program needs to check if the user has inputted chars mixed in the numbers the scanf() reads, in affirmative, the program will repeat the scanf(). So I decided to check the return value of scanf(). It works if I use only character input, but when I mixed it with integers, the program reads the integer and uses the maintained character on the buffer. How can I solve this?
#include <stdio.h>
int main() {
int tamanho = 0, verificador = 0;
do {
printf("Digite um valor n>0: ");
verificador = scanf("%d", &tamanho);
getchar();
if (verificador != 1) {
printf("\nO programa aceita apenas valores inteiros\n");
printf("Tente novamente\n");
}
} while (verificador != 1);
int conjunto[tamanho];
do {
printf("Digite os numeros do conjunto de tamanho 'n': ");
for (int i = 0; i < tamanho; i++) {
verificador = scanf("%d", &conjunto[i]);
if (verificador != 1) {
printf("\nO programa aceita apenas números\n");
printf("Tente novamente\n");
getchar();
break;
}
}
} while (verificador != 1);
printf("numero = %d\n", tamanho);
for (int i = 0; i < tamanho; i++) {
if (i <= tamanho - 2) {
printf("%d, ", conjunto[i]);
} else if (i == tamanho - 1) {
printf("%d.\n", conjunto[i]);
}
}
return 0;
}
#include <stdio.h>
void chercherVal(int tab[], int N, int A, int *pos, int *nb_occ) {
int i = 0;
while (i < N) {
if (tab[i] == A) {
*pos = i;
*nb_occ = *nb_occ + 1;
}
i++;
}
printf("la position est %d et le nombre d'occurence est %d", pos, nb_occ);
}
int main() {
int pos = -1, nb_occ = 0;
char A;
int i, N;
int tab[100];
printf("saisir le nombre d'elements de tab :");
scanf("%d", &N);
for (i = 0; i < N; i++) {
printf("saisir l'element %d du tableau tab :", i + 1);
scanf("%d", &tab[i]);
}
printf("saisir la valeur a rechercher :");
scanf("%s", &A);
chercherVal(tab, N, A, &pos, &nb_occ);
}
Here is one pointer problem (or lack of)
printf("la position est %d et le nombre d'occurence est %d", pos, nb_occ);
should be
printf("la position est %d et le nombre d'occurence est %d", *pos, *nb_occ);
The compiler should have warned that the wrong argument types are being passed.
Reading a string with scanf("%s", &A); into a single char has undefined behavior because scanf() will store the bytes and a null terminator, writing beyond the destination variable.
You should either make A and int and read a number: scanf("%d", &A);
Or you should read a single char with scanf(" %c", &A); (note the space before the % to skip pending white space, including the newline left in the standard input by previous calls to scanf().
Here is a modified version:
#include <stdio.h>
void chercherVal(const int tab[], int N, int A, int *posp, int *nb_occp) {
int pos = -1, occ = 0;
for (int i = 0; i < N; i++) {
if (tab[i] == A) {
occ++;
if (pos < 0) { /* only store the first position */
pos = i;
}
}
}
/* always store the return values */
*posp = pos;
*nb_occp = occ;
}
int main() {
int tab[100];
int N, A, pos, nb_occ;
printf("saisir le nombre d'elements de tab : ");
if (scanf("%d", &N) != 1)
return 1;
if (N > 100) /* prevent buffer overflow */
N = 100;
for (int i = 0; i < N; i++) {
printf("saisir l'element %d du tableau tab : ", i + 1);
if (scanf("%d", &tab[i]) != 1)
return 1;
}
printf("saisir la valeur a rechercher : ");
if (scanf("%d", &A) != 1)
return 1;
chercherVal(tab, N, A, &pos, &nb_occ);
printf("la position est %d et le nombre d'occurences est %d\n", pos, nb_occ);
return 0;
}
The program compiles perfectly, the problem is the cycle, it does not show me the position
here goes the include of library stdio.h
int main(void)
{ int x, i=0,j=0, a[100];
char sal;
printf("Este programa lee un arreglo de numeros enteros y un numero x, y muestra en pantalla los indices de las posiciones en donde se encuentra ese numero x\n");
do
{
printf("Ingrese un numero: ");
scanf("%i", &a[i]);
i++;
printf("Si desea salir presione s: ");
scanf(" %c", &sal);
}while(sal!='s');
printf("Ingrese el valor de la variable x: ");
scanf("%i", &x);
for (j; j<=i; j++)
{
if(a[i]==x)
printf("%i",i);
}
printf("\n");
}
You condition of the for loop should be j<i, not j<i+1. When the while
loop exits, i has the value for the next input, but it has not been set because
the loop exited.
Also you are using the index i instead of j in the for-loop. j is the
running index, not i:
for (j; j<i; j++)
{
if(a[j]==x)
printf("%i", j);
}
would be correct.
Your while loop is ok, but a bit clunky. First you don't check if you are
writing past the limit of a. The conditions should be
while(sal!='s' && i < (sizeof a / sizeof *a));
so that the user cannot input more values than a can hold.
The way you exit the loop is also awkward, the user has to type something
different to s to continue and it can only be one character. This would be
better:
int c;
char line[100] = { 0 };
do
{
printf("Ingrese un numero: ");
scanf("%i", &a[i]);
while((c = getchar()) != '\n' && c != EOF); // to clear the input buffer
i++;
printf("Si desea salir ingrese SALIR. Para continuar presione ENTER: ");
fgets(line, sizeof line, stdin);
} while(strcmp(line, "SALIR\n") && strcmp(line, "salir\n") && i < (sizeof a / sizeof *a));
Note that strcmp returns 0 when the strings are equal, a non-zero otherwise.
A tip, you should always set the loop counter to 0 either right before the loop, or in the loop. And it's always a good practice to initialize all variables during declarations. In your case, you did not initialize integer array. Below is a modified version of your code.
int main(void)
{
int x, i, j;
x = i = j = 0;
int a[100] = { 0 };
char sal = 0;
printf ("Este programa lee un arreglo de numeros enteros y un numero x, "
"y muestra en pantalla los indices de las posiciones en donde se "
"encuentra ese numero x\n");
while(1)
{
printf("Ingrese un numero: ");
scanf("%d", &a[i]);
i++;
printf("Si desea salir presione s: ");
scanf(" %c", &sal);
if (sal == 's')
break;
}
printf("Ingrese el valor de la variable x: ");
scanf("%d", &x);
for (j = 0; j <= i; j++)
{
if (a[i] == x)
printf("%d", i);
}
printf("\n");
}
i don't understand why when i try to print values in archivio[] with stampa function,this program prints
"studente","matricola","nome","cognome"
correctly, but doesn't print values from stampaEsami.
#include <stdio.h>
#include <stdlib.h>
#define MAXSTUDENTI 20
#define MAXSTRINGA 100
#define MAXESAMI 25
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
typedef char Stringa[MAXSTRINGA];
typedef enum { uno, due, tre, FC
} AnnoCorso;
typedef struct {
Stringa nomeEsame;
int voto;
} Esame;
typedef struct {
Esame listaEsami[MAXESAMI];
int numeroEsami;
}ListaEsame;
typedef struct {
int matricola;
Stringa nome;
Stringa cognome;
AnnoCorso anno;
ListaEsame esami;
} Studente;
void init(Studente[], int);
void acquisisciEsami(Studente, int);
void stampa(Studente[], int);
void stampaEsami(ListaEsame);
void init(Studente archivio[], int n){
int i;
int nEsami;
for(i = 0; i < n; i++){
printf("Studente n. %d\n", i+1);
printf("Inserire matricola: ");
scanf("%d", &archivio[i].matricola);
printf("Inserire nome: ");
scanf("%s", &archivio[i].nome);
printf("Inserire cognome: ");
scanf("%s", &archivio[i].cognome);
printf("Inserire il numero di esami svolti: ");
scanf("%d", &archivio[i].esami.numeroEsami);
nEsami = archivio[i].esami.numeroEsami;
if(nEsami != 0) {
acquisisciEsami(archivio[i], nEsami);
}
}
}
void acquisisciEsami(Studente studente, int n){
int i;
for(i = 0; i < n; i++) {
printf("Inserire nome esame:");
scanf("%s", studente.esami.listaEsami[i].nomeEsame);
printf("Inserire voto esame:");
scanf("%d", &studente.esami.listaEsami[i].voto);
}
}
void stampa(Studente archivio[], int n){
printf("\nGli studenti presenti in archivio sono:\n");
int i;
for(i = 0; i < n; i++){
printf("Studente n. %d:\n", i+1);
printf("Matricola: %d\n", archivio[i].matricola);
printf("Nome: %s\n", archivio[i].nome);
printf("Cognome: %s\n", archivio[i].cognome);
stampaEsami(archivio[i].esami);
}
}
void stampaEsami(ListaEsame esami){
int i = 0;
int n = esami.numeroEsami;
for(i = 0; i < n; i++){
printf("Nome esame: %s\n", esami.listaEsami[i].nomeEsame );
printf("Voto esame: %d\n", esami.listaEsami[i].voto);
}
}
int main(int argc, char *argv[]) {
Studente studenti[MAXSTUDENTI] ;
int n;
printf("Inserire il numero di studenti da memorizzare in archivio:\n ");
scanf("%d", &n);
init(studenti, n);
stampa(studenti, n);
return 0;
}
If input is:
Inserire il numero di studenti da memorizzare in archivio:1
Inserire matricola: 13434
Inserire nome: test
Inserire cognome: test
Inserire il numero di numero di esami svolti: 1
Inserire nome esame: asd2
Inserire voto esame: 20
it prints:
Gli studenti presenti in archivio sono:
Studente n.1:
Matricola: 13434
Nome : test
Cognome: test
Nome esame:
Voto esame: 0
Your problem is acquisisciEsami function.
It should accept Studente *, instead of a variable passed by value.
void acquisisciEsami(Studente *studente, int n)
{
int i;
for(i = 0; i < n; i++)
{
printf("Inserire nome esame:");
scanf("%s", studente->esami.listaEsami[i].nomeEsame);
printf("Inserire voto esame:");
scanf("%d", &studente->esami.listaEsami[i].voto);
}
}
So what is the problem? Your code is compiling a structure that has local scope into acquisisciEsami function and all data will be lost when function ends. So esami member of archivio[i] is not modified.
Passing archivio[i] by reference to acquisisciEsami you can change content of esami memeber of archivio[i]
Obviously the call to acquisisciEsami will be:
acquisisciEsami(&archivio[i], nEsami);
As I commented you have issue to fix:
scanf("%s", &archivio[i].nome); must be scanf("%s",archivio[i].nome);
scanf("%s", &archivio[i].cognome); should be scanf("%s",archivio[i].cognome);