In C,Print Statement not getting Printed in for loop - c

In my program, after I enter the first input. I expected the values to get printed because of the printf statement next to scanf, but for the first time alone it's not getting printed.For the next iterations and all its working correctly
Ex:
Output :
Enter input10
12
i=0,a[i]=11896224
Enter input
Code:
#include<stdio.h>
#include<stdlib.h>
int func(int *, int);
int *a;
int main()
{
int length = 5;
a = (int *)malloc(sizeof(int)*length);
for (int i = 0;i < length;i++)
{
printf("Enter input");
scanf("%d\n", &a[i]);//100,104,108,112,116
printf("i=%d,a[i]=%d\n", i, &a[i]);/*Print Statement which is not executing for first time*/
}
func(a, length);
return 0;
}
int func(int *b, int length)
{
printf("Length=%d", length);
for (int j = 0;j < length;j++)
printf("b[%d]=%d", j, b[j]);//
return 0;
}

Remove the \n from the scanf function.

Related

using output of a program as input in same program

I am writing a program to generate all possible permutations of a given series of numbers and then generate all possible binary trees from that permutations so, what I thought is having a program which generates permutations and stores the result to a file and then write further code to read line by line (which has all permutations ) and generate binary trees out of them, so right now I have written half program which generates permutation and it stores the result in file.
#include <stdio.h>
//function to print the array
void printarray(int arr[], int size)
{
FILE *fp;
int i,j;
fp=fopen("result.txt","w");
for(i=0; i<size; i++)
{
// printf("%d\t",arr[i]);
fprintf(fp,"%d\t",arr[i]);
}
printf("\n");
fclose(fp);
}
//function to swap the variables
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
//permutation function
void permutation(int *arr, int start, int end)
{
if(start==end)
{
printarray(arr, end+1);
return;
}
int i;
for(i=start;i<=end;i++)
{
//swapping numbers
swap((arr+i), (arr+start));
//fixing one first digit
//and calling permutation on
//the rest of the digits
permutation(arr, start+1, end);
swap((arr+i), (arr+start));
}
}
int main()
{
//taking input to the array
int size;
printf("Enter the size of array\n");
scanf("%d",&size);
int i;
int arr[size];
for(i=0;i<size;i++)
scanf("%d",&arr[i]);
//calling permutation function
permutation(arr, 0, size-1);
return 0;
}
but the problem here in this program is that this program only stores one permutation and does not stores other permutations in result.txt file, how do I go on storing result this way. Also program does not ends a blank cursor blinking which gives a false impression of infinite while loop.
I had to press Ctrl+c to end the program how to get rid of this?
your fopen("result.txt","w"); truncates file each time opened.
use fopen("result.txt","a"); instead
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#define N 10
void print(int *num, int n)
{
FILE *fp;
fp=fopen("result.txt","a");
int i;
for ( i = 0 ; i < n ; i++)
// printf("%d ", num[i]);
fprintf(fp,"%d ",num[i]);
fprintf(fp,"\n");
fclose(fp);
}
int main()
{
int num[N];
int *ptr;
int temp;
int i, n, j;
printf("\nHow many number you want to enter: ");
scanf("%d", &n);
printf("\nEnter a list of numbers to see all combinations:\n");
for (i = 0 ; i < n; i++)
scanf("%d", &num[i]);
for (j = 1; j <= n; j++) {
for (i = 0; i < n-1; i++) {
temp = num[i];
num[i] = num[i+1];
num[i+1] = temp;
print(num, n);
}
}
return 0;
}

I have an exercise of c

