Problems in the for loop in language C - c

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");
}

Related

a matrix not printing correctly in c

I don't know why mat[7][8]='A' prints A in the whole column. The procedure is a game grid where we should put pions of gamers and maintain all their previous pions on the grid. I don't know why changing the value of this matrix outside a for loop doesn't do anything right as it supposed to be.
Here is the code:
#include "Go_1.h"
#define DIMENSION 9
#define SPACELEFT 2
/* cette donction permet d'affichier la matrice à l'état initial, de placer le pion du joueur à
l'intersection en analysant si la place est vide ou pas, et d'afficher la grille avec les pions
des joueurs*/
void grille(char mat[][TAILLE_MATRICE], int *x, int *y,char jeton,char *joueur,char lettres[],char nombres[])
{
int a=0; /* servira de compteur pour afficher tous les caracteres de A--I en utilsant le code ASCII*/
int b=1;
const int LIGNE_COLONNE=(SPACELEFT-1)*(DIMENSION-1)+ DIMENSION;/* = 25// nb de lignes et colonnes où
on doir afficher les valeurs de la matrice stockées dans LIGNE_COLONNE(25) lignes et colonnes*/
printf("\t");
printf(" "); /*2 spaces*/
/*affichage des lettres délimitant le goban horizontalement*/
for(int j=0;j<DIMENSION;j++)
{
printf("%c", 'A'+a);
a++;
for (int k=0; k<(2*SPACELEFT-1);k++)
{
printf(" "); /*5 spaces 5= 2*SPACELEFT-1 */
}
}
printf("\n");
/*Remplissage de la matrice*/
for (int i=0;i<LIGNE_COLONNE;i+=SPACELEFT)
{
for (int j=0;j<LIGNE_COLONNE;j+=SPACELEFT)
{
mat[i][j]='0';
}
}
mat[7][8]='A';
/*affichage des nombres délimitant le goban verticalement*/
for (int i=0;i<LIGNE_COLONNE;i++) /* LIGNE_COLONNE in this case= 25*/
{
printf("\t");
if (i%SPACELEFT==0)
{
printf("%d ",b);
b++;
}
else
printf(" ");
for (int j=0; j<LIGNE_COLONNE;j++)
{
if ((i%SPACELEFT==0)&&(j%SPACELEFT==0)) /* le cas où mat[i][j] est une intersection*/
{
/*if (i==*x && j==*y) /*tester si les indices coincident avec ceux choisis par le joueur
{
if (mat[*x][*y]=='0') /*tester si l'intersection ets vide cad contient '0'*
{
mat[*x][*y]=jeton;
}
else
{
printf("\tLa place est deja occupee!");
choix_pion(joueur,jeton,x,y,lettres,nombres);/*on lui demande de réexprimer
son choix où placer son pion
break;
}
} */
printf("%c ",mat[i][j]);
}
else if ((i%SPACELEFT==0)&&(j%SPACELEFT!=0))
printf("* ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT!=0))
printf(" ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT==0))
printf("* ");
}
printf("\n");
}
return;
}
Well, I refactored the code a bit and I get the following output:
A B C D E F G H I
Since I did not know how to define TAILLE_MATRICE I just assigned 64
That's the code for anyone wanting to try it out:
#include<stdio.h>
#define DIMENSION 9
#define SPACELEFT 2
#define TAILLE_MATRICE 64
int main(char mat[][TAILLE_MATRICE], int *x, int *y,char jeton,char
*joueur,char lettres[],char nombres[])
{
int a=0;
int b=1;
const int LIGNE_COLONNE=(SPACELEFT-1)*(DIMENSION-1)+ DIMENSION;
printf("\t");
printf(" ");
for(int j=0;j<DIMENSION;j++)
{
printf("%c", 'A'+a);
a++;
for (int k=0; k<(2*SPACELEFT-1);k++)
{
printf(" "); /*5 spaces 5= 2*SPACELEFT-1 */
}
}
printf("\n");
for (int i=0;i<LIGNE_COLONNE;i+=SPACELEFT)
{
for (int j=0;j<LIGNE_COLONNE;j+=SPACELEFT)
{
mat[i][j]='0';
}
}
mat[7][8]='A';
for (int i=0;i<LIGNE_COLONNE;i++)
{
printf("\t");
if (i%SPACELEFT==0)
{
printf("%d ",b);
b++;
}
else
printf(" ");
for (int j=0; j<LIGNE_COLONNE;j++)
{
if ((i%SPACELEFT==0)&&(j%SPACELEFT==0))
{
printf("%c ",mat[i][j]);
}
else if ((i%SPACELEFT==0)&&(j%SPACELEFT!=0))
printf("* ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT!=0))
printf(" ");
else if ((i%SPACELEFT!=0)&&(j%SPACELEFT==0))
printf("* ");
}
printf("\n");
}
return 0;
}

I am trying to make a scanf that checks if the user has input only numbers or char mixed with numbers

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;
}

User input not being passed to function

I am working on a college project and we're supposed to write a basic CRUD program in C. In case 1 of my switch, "cpfinput" is passed fine to my function inserir_servidor, but "nominput" (name) is not. I tried debugging it and nominput does actually contain the user input, but when I print my "nomes" array after calling the function, it's empty.
Please forgive me if this is a poorly written post, I am new to SO.
How to reproduce:
1 - Type 1 and press enter.
2 - Enter anything.
3 - Enter anything.
4 - Type 5, it should display "0, a blank, and whatever your inserted in step 3.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TAM 100
char codigos[TAM][9];
char nomes[TAM][255];
char cpfs[TAM][11];
int ocupados[TAM];
int inserir_servidor(char[], char[]);
int alterar_servidor(char[], char[], char[]);
int excluir_servidor(char[]);
int mostrar_servidor(char[]);
int mostrar_servidores();
void inic_ocupados();
int main()
{
char codinput[9], nominput[255], cpfinput[11];
int input = -1;
inic_ocupados();
do
{
printf("1. Inserir um servidor.\n");
printf("2. Alterar um servidor.\n");
printf("3. Excluir um servidor.\n");
printf("4. Mostrar um servidor.\n");
printf("5. Mostrar todos os servidores.\n");
printf("0. Sair do programa.\n");
printf("Escolha: ");
scanf("%d", &input);
switch(input)
{
case 0:
printf("Encerrando...");
return 0;
case 1: //inserir
printf("Insira o nome do servidor: ");
scanf(" %s", nominput);
printf("Insira o cpf do servidor: ");
scanf(" %s", cpfinput);
inserir_servidor(nominput, cpfinput);
break;
case 2: //alterar
printf("Insira o codigo do servidor: ");
scanf(" %s", codinput);
printf("Insira um novo nome: ");
scanf(" %s", nominput);
printf("Insira um novo cpf: ");
scanf(" %s", cpfinput);
alterar_servidor(codinput, nominput, cpfinput);
break;
case 3: //excluir
printf("Digite o codigo do servidor a ser excluido: ");
scanf(" %s", codinput);
excluir_servidor(codinput);
break;
case 4: //listar um
printf("Digite o codigo do servidor a ser mostrado: ");
scanf(" %s", codinput);
mostrar_servidor(codinput);
break;
case 5: //listar todos
mostrar_servidores();
break;
default:
printf("Escolha invalida.\n");
break;
}
} while(input);
return 0;
}
int inserir_servidor(char nominput[], char cpfinput[])
{
for(int i = 0; i < TAM; i++)
{
if (!ocupados[i])
{
itoa(i, codigos[i], 10);
strcpy(nomes[i], nominput);
strcpy(cpfs[i], cpfinput);
ocupados[i] = 1;
return 1;
}
}
return 0;
}
int alterar_servidor(char codinput[], char nominput[], char cpfinput[])
{
for(int i = 0; i < TAM; i++)
{
if(!strcmp(codigos[i], codinput))
{
strcpy(nomes[i], nominput);
strcpy(cpfs[i], cpfinput);
return 1;
}
}
return 0;
}
int excluir_servidor(char codinput[])
{
for(int i = 0; i < TAM; i++)
{
if(!strcmp(codigos[i], codinput))
{
ocupados[i] = 0;
return 1;
}
}
return 0;
}
int mostrar_servidor(char codinput[])
{
for(int i = 0; i < TAM; i++)
{
if(!ocupados[i])
{
if(!strcmp(codigos[i], codinput))
{
printf("Codigo \t Nome \t CPF\n");
printf("%s \t %s \t %s\n", codigos[i], nomes[i], cpfs[i]);
return 1;
}
}
}
return 0;
}
int mostrar_servidores()
{
for(int i = 0; i < TAM; i++)
{
if(ocupados[i])
{
printf("Codigo \t Nome \t CPF\n");
printf("%s \t %s \t %s\n", codigos[i], nomes[i], cpfs[i]);
}
}
return 0;
}
void inic_ocupados()
{
for(int i = 0; i < TAM; i++)
{
ocupados[i] = 0;
}
}
I cannot find the error you report.
1. Inserir um servidor.
2. Alterar um servidor.
3. Excluir um servidor.
4. Mostrar um servidor.
5. Mostrar todos os servidores.
0. Sair do programa.
Escolha: 1
Insira o nome do servidor: aaaaa
Insira o cpf do servidor: bbbbb
1. Inserir um servidor.
2. Alterar um servidor.
3. Excluir um servidor.
4. Mostrar um servidor.
5. Mostrar todos os servidores.
0. Sair do programa.
Escolha: 5
Codigo Nome CPF
0 aaaaa bbbbb
1. Inserir um servidor.
2. Alterar um servidor.
3. Excluir um servidor.
4. Mostrar um servidor.
5. Mostrar todos os servidores.
0. Sair do programa.
Escolha:
There are multiple errors in the code.
First scanf(" %s",... looks for space delimted input so if I enter this
Escolha: 1
Insira o nome do servidor: mr smith <<<<<=========
Insira o cpf do servidor: 1. Inserir um servidor.
2. Alterar um servidor.
3. Excluir um servidor.
4. Mostrar um servidor.
5. Mostrar todos os servidores.
0. Sair do programa.
Escolha:
The 'mr' is taken as 'nom' and 'smith' is taken as 'cpf'
Also this function
int mostrar_servidor(char codinput[])
{
for (int i = 0; i < TAM; i++)
{
if (!ocupados[i])
{
if (!strcmp(codigos[i], codinput))
{
printf("Codigo \t Nome \t CPF\n");
printf("%s \t %s \t %s\n", codigos[i], nomes[i], cpfs[i]);
return 1;
}
}
}
return 0;
}
Is broken.
It only looks at unoccupied cells
if (!ocupados[i])
should be
if (ocupados[i])

Is there any way to make the scanf() function ignore invalid characters?

So, I've made this code, and it works wonderfully, but the problem is that I've got some scanf functions only accepting numbers, and some others only accepting characters, but for example, when I input a character on a scanf that requires an int value, the program behaves really unexpectedly, doing stuff such as repeating the same printf all over the command prompt, or repeating it thrice.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int descuento(int num, int descuento);
int rangoValido(int Rangomin, int Rangomax, int i);
int numeroRandom();
int sino(char sino);
int main(void){
int productoid[1000][1];
int idprompt;
int descuento25[14] = {398, 309, 281, 948, 19, 67, 187, 80, 889, 482, 566, 24, 87, 98};
int descuento15[14] = {992, 788, 987, 90, 155, 596, 27, 587, 98, 273, 344, 69, 89, 234};
char respuesta;
int listacompra[100][1];
int precio;
int colector = 0;
int comprobante = 0;
int total;
int monto;
//Si la id del producto no esta dentro del rango valido, el bloque se repite
do{
do{
do{
printf("Escriba la ID del producto: ");
scanf("%d", &idprompt);
}
while(0==rangoValido(1,1000,idprompt));
//Una vez comprobada la validez del numero ingresado, se crea un numero aleatorio que se le
asigna para el precio, idprompt es la misma id
comprobante = 0;
srand(idprompt);
productoid[idprompt][1]=numeroRandom();
printf("ID del producto: %d\n", idprompt);
printf("Precio del producto: %d\n", productoid[idprompt][1]);
precio = productoid[idprompt][1];
//Comprobacion de descuentos
for(int i=0; i<=14; i++){
if(descuento25[i]==idprompt){
productoid[idprompt][1] = descuento(productoid[idprompt][1],25);
printf("Descuento del producto: 25\n");
}else{
if(descuento15[i]==idprompt){
productoid[idprompt][1] = descuento(productoid[idprompt][1],15);
printf("Descuento del producto: 15\n");
}
}
}
//Anadiendo el producto al carro de compras y comprobando la respuesta
do{
printf("Quieres anadir este producto a tu carrito de compras? (Y/N) ");
scanf(" %c", &respuesta);
}while(2 == sino(respuesta));
}while(respuesta == 'n' || respuesta == 'N');
if(respuesta == 'y' || respuesta == 'Y'){
listacompra[colector][0] = idprompt;
listacompra[colector][1] = precio;
colector = colector + 1;
}
do{
printf("Quieres seguir comprando? (Y/N) ");
scanf(" %c", &respuesta);
printf("\n");
if(0 == sino(respuesta)){
for(int i=0; i<colector; i++){
printf("\nID del producto %d: %d\n", i+1, listacompra[i][0]);
printf("Precio del producto %d: %d\n", i+1, listacompra[i][1]);
}
}
if(1==sino(respuesta)){
comprobante = 1;
}
}while(2==sino(respuesta));
}while(comprobante==1);
for(int i=0; i<colector; i++){
total = total + listacompra[i][1];
}
printf("\n\nTotal a pagar: %d\n", total);
printf("Ingrese monto recibido: ");
scanf("%d", &monto);
printf("\n");
if(monto<total){
printf("%d faltantes.", total-monto);
}
if(monto>=total){
printf("Vuelto: %d", monto-total);
}
return 0;
}
int numeroRandom(){
int random;
random = rand();
if(random>3000 && random<10000){
random = random / 5;
}
if(random<100){
random = random * 3;
}
if(random>10000){
random = random / 13;
}
return random;
}
int rangoValido(int Rangomin, int Rangomax, int i){
if(i>=Rangomin && i<=Rangomax){
return 1;
}else{return 0;}
}
int descuento(int num, int descuento){
num = num * (descuento / 100);
return num;
}
//Si la funcion sino() regresa 0, entonces la respuesta fue no. Si es 1, la respuesta es si. Y si
es 2, la respuesta es invalida.
int sino(char sino){
if(sino=='y' || sino=='Y'){
return 1;
}
if(sino=='n' || sino=='N'){
return 0;
}
else{return 2;}
}

C For only print last index input

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.

Resources