I have this C code and I struggle with the functions printCol(); and printRow.
When I run the code and call for these functions to print a specific column or a row, they always return the second row or column.
EDITED: I know that many functions are nonsense, but i just started to learn C, please don't be rude...
#include <stdio.h>
#include <stdlib.h>
void printRow1(int *p1, int rowSize) {
for (int i = 0; i < rowSize; i++) {
printf("%d\t", *p1);
p1 += 1;
}
}
void printCol1(int *p, int colSize) {
for (int i = 0; i < colSize; i++) {
printf("%d\n", *p);
p += 4;
}
}
void reverseRow1(int *p2) {
for (int i = 4; i > 0; i--) {
printf("%d\t", *p2);
p2-=1;
}
}
int arr[3][4] = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
void printMat() {
int col = 3;
int row = 4;
for (int i = 0; i < col; i ++) {
printf("\n");
for (int j = 0; j < row; j++) {
printf("%d\t", arr[i][j]);
}
}
}
void printCol() {
printf("Which column would you like to print? \t");
int choiceCol;
scanf("%d\n", &choiceCol);
char buf = fgetc(stdin);
if (choiceCol >= 1 && choiceCol <= 4) {
printCol1(&arr[0][choiceCol-1], 3);
} else {
printf("An Error occured\n");
}
}
void printRow() {
printf("Which row would you like to print? \t");
int choiceRow;
scanf("%d\n", &choiceRow);
char buf = fgetc(stdin);
if (choiceRow >= 1 && choiceRow <= 3){
printRow1(&arr[choiceRow-1][0], 4);
} else {
printf("An Error occured\n");
}
}
void reverseRow() {
printf("which row to reverse?: \t");
int reversedR = scanf("%d\n", &reversedR);
printf("%d\n", reversedR);
reverseRow1(&arr[0][reversedR]);
}
void printMenu() {
printf("\n");
printf("You can choose one of these services: \n");
printf("1. Print matrix tabular form. \n");
printf("2. Print a specific row or a number of rows in sequence \n");
printf("3. Print a specific column or a number of columns in sequence \n");
printf("4. Get the elements of a specific row reversed \n");
printf("5. find the number of prime numbers in a specific row \n");
printf("6. Quit \n");
printf("Please select one to try ");
int answer;
scanf("%d\n", &answer);
int *an = &answer;
switch (*an) {
case 1:
printMat();
printMenu();
break;
case 2:
printCol();
printMenu();
break;
case 3:
printRow();
printMenu();
break;
case 4:
reverseRow();
break;
case 5:
/* code */
break;
case 6:
printf("Bye!\n");
break;
default:
printf("please select carefully! \n");
break;
}
}
int main() {
char buf;
printMat();
printMenu();
return 0;
}
Can anyone please help me understand why this is happening? They are always printing wrong column or row.
Tricky little bug, the problem wasn't with your print functions, but with the way you are reading input. You use things like scanf("%d\n", &answer); which wants to read a %d and a \n. When you enter a number you have to follow it by an enter, which might lead you to believe you need to read the \n, but it doesn't go into the input stream. This is also why in your program you would need to enter the selection twice. The second time it leaves a number in the input stream which is wrongly read to choose the row/column. I have corrected these mistakes in the below code.
#include <stdio.h>
#include <stdlib.h>
void printRow1(int *p1, int rowSize) {
for (int i = 0; i < rowSize; i++) {
printf("%d\t", *p1);
p1 += 1;
}
}
void printCol1(int *p, int colSize) {
for (int i = 0; i < colSize; i++) {
printf("%d\n", *p);
p += 4;
}
}
void reverseRow1(int *p2) {
for (int i = 4; i > 0; i--) {
printf("%d\t", *p2);
p2-=1;
}
}
int arr[3][4] = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
void printMat() {
int col = 3;
int row = 4;
for (int i = 0; i < col; i ++) {
printf("\n");
for (int j = 0; j < row; j++) {
printf("%d\t", arr[i][j]);
}
}
}
void printCol() {
printf("Which column would you like to print? \t");
int choiceCol;
scanf("%d", &choiceCol);
if (choiceCol >= 1 && choiceCol <= 4) {
printCol1(&arr[0][choiceCol-1], 3);
} else {
printf("An Error occured\n");
}
}
void printRow() {
printf("Which row would you like to print? \t");
int choiceRow;
scanf("%d", &choiceRow);
if (choiceRow >= 1 && choiceRow <= 3){
printRow1(&arr[choiceRow-1][0], 4);
} else {
printf("An Error occured\n");
}
}
void reverseRow() {
printf("which row to reverse?: \t");
int reversedR = scanf("%d", &reversedR);
printf("%d\n", reversedR);
reverseRow1(&arr[0][reversedR]);
}
void printMenu() {
printf("\n");
printf("You can choose one of these services: \n");
printf("1. Print matrix tabular form. \n");
printf("2. Print a specific row or a number of rows in sequence \n");
printf("3. Print a specific column or a number of columns in sequence \n");
printf("4. Get the elements of a specific row reversed \n");
printf("5. find the number of prime numbers in a specific row \n");
printf("6. Quit \n");
printf("Please select one to try ");
int answer;
scanf("%d", &answer);
switch (answer) {
case 1:
printMat();
printMenu();
break;
case 2:
printCol();
printMenu();
break;
case 3:
printRow();
printMenu();
break;
case 4:
reverseRow();
break;
case 5:
/* code */
break;
case 6:
printf("Bye!\n");
break;
default:
printf("please select carefully! \n");
break;
}
}
int main() {
printMat();
printMenu();
return 0;
}
A few other things I noticed, your menu options for row and column are flipped, and your code assumes the size of the array in several spots (this is very bad practice). If the code should work with different sized arrays then you should be passing the size around, if not then you should use macros to define the size. There may be other issues I didn't notice, but the issue mentioned in the question is now fixed.
I have a string named pos, and I want to insert integer in middle of string. I am new to C.
My code is
char *pos;
int i = 1;
pos = "(%d)",i;
printf("%s",pos);
I get this output (%d)
Whereas I want (1)
Correct me if my approach is wrong.
I know I can directly print it but I want to use the variable in program.
Edit: I have switched from C++, I haven't read much about pointers till yet
The function definition is defined in int program_list(char *programs[],int program_len,int progress[],int progress_len)
by the way my entire program is
#include <stdlib.h> // exit()
#include <stdio.h>
#include <string.h>
#include <conio.h> // clrscr(), getch()
#define width 68
#define array_size(arr) ((sizeof(arr))/(sizeof(*arr)))
void ln();
int program_list(char *programs[],int program_len,int progress[],int progress_len);
void get_elements(int arr[],int size);
void display_elements(int arr[],int size);
int insert_element(int arr[],int *size,int pos,int item);
int delete_element(int arr[],int *size,int pos);
int linear_search(int arr[],int beg,int last,int item);
int binary_search(int arr[],int beg,int last,int item);
void swap(int *a,int *b);
int bubble_sort(int arr[],int size);
int main() {
int item,opt,size,pos,arr[20];
int progress[] = {6,7,11,14,15,16};
char *programs[] = {"GCD of 2 nos. using recursion",
"Fibonacci series using recursion",
"Length of string, concatenate 2 strings using pointer",
"Copy a string, extract substring from string using pointers",
"Tower of Hanoi with 3 discs using recursion",
"Insert integer in array",
"Delete integer from array",
"Create linked list and display it",
"Sort N nos. using insertion sort",
"Sort N nos. using selection sort",
"Sort N nos. using bubble sort",
"Sort N nos. using merge sort",
"Sort N nos. using quick sort",
"Binary Search using recursion",
"Linear Search using recursion",
"EXIT"
};
do{
opt = program_list(programs,array_size(programs),progress,array_size(progress));
switch(opt){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
printf("\nEnter size of array : ");
scanf("%d",&size);
printf("Enter elements of array -:");
get_elements(arr,size);
printf("Elements of array -:");
display_elements(arr,size);
printf("At which index you want to insert? : ");
scanf("%d",&pos);
printf("Enter value which you want to insert : ");
scanf("%d",&item);
*arr = insert_element(arr,&size,pos,item);
printf("Elements of array after insertion -:");
display_elements(arr,size);
break;
case 7:
printf("\nEnter size of array : ");
scanf("%d",&size);
printf("Enter elements of array -:");
get_elements(arr,size);
printf("Elements of array -:");
display_elements(arr,size);
printf("Enter index which you want to delete : ");
scanf("%d",&pos);
*arr = delete_element(arr,&size,pos);
printf("Elements of array after deletion -:");
display_elements(arr,size);
break;
case 8:
break;
case 9:
break;
case 10:
break;
case 11:
printf("\nEnter size of array : ");
scanf("%d",&size);
printf("Enter elements of array -:");
get_elements(arr,size);
printf("Elements of array -:");
display_elements(arr,size);
*arr = bubble_sort(arr,size);
printf("Sorted array using bubble sort -:");
display_elements(arr,size);
break;
case 12:
break;
case 13:
break;
case 14:
printf("\nEnter size of array : ");
scanf("%d",&size);
printf("Enter elements of array -:");
get_elements(arr,size);
printf("Elements of array -:");
display_elements(arr,size);
printf("Enter value which you want to search : ");
scanf("%d",&item);
pos = binary_search(arr,0,size-1,item);
if(pos==-1){
printf("%d not found using binary search\n",item);
}
else{
printf("arr[%d] = %d (found using binary search)\n",pos,item);
}
break;
case 15:
printf("\nEnter size of array : ");
scanf("%d",&size);
printf("Enter elements of array -:");
get_elements(arr,size);
printf("Elements of array -:");
display_elements(arr,size);
printf("Enter value which you want to search : ");
scanf("%d",&item);
pos = linear_search(arr,0,size-1,item);
if(pos==-1){
printf("%d not found using linear search\n",item);
}
else{
printf("arr[%d] = %d (found using linear search)\n",pos,item);
}
break;
case 16:
exit(EXIT_SUCCESS);
break;
default:
printf("Enter valid choice!\n");
opt=0;
}
printf("Program finished! Press enter to restart");
getch(); // use getch() two times for linux based OS (modified by me)
getch();
}while( opt>=0 && opt<=array_size(programs) );
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ln(){
printf("\n");
} // function to leave a line
int program_list(char *programs[],int program_len,int progress[],int progress_len){
clrscr();
int opt,i=0,j,k;
char *text,*status,*pos;
while(i>=0 && i<=2){
switch(i){
case 1:
for(j=0;j<program_len;j++){
for(k=0;k<=width;k++){
if(k==0 || k==width) printf("|");
else{
if(linear_search(progress,0,progress_len,j+1)==-1) status=" ";
else status="->";
pos = "(%d) ",(j+1);
text = programs[j];
printf("%s%s%s",status,pos,text);
k=strlen(status)+strlen(pos)+strlen(text);
while(k<width-1){
printf(" ");
k++;
}
}
}
ln();
}
break;
default:
for(j=0;j<=width;j++){
if(j==0 || j==width) printf("+");
else printf("-");
}
ln();
}
i++;
}
printf("\nYour option : ");
scanf("%d",&opt);
return opt;
} // function to display list of programs in beautiful manner
void get_elements(int arr[],int size){
int i;
ln();
for(i=0;i<size;i++){
printf("arr[%d] -> ",i);
scanf("%d",&arr[i]);
}
ln();
} // function to get elements in array
void display_elements(int arr[],int size){
int i;
ln();
for(i=0;i<size;i++){
printf("arr[%d] = %d\n",i,arr[i]);
}
ln();
} // function to display elements of array
int insert_element(int arr[],int *size,int pos,int item){
if (pos>*size){
printf("OVERFLOW\n");
}
else{
int i;
for(i=*size;i>pos;i--){
arr[i]=arr[i-1];
}
arr[pos] = item;
*size = *size+1;
}
return *arr;
} // function to insert element in array
int delete_element(int arr[],int *size,int pos){
if (pos>*size){
printf("OVERFLOW\n");
}
else{
*size = *size-1;
int i;
for(i=pos;i<*size;i++){
arr[i]=arr[i+1];
}
}
return *arr;
} // function to delete element from array
int linear_search(int arr[],int beg,int last,int item){
if (beg<=last){
if(arr[beg]==item){
return beg;
}
return linear_search(arr,beg+1,last,item);
}
return -1;
} // function to search elements using linear search
int binary_search(int arr[],int beg,int last,int item){
if (beg<=last){
int mid;
mid = (beg+last)/2;
if(arr[mid]==item){
return mid;
}
if(arr[mid]>item){
return binary_search(arr,beg,mid-1,item);
}
return binary_search(arr,mid+1,last,item);
}
return -1;
} // function to search elements using binary search
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
} // function to swap numbers
int bubble_sort(int arr[],int size){
int i=0,j;
while(i<size-1){
j=0;
while(j<size-1-i){
if(arr[j]>arr[j+1]){
swap(&arr[j],&arr[j+1]);
}
j++;
}
i++;
}
return *arr;
} // function to sort array using bubble sorting
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
My output
You don't need the pos variable. Just put what you want in the printf() format string.
To get the length that was printed, use the %n format specifier rather than adding strlen(). See What is the use of the %n format specifier in C?
for(j=0;j<program_len;j++){
for(k=0;k<=width;k++){
if(k==0 || k==width) printf("|");
else{
if(linear_search(progress,0,progress_len,j+1)==-1) status=" ";
else status="->";
text = programs[j];
printf("%s(%d)%s%n",status,j+1,text, &k);
while(k<width-1){
printf(" ");
k++;
}
}
}
ln();
}
But if you really want another variable, declare it as an array, not a pointer. Then use sprintf() to format it.
for(j=0;j<program_len;j++){
for(k=0;k<=width;k++){
if(k==0 || k==width) printf("|");
else{
if(linear_search(progress,0,progress_len,j+1)==-1) status=" ";
else status="->";
text = programs[j];
char pos[20];
sprintf(pos, "(%d)", i+1);
printf("%s%s%s%n",status,pos,text, &k);
while(k<width-1){
printf(" ");
k++;
}
}
}
ln();
}
Like i want to put the "return 0" at the right place, everything in the code is working normal.
complie the code and they keep saying about "while before return", i tried to put outside of the code and inside
#include <stdio.h>
#include <stdlib.h>
#define MAXN 100
int menu(){
printf("Menu:\n");
printf("1- Add a value\n");
printf("2- Search a value\n");
printf("3- Print out the array\n");
printf("4- Print out values in a range\n");
printf("5- Print out the array in ascending order\n");
printf("6- Quit?\n");
printf("Enter your operation: ");
int choice;
scanf("%d", &choice);
return choice;
}
int isFul (int*a, int n){
return n==MAXN;
}
int isEmpty (int*a, int n){
return n==0;
}
void add(int value, int*a, int*pn){
a[*pn] = value;
(*pn)++;
}
int search(int x, int *a, int n){
int i;
for (i=0; i<n; i++) if (a[i]==x) return i;
return -1;
}
void printvalueinrange (int*a, int n){
int i, min, max;
printf("\nEnter min value: ");scanf("%d", &min);
printf("\nEnter max value: ");scanf("%d", &max);
for(i=0; i<sizeof(a); i++)
if(a[i]>=min&&a[i]<=max) printf("%d", a[i]);
}
void printarray(int*a, int n){
int i;
for (i=0;i<n;i++) printf("%d", a[i]);
}
void printAsc(int*a, int n){
int** adds =(int**)calloc(n, sizeof(int*));
int i,j;
for(i=0; i<n; i++) adds[i]= &a[i];
int* t;
for (i=0;i<n-1; i++)
for(j=n-1; j>i; j--)
if (*adds[j]< *adds[j-i]){
t=adds[j];
adds[j]=adds[j-1];
adds[j-1]=t;
}
for (i=0;i<n; i++) printf("%d ", *adds[i]);
free(adds);
}
int main(){
int a[MAXN];
int n=0;
int value;
int choice;
do
{ choice= menu();
switch(choice){
case 1:{
if (isFull(a,n)) printf("\n Sorry! The array is full.\n");
else
{ printf ("Input an added value:");
scanf("%d", &value);
add(value, a, &n);
printf("Added!\n");
}
break;
}
case 2:{
if (isEmpty(a,n)) printf("\n Sorry! The array is empty.\n");
else
{ printf ("Input the searched value:");
scanf("%d", &value);
int pos = search(value, a, n);
if (pos<0) printf("Not found!\n");
else printf("Postion is found: %d\n", pos);
} break;
}
case 3:{
if (isEmpty(a,n)) printf("\n Sorry! The array is empty.\n");
else
{
printarray(a,n);
} break;
}
case 4:{
if (isEmpty(a,n)) printf("\n Sorry! The array is empty.\n");
else
{
printvalueinrange(a,n);
} break;
}
case 5:{
if (isEmpty(a,n)) printf("\n Sorry! The array is empty.\n");
else
{
printAsc(a,n);
} break;
}
default: printf ("Goodbye!");
break;
}
while (choice>0 && choice<7);
getchar();
}
return 0;
}
I just adding some word to fit with the requirement :"D
And if u find out any kind of error or mistake that in my code, just points out for me to improve them xd
In this part of main
}
while (choice>0 && choice<7);
getchar();
}
return 0;
}
the while construction occupies a wrong place.
There should be
}
} while (choice>0 && choice<7);
getchar();
return 0;
}
Also in this statement
if (isFull(a,n)) printf("\n Sorry! The array is full.\n");
^^^^^^
there is a typo. There should be
if (isFul(a,n)) printf("\n Sorry! The array is full.\n");
/int arr[n]; int n;/
void Linear_Search() {
int i, q, flag = 0, num, n;
int arr[n];
printf("Enter the number of array\n");
scanf("%d", n);
printf("Enter the numbers from which searched\n");
for (i = 0; i <= n; i++); {
scanf("%d", & arr[i]);
}
printf("enter the number to be searched\n");
scanf("%d", & q);
for (i = 0; i <= n; i++) {
if (q == arr[i]); {
num = q;
flag = 1;
}
}
if (flag == 1) printf("found! number is %d", num);
else printf("number not present in group\n");
getch();
}
void main() {
printf("ALL SEARCHING TECHNIQUE\n");
printf("Choices\n");
printf("1.Linear Search\n2.Binary Search\n3.Interpolation Search\n4.Jump Search\n");
void Linear_Search();
int select, l = 1;
scanf("%d", & select);
switch (select) {
case 1:
printf("This is Linear Search\n");
void Linear_Search();
break;
}
/case 2: printf("This is Binary Search\n"); void Binary_Search(); break; case 3: printf("This is Interpolation Search\n"); void Interpolation_Search(); break; case 4: printf("This is Jump Search\n"); void Jump_Search(); break; } printf("To continue PRESS 1 or PRESS ANY KEY"); scanf("%d",&l);/
getch();
}
You are including the return type of the function at the places where you are trying to call them. This turns them from a function call to a function prototype declaration. Remove the return type (void in these cases) at the places where the function shall be called.
When i run the code,in main function something going wrong.After first round of loop in main,program print "Wrong Choice" altough choice is legal.
#include <stdio.h>
#include <stdlib.h>
int factorial(int n);
void prime_numbers(){
int upper_bound;
printf("Define upper bound:");
scanf("%d",&upper_bound);
printf("Prime Numbers: ");
int i,j;
int variable;
for (i=2;i<=upper_bound;i++)
{
variable = 1;
for (j = 2; j <i; j++)
{ if (i % j == 0)
{
variable = 0;
break;
}
}
if (variable == 1)
printf ("%d ", i );
}
printf("\n");
}
void leibniz_series(){
printf("Define k value:");
int k;
scanf("%d",&k);
double sum=0;
int i;
for (i=1; i<k; i++)
{
if ((i%2)==1)
sum=sum+1.0/((2.0 * (double)i) - 1.0);
else
sum = sum - 1.0/((2.0 * (double)i) - 1.0);
}
printf("Result:%f\n",4*sum);
}
void combination(){
int comb;
printf("Define n and r:");
int n,r;
scanf("%d %d",&n,&r);
comb=factorial(n)/(factorial(r)*factorial(n-r));
printf("Result:%d ",comb);
printf("\n");
}
int factorial(int n){
int f=1;
int i;
for(i=1;i<=n;i++)
f=f*i;
return f;
}
int main()
{
printf("Press P or p for Prime Numbers\n");
printf("Press L or l for Leibniz Series\n");
printf("Press C or c for Combinations\n");
printf("Press E or e for Exit\n");
char choice;
for(;;){
printf("Enter your choice:");
scanf("%c",&choice);
if(choice=='E' || choice=='e')
exit(0);
switch(choice){
case 'p' : prime_numbers();
break;
case 'P' : prime_numbers();
break;
case 'l' : leibniz_series();
break;
case 'L' : leibniz_series();
break;
case 'c' : combination();
break;
case 'C' : combination();
break;
default : printf("Wrong choice\n");
}
}
return 0;
}
It is probably something to do with the return key you pressed to enter the input lying around in your input buffer.
To simply clear that character from the buffer you can read it and ignore it by adding scanf("%*c"); immediately after you scan for a character from the STDIN.
So your new code would look something like this:
printf("Enter your choice:");
scanf("%c",&choice);
scanf("%*c");