My exercise is input list integer numbers from keyboard and the end of program by 0. Then print sum of array. This is my code:
#include <stdio.h>
#include <stdlib.h>
const int MAX_ITEMS = 50;
void inputIntegerNumber(int* a, int* count);
int sumOfInteger(int* n, int* count);
int main(int argc, char** argv) {
int x[MAX_ITEMS], count;
inputIntegerNumber(&x, &count);
printf("Sum of array is %d", sumOfInteger(&x, &count));
return (EXIT_SUCCESS);
}
void inputIntegerNumber(int* a, int* count ){
do{
printf("Please! input numbers: ");
scanf("%d", a);
*count++;
}while((*a != 0) && (*count != MAX_ITEMS));
}
int sumOfInteger(int* n, int* count){
int sum = 0;
for (int i = 0; i < *count; i++)
sum += *n;
return sum;
}
I don't know what's wrong with it? It doesn't give me a result same my thinks...
There are some problems like -
inputIntegerNumber(&x, &count);
printf("Sum of array is %d", sumOfInteger(&x, &count));
in both calls you pass &x but x is an array of int and your function expects int * not int (*)[]. This must have given an error atleast.
For both functions you can just pass the array x directly.
And in your function inputIntegerNumber this -
*count++;
You need to increment value of count, so it should be (*count)++. Dereference first and then increment the value.
You are doing some mistakes in your code like passing pointer to a pointer &x value(since array is basically a pointer to some memory location) and overwriting the same location again and again. In scanf("%d", a); you are overwriting the first location again and again without changing a in you input loop.You need to learn about arrays and their usage. In sumOfInteger function also you're not changing the value of n. I changed you code a bit and i was able to see desired output.
#include <stdio.h>
#include <stdlib.h>
const int MAX_ITEMS = 50;
void inputIntegerNumber(int* a, int* count);
int sumOfInteger(int* n, int* count);
int main(int argc, char** argv) {
int x[MAX_ITEMS], count = 0; // zero elements in array
inputIntegerNumber(x, &count);
printf("Sum of array is %d", sumOfInteger(x, &count));
return (EXIT_SUCCESS);
}
void inputIntegerNumber(int* a, int* count ){
int aIndex = 0;
do{
printf("Please! input numbers: ");
scanf("%d", &a[aIndex]);
aIndex++;
}while((a[aIndex-1] != 0) && (aIndex != MAX_ITEMS));
*count = aIndex;
}
int sumOfInteger(int* n, int* count){
int sum = 0;
for (int i = 0; i < *count; i++)
sum += n[i];
return sum;
}
when i run it i can see :
~/Documents/src : $ ./a.out
Please! input numbers: 1
Please! input numbers: 2
Please! input numbers: 3
Please! input numbers: 0
Sum of array is 6
You're overcomplicating things. Before you sit down to write a program, always write the general steps that must be done
Read the numbers from the command line
Convert them to ints and save them in memory
Calculate the sum
Print it
Here is the revised program
#include <stdio.h>
#include <stdlib.h> /* for strtol */
#define DIE(msg) fprintf(stderr, "%s", msg); exit(EXIT_FAILURE)
int main(int argc, char *argv[])
{
int *nums;
if (argc <= 1)
DIE("Usage: [int-list]\n");
/* skip program name */
--argc;
++argv;
nums = malloc(argc * sizeof(int));
if (!nums)
DIE("Out of mem\n");
for (int i = 0; i < argc; ++i) {
char *end;
double val = strtol(argv[i], &end, 0);
if (end == argv[i]) /* no digits detected */
DIE("Usage: [int-list]\n");
nums[i] = val;
}
printf("%d\n", add(nums, argc));
free(nums);
}
int add(int arr[], size_t n)
{
int sum = 0;
for (int i = 0; i < n; ++i)
sum += arr[i];
return sum;
}
To complete the strtol error handling is an exercise for the OP.

Output is the same for every number?

This program is supposed to asks the user to enter a positive integer (the integer could be of any number of digits in the range of the integer type) and replace each digit by the sum of that digit plus 6 modulus 10. The program then should swap the first digit with the last digit before it displays the output.
A sample input/output:
Enter the number of digits of the number: 5
Enter the number: 92828
Output: 48485
For some reason with my code, no matter what number I enter, everything just comes out as 6. (so if I enter 5 numbers, I get 666666). I'm new to pointers, so is there an issue with that, or do I just have some math wrong? The program runs without any compiler warnings.
#include <stdio.h>
#include <stdlib.h>
void replace(int *a, int *b, int n);
void swap(int *p, int *q);
int main()
{
int n = 0;
int i = 0;
int a[100], b[100];
//Prompt user to enter number of digits
printf("Enter the number of digits you'd like to replace: ");
scanf("%d", &n);
//Prompt user to enter the number to use
printf("Enter the number to use: ");
for(i = 0; i < n; i++);
scanf("%1d", &a[i]);
//replace function
replace(a, b, n);
for(i = 0; i < n; i++)
printf("%d", b[i]);
printf("\n\n");
return 0;
}
void replace(int *a, int *b, int n)
{
int i;
for (i = 0; i < n; i++)
{
*(b+i) = (*(a+i)+ 6) % 10;
}
printf("The output is: ");
//swap function
swap(b, (b+ (n-1)));
}
void swap(int *p, int *q)
{
int t;
t = *p;
*p = *q;
*q = t;
}
Your code is absolutely correct except a silly mistake in the following code snippet.
for(i = 0; i < n; i++);
scanf("%1d", &a[i]);
Why did you put a ; after the for statement? It means your for loop is just iterating once (instead of 5 if n = 5). As a result, only the first digit input is considered given by the user but that too be stored in a[5] (considering n = 5), values stored in a[0] to a[4] are all garbage value.
Just remove the semicolon and update your code as follows.
for(i = 0; i < n; i++)
scanf("%1d", &a[i]);
Now it works fine.
The culprit in your code is the semicolon after the for loop:
for(i = 0; i < n; i++)**;**
scanf("%1d", &a[i]);
So the scanf that you wrote is basically out of the for-loop and stores the first digit into a[n].

