Why is this program running fine till a is 5. [as soon as a becomes 6, the program prints its last value (i.e., '000007') and ends without even printing the 'Program END' msg, in the last and without even executing the last getch();] While this program is supposed to work like: print a-1 number of 0 and print 7 at last; this process should repeat itself every time the user enters any character, with an increment in the value of a. I want all of this to happen at the center, an wanted the '7' to be printed seperately, so I used created gotoxy function, and printed the 7 seperately.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
void gotoxy(int x, int y)
{
COORD c;
c.X = x;
c.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
/* X = 0-80
AND Y= 0-25*/
}
int main()
{
int a = 2;
int *ptr;
int k=40;
for (int j = 1; j >= 1; j++)
{
system("cls");
ptr = (int *)calloc(a, sizeof(int));
gotoxy(k, 13);
*(ptr + a) = 7;
// ptr[1] = 0;
for (int i = 1; i < 2; i++)
{
printf("%d",ptr[a]);
}
gotoxy(39, 13);
for (int i = 1; i < a; i++)
{
printf("%d", ptr[i]);
}
a++;
k++;
free(ptr);
getch();
}
printf("\nProgram END");
getch();
return 0;
}
Related
I made a 2 dimension array where I have to type 16 numbers and the program should return me the biggest value and its location (This is just an exercise, I know I can just use an array with 16 values instead of 4x4)
#include <stdlib.h>
#define CONSTC 4
#define CONSTL 4
int main ()
{
int i=1;
int e;
int k;
int c;
int a;
int A [CONSTR][CONSTC];
for (k=0; k<CONSTL; k++)
{
for (c=0; c<CONSTC; c++, i++)
{
printf ("%2d - Type number\n", i);
scanf ("%d", &A [k][c]);
}
}
e = Matriz [0][0];
for (k=0; k<CONSTL; k++)
{
for (c=0; c<CONSTC; c++, i++)
{
if (e>A[k][c])
{
e = A [k][c];
return k;
return c;
}
}
}
printf ("\t\tBiggest Value = %d\nValue Location = %d %d", e, k, c);
}
I corrected some stuff in your code
#include <stdlib.h>
#include <stdio.h> //you need to include this to use printf and scanf
#define CONSTC 4
#define CONSTL 4
int main()
{
int i=1;
int e;
int k;
int c;
int a;
int A [CONSTL][CONSTC];
for (k=0; k<CONSTL; k++)
{
for (c=0; c<CONSTC; c++, i++)
{
printf ("%2d - Type number\n", i);
scanf ("%d", &A [k][c]);
}
}
e = A[0][0];//Not sure what Matriz was, you meant A right?
for (k=0; k<CONSTL; k++)
{
for (c=0; c<CONSTC; c++, i++)
{
if (e>A[k][c])
{
e = A [k][c];
//return k;
//return c;
}
}
}
printf ("\t\tBiggest Value = %d\nValue Location = %d %d", e, k, c);
return 0;
}
The main problem was that you let return k and return c in the middle of the loop, return stops the whole process and the whole program.
So you never get to the last printf.
Also, if you need the biggest value, you would need your if statement to be if(e < A[k][c]).
There are several problems in the code:
The return statement would return the given code to the main(), which makes no sense.
Some variables aren't declared which is a huge error.
Defined stdlib.h but I/O operations does exists in stdio.h library.
After the first return statement, the second will never get executed.
Code redefined:
#include <stdio.h>
#define MAX_ROWS 4
#define MAX_COLS 4
int main(void) {
int mat[MAX_ROWS][MAX_COLS];
int max = 0;
int posM, posN;
printf("Enter [4 x 4] Matrix below: \n");
for (int i = 0; i < MAX_ROWS; i++)
for (int j = 0; j < MAX_COLS; j++)
scanf("%d", &mat[i][j]); // getting the values of i * j positon
for (int i = 0; i < MAX_ROWS; i++)
for (int j = 0; j < MAX_COLS; j++)
if (mat[i][j] > max) {
max = mat[i][j]; // if max is lesser than the current one, then assign
posM = i + 1; // we had started the counting from 0, so increased 1
posN = j + 1;
}
printf("The largest element in the matrix: %d\n", max);
printf("The position is: %d x %d\n", posM, posN); // simply get the value
return 0;
}
The program simply asks the user to fill 4 ✕ 4 multidimensional array values. And then a loop is executed once as soon as the first loop quits.
The second loop tries to find the maximum value held by the matrix array. If the current value is lesser than the previously scanned value, it's then assigned. This process continues until the loop ends and finally displays the results.
A sample output:
Enter [4 x 4] Matrix below: // --- INPUT
1 2 3 4
4 3 2 1
3 3 3 4
5 4 3 1
The largest element in the matrix: 5 // --- OUTPUT
The position is: 4 x 1
The return; statement ends the function. When there's an expression afterwards, e.g. return k;, the result of the function is k.
Since the return statement exits from the function main, no more code runs after that point. This is why no output is printed.
I would like to create a char array, print it, reorganize it, and then reprint it in C. Here's what I have so far:
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
int i = 0;
int j = 0;
char k[4][2];
char thing[1][1];
strcpy(k[0] , "A");
strcpy(k[1] , "B");
strcpy(k[2] , "C");
strcpy(k[3] , "D");
printf("\nThe original order is: \n");
for (int i = 0; i < 4; i++) { // fill
printf("%s,", k[i]);
}
printf("\nThe reordering is: \n");
for (int i = 0; i < 4; i++) { // reorder
strcpy(thing[0], k[i]);
j = (int)(i + rand() / (RAND_MAX / (5 - i)) );
strcpy(k[i], k[j]);
strcpy(k[j], thing[0]);
printf("%s,", k[i]); // print
}
return(0);
}
Here's my Terminal Output. There are no warnings, just the abort.
mac% clang thing.c -o thing
mac% ./thing
The original order is:
A,B,C,D,
The reordering is:
zsh: abort ./thing
I figured it out! Here's the solution I came up with:
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
int i = 0;
int j = 0;
char k[4] = "ABCD";
char thing[1] = "O";
printf("\nThe original order is: \n");
for (int i = 0; i < 4; i++) { // fill
printf("%c,", k[i]);
}
printf("\nThe reordering is: \n");
for (int i = 0; i < 4; i++) { // reorder
thing[0]= k[i];
j = (int)(i + rand() / (RAND_MAX / (4 - i)) );
k[i]= k[j];
k[j]= thing[0];
printf("%c,", k[i]); // print
}
return(0);
}
And the output is
The original order is:
A,B,C,D,
The reordering is:
A,B,D,C,%
Can't get my program to output the correct number. I feel like I am making a simple mistake. This is written in C.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
int list[n];
while(1)
{
scanf("%d", &n);
if(n == -1)
{
break;
}
else
{
for(i = 2; i < n; i++)
{
list[i] = list[i-1]+list[i-2];
}
printf("%d %d", i, list[i] );
}
}
}
(To make things simpler, I'm going to ignore dealing with input.)
First problem is turning on compiler warnings. Most C compilers don't give you warnings by default, you have to ask for them. Usually by compiling with -Wall. Once we do that, the basic problem is revealed.
test.c:6:14: warning: variable 'n' is uninitialized when used here [-Wuninitialized]
int list[n];
^
test.c:5:10: note: initialize the variable 'n' to silence this warning
int n, i;
^
= 0
1 warning generated.
int list[n] immediately creates a list of size n. Since n is uninitialized it will be garbage. You can printf("%d\n", n); and see, it'll be something like 1551959272.
So either n needs to be initialized, or you need to reallocate list dynamically as n changes. Dynamic allocation and reallocation gets complicated, so let's just make it a static size.
So we get this.
#include <stdio.h>
#include <stdlib.h>
int main() {
/* Allocate an array of MAX_N integers */
const int MAX_N = 10;
int list[MAX_N];
/* Do Fibonacci */
for(int i = 2; i < MAX_N; i++) {
list[i] = list[i-1]+list[i-2];
}
/* Print each element of the list and its index */
for( int i = 0; i < MAX_N; i++ ) {
printf("%d\n", list[i]);
}
}
That runs, but we get nothing but zeros (or garbage). You have a problem with your Fibonacci algorithm. It's f(n) = f(n-1) + f(n-2) with the initial conditions f(0) = 0 and f(1) = 1. You don't set those initial conditions. list is never initialized, so list[0] and list[1] will contain whatever garbage was in that hunk of memory.
#include <stdio.h>
#include <stdlib.h>
int main() {
/* Allocate an array of MAX_N integers */
const int MAX_N = 10;
int list[MAX_N];
/* Set the initial conditions */
list[0] = 0;
list[1] = 1;
/* Do Fibonacci */
for(int i = 2; i < MAX_N; i++) {
list[i] = list[i-1]+list[i-2];
}
/* Print each element of the list and its index */
for( int i = 0; i < MAX_N; i++ ) {
printf("%d\n", list[i]);
}
}
Now it works.
0 0
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34
Here is code snippet,
#include <stdio.h>
int main()
{
int MAX_SIZE = 100; //Initial value
int n, i;
int list[MAX_SIZE];
printf("Enter value of 'n'");
scanf("%d",&n);
if(n < 0){
printf("'n' cannot be negative number");
return 0;
}else if (n==1){
list[0]=0;
}else if(n == 2){
list[0]=0;
list[1]=1;
}else{
list[0]=0;
list[1]=1;
for(i = 2; i <= n; i++)
{
list[i] = list[i-1]+list[i-2];
}
}
//To view array elements
for(int i=0;i<n;i++){
printf("%3d",list[i]);
}
}
You don't have return in main function.
n must be defined previous. Otherwise it took random value from memory.
So, your list array is created with unknown value.
int list[n];
Also, this will never happends, becous n is declared, but not defined.
i < n;
Is this what you need?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int F[100];
F[0] = 0;
F[1] = 1;
int i = 2;
while(1)
{
if(i < 100)
{
F[i] = F[i-1] + F[i-2];
i++;
}
else
{
break;
}
}
i = 0;
while(1)
{
if(i < 100)
{
printf("%d ; ", F[i]);
i++;
}
else
{
break;
}
}
return 0;
}
You need to allocate memory on demand for each iteration. In your code, n is uninitalized which leads to unpredectiable behavior. Also you need to initialize list[0] and list[1] since this is the 'base' case.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
int* list; /* Declare a pointer to the list */
while(1)
{
scanf("%d", &n);
if(n == -1)
{
break;
}
else if ( n > 0 )
{
list = (int *) malloc( n * sizeof(int) );
list[0] = 1;
list[1] = 1;
for(i = 2; i < n; i++)
{
list[i] = list[i-1]+list[i-2];
}
printf("%d %d\n", i, list[i-1] );
free(list);
}
}
}
I updated my main and sequetialSearch and now it crashes when it runs. It compiles okay, but then crashes.
main.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include "percentage.h"
#include "sequentialSearch.h"
#define searchAmount 100
int main(int argc, char *argv[])
{
int numbers[100];
int searches[searchAmount];
int testAmounts[searchAmount];
int i;
int where;
int searchSuccess;
int searchUnsuccess;
int percent;
int looker;
int sum;
int average;
srand(time(NULL));
for (i = 0; i < 100; i++){
numbers[i] = rand() % 200;
}
for (i = 0; i < searchAmount; i++){
searches[i] = rand() % 200;
}
searchUnsuccess = 0;
searchSuccess = 0;
sum = 0;
for(i = 0; i < searchAmount; i++){
if(seqSearch(numbers, 100, searches[i], &where, &looker)){
searchSuccess++;
testAmounts[i] = looker;
}else{
searchUnsuccess++;
testAmounts[i] = looker;
}
}
for(i = 0; i < searchAmount; i++){
sum = sum + testAmounts[i];
}
average = sum / searchAmount;
percent = percentRate(searchSuccess, searchAmount);
printf("Total number of searches: %d\n", searchAmount);
printf("Total successful searches: %d\n", searchSuccess);
printf("Success Rate: %d%%\n", percent);
printf("Total number of tests ran: %d\n", average);
system("PAUSE");
return 0;
}
sequentialSearch.h
bool seqSearch (int list[], int last, int target, int* locn, int* looker){
*looker = 0;
while(*looker < last && target != list[*looker]){
*looker++;
}
*locn = *looker;
return(target == list[*looker]);
}
Pass looker in by reference, so that you can access its value from the caller.
int looker;
...
for(i = 0; i < searchAmount; i++){
if(seqSearch(numbers, 100, searches[i], &where, &looker)){
searches[i] += looker;
searchSuccess++;
}else{
searchUnsuccess++;
}
}
bool seqSearch (int list[], int last, int target, int* locn, int *looker){
*looker = 0;
while(*looker < last && target != list[*looker]){
(*looker)++;
}
*locn = *looker;
return(target == list[*looker]);
}
By the way, you may wish to reconsider defining functions in your header file; this could cause problems with duplicate symbol when linking if you have more than one c file including this file.
Why not just pass looker in as an int*, use it essentially as you have been, look at the value after seqSearch(...) returns, and add it to a running total back in main()?
One problem is that the increment of looker in seqSearch is incrementing the pointer rather than the value. It should probably be:
(*looker)++;
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void initDeck (int deck[]);
void showDeck (int deck[]);
void shuffleDeck (int deck[]);
int getBet ();
main()
{
int deck[52];
int playerBet;
char z;
initDeck(deck);
shuffleDeck(deck);
showDeck(deck);
playerBet = getBet();
//scanf ("%d\n", &playerBet);
printf("%d\n", playerBet);
z = 1;
getchar(z);
return 0;
}
void initDeck (int deck[]){
int k;
int i;
for (k = 1; k < 53; k++){
i = k - 1;
deck[i] = k;
}
return;
}
void showDeck (int deck[]){
int k;
for (k = 0; k < 52; k++){
printf("%d\n", deck[k]);
}
return;
}
void shuffleDeck (int deck[]){
int random;
int k;
int temp;
srand(time(0));
for (k = 52; k > 1; k--){
random = (rand() % k) + 1;
if (random != k){
temp = deck[k - 1];
deck[k - 1] = deck[random - 1];
deck[random- 1] = temp;
}
else{
k++;
continue;
}
}
return;
}
int getBet (){
int bet;
scanf ("%d\n", &bet);
return bet;
}
The function at issue is getBet() and when I input an integer it doesn't give me any output. I tried doing the input in main and it worked, but I don't see the problem with this. I've double checked for small errors a few times, and I don't see anything wrong with it...
The problem is that you end your scanf string with a newline. This means (read the scanf documentation) any amount of whitespace. So when you enter "" it still waits for more white space. Try entering non-whitespace characters afterwards to see it accept the input. As Artem says, omitting the \n could be one solution.
Instead of
scanf("%d\n", &bet);
do
scanf("%d", &bet);
Just tested and it works.
I also don't see the error. Why don't you pass it by address instead?
int main()
{
int playerBet;
//
getBet(&playerBet);
}
void getBet(int* bet)
{
scanf("%d", bet);
}
I don't do C, but that is the general idea.