Reading and printing matrix in C

Ok so my main goal is to multiply two matrices.Before jumping there i proposed myself to write 2 functions to read and display a matrix. Basic stuff i thought.
After i run the program and i enter the number of lines and columns,i can only enter 1 value before it crashes.
I use Dev c++.
What could the issue be here? Thank you in advance.
#include <stdio.h>
#define MAXSIZE 20
void readM(int M[MAXSIZE][MAXSIZE],int,int);
void printM(int M[MAXSIZE][MAXSIZE],int,int);
int main ()
{
int NL,NC,i,j;
int M[20][20];
readM(M[20][20],NL,NC);
printM(M[20][20],NL,NC);
return 0;
}
void readM(int M[20][20],int NL,int NC)
{
int i,j;
printf("Type in number lines ");
scanf("%d",&NL);
printf("Type in number of columns ");
scanf("%d",&NC);
printf("Type in values \n");
for(i=0;i<NL;i++)
{
for(j=0;j<NC;j++)
{
scanf("%d",&M[i][j]);
}
}
}
void printM(int M[20][20],int NL,int NC)
{
int i,j;
printf("Matrix is \n");
for(i=0;i<NL;i++)
{
for(j=0;j<NC;j++)
{
printf("\t%d\t",M[i][j]);
}
printf("\n");
}
}
First, when you call readM and printM, you should call them using M, not M[20][20].
Then, there's the lines and columns problem. When you pass the arguments NL and NC to readM, you're passing a copy of their values inside main. When you read the values in readM you'll store what you read locally, and main will never know about it.
To change that, you could use pointers or you could read the lines and columns in main, leaving readM with the sole purpose of reading matrix itens.
The program may be skipping your input because there's trash in the input buffer. The best way of getting user input is creating a custom function that reads whatever there is in stdin, and then treat it accordingly. Because you never know what users will input...
Here's the code with my suggestions:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20
void readM(int M[MAXSIZE][MAXSIZE], int, int);
void printM(int M[MAXSIZE][MAXSIZE], int, int);
/* very simple function to treat user input */
int read_num(void)
{
char buf[50];
fgets(buf, 50, stdin);
return atoi(buf);
}
/* if main() won't take any arguments, use void */
int main(void)
{
int NL, NC, i, j;
int M[20][20];
/* extracted from readM */
printf("Type in number lines ");
NL = read_num();
printf("Type in number of columns ");
NC = read_num();
readM(M, NL, NC);
printM(M, NL, NC);
return 0;
}
void readM(int M[MAXSIZE][MAXSIZE], int NL, int NC)
{
int i, j;
printf("Type in values \n");
for (i = 0; i < NL; i++) {
for (j = 0; j < NC; j++) {
M[i][j] = read_num();
}
}
}
void printM(int M[MAXSIZE][MAXSIZE], int NL, int NC)
{
int i, j;
printf("Matrix is \n");
for (i = 0; i < NL; i++) {
for (j = 0; j < NC; j++) {
printf("\t%d\t", M[i][j]);
}
printf("\n");
}
}

Recursive function calculating average from int array three by three elements

Calculating average three by three elements and replacing those elements with the average result.
Example array [1,2,7,-2,5,0, 2,8]
After transformation [3,3,3,1,1,1,5,5]
Something is wrong, I can't get it to work.
#include <stdio.h>
int main ( ) {
int n, c[n];
int *avg;
int pom=0;
printf("Enter lenght of array\n");
scanf("%d",&n);
printf("Enter elements");
for(i = 0;i < n; i++)
scanf("%d",c[i]);
avg=Average(c , n, pom);
for(i = 0; i < n; i++)
printf("Avg elements= %d",*(avg+i))
return 0;
}
int Average(int arr[], int size, int z)
{
int k, l, m, Asum;
if (size < 0) {
return arr;
} else {
k=arr[z];
l=arr[z+1];
m=arr[z+2];
Asum=(k + l + m)/3;
arr[z]=Asum;
arr[z+1]=Asum;
arr[z+2]=Asum;
}
return Average(arr,size--,z++);
}
int n, c[n]; is a problem. n is uninitialized so the size of the array is who-knows-what? This is undefined behavior.
Instead
int main(void) {
int n;
int *avg;
int pom=0;
printf("Enter length of array\n");
if (scanf("%d",&n) != 1) return -1;
int c[n];
for(i = 0;i < n; i++)
// scanf("%d",c[i]);
scanf("%d",&c[i]); // pass the address of an `int`
Likely other issues too.
Try simple input first, imagine what happens when you enter only 1 number, what will the Average function do? Don't run the code but try to execute it in your head or with pencil and paper. If you think the program only has to work with three or more numbers, try three.
A serious program would explicitly reject invalid input.

Resources