Infinite output with scanf("%[^\n]"); - while-loop

Basically the code here takes some string and gives a string wihtout special character .
But when I give input, the Output gives the desired output. But it gives me infinite output.
What I want is user will give infinite input and will get desired output .
int main()
{
int g= 2; char C;
while (1) {
char s[257];
scanf("%[^\n]", s);
int i;
int j= strlen (s);
for (i=0; i< j; i++){
if( (s[i]>='a'&& s[i]<='z')|| (s[i]>='A' && s[i]<='Z') || (s[i]==' ') )
printf ("%c",s[i]);
}
}
return 0;
}

Related

Star Pattern Logic

I want make a star pattern just like this.
*
* * *
* * * * *
* * *
*
I am using this code.
for (int i=1; i<=3; i++) {
for (int j=1; j<=3-i; j++) {
printf(" ");
}
for (int k=1; k<=2*i-1; k++) {
printf("x");
}
printf("\n");
}
This will give
*
* * *
* * * * *
How I will iterate in decrement order.
when I am using
for (int i=3; i>=0; i--) {
for (int j=1; j<=3-i; j++) {
printf(" ");
}
for (int k=1; k<=2*i-1; k++) {
printf("x");
}
printf("\n");
}
xxxxx
xxx
x
How we merged it?
Another logic here
int x=11;
int y=x/2;
int z=1;
BOOL b1=true;
BOOL b2= true;
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
{
printf(" ");
}
for(int k=0;k<z;k++)
{
printf("*");
}
if(y==0) b1=false;
if(z==x) b2=false;
y=b1?y-1:y+1;
z=b2?z+2:z-2;
printf("\n");
}
Try with below logic,
for (int i=1; i<=3; i++) {
for (int j=1; j<=3-i; j++) {
printf(" ");
}
for (int k=1; k<=2*i-1; k++) {
printf("*");
}
printf("\n");
}
for (int i =2; i>=0; i--) {
for (int j=1; j<=3-i; j++) {
printf(" ");
}
for (int k=1; k<=2*i-1; k++) {
printf("*");
}
printf("\n");
}
Output Will look like :
*
***
*****
***
*
The given pattern is a combination of simple pyramid star pattern and inverted pyramid star pattern. It consist of N*2-1 rows (for this case N=3). Each row contain spaces and stars in printed in increasing and decreasing order.
Stars are printed in increasing order till Nth row. After Nth row stars are printed in decreasing order.
Spaces are printed in decreasing order till Nth row. After Nth row spaces are printed in increasing order. Point your mouse cursor over the pattern to count total spaces.
Step by step descriptive logic to print diamond star pattern.
Input number of rows to print from user (in real number of rows/2). Store it in a variable say rows.
Declare two variables to keep track of total columns to print each row, say stars=1 and spaces=N-1.
To iterate through rows, run an outer loop from 1 to rows*2-1. The loop structure should look like for(i=1; i<rows*2; i++).
To print spaces, run an inner loop from 1 to spaces. The loop structure should look like for(j=1; j<=spaces; j++). Inside this loop print single space.
To print stars, run another inner loop from 1 to stars*2-1. The loop structure should look like for(j=1; j<=stars; j++). Inside this loop print star.
After printing all columns of a row, move to next line i.e. print new line.
Check if(i < rows) then increment stars and decrement spaces. Otherwise increment spaces and decrement stars.
Try Below code:-
int i, j, rows;
int stars, spaces;
printf("Enter rows to print : ");
scanf("%d", &rows);
stars = 1;
spaces = rows - 1;
/* Iterate through rows */
for(i=1; i<rows*2; i++)
{
/* Print spaces */
for(j=1; j<=spaces; j++)
printf(" ");
/* Print stars */
for(j=1; j<stars*2; j++)
printf("*");
/* Move to next line */
printf("\n");
if(i<rows)
{
spaces--;
stars++;
}
else
{
spaces++;
stars--;
}
}

Confusion about my QuickSort algorithm & Mergesort algorithm

I am currently conducting empirical studies to evaluate the run-time complexities of the quicksort, and mergesort algorithms. To do this I run a random number generator that stores whatever amount of numbers I specify in a binary file. The ranges of those numbers are from 1-1,000,000.I then run tests of each algorithm starting from 100,000 numbers, incrementing by 50,000 each time, until 1,000,000 numbers are sorted on the last run. So 20 tests each. I have successfully completed each algorithm but my results are kind of puzzingly. This is a graph showing my results.
I understand that quicksort has a worst case of O(n2) time, but typically O(n·lg(n)) time. Mergesort has Θ(n·lg(n)) time.
Also I would like to note that when I started the timer I just used clock() from time.h, and calculated the time elapsed. I started my timer one line of code before I called my sorting function.
What I dont understand is how my graph shows mergesort is always double the time, and reaching triple the time to sort numbers compared to quicksort.
My only thought is that for my mergesort algorithm every time I divide my array in half I use malloc to create a new integer array for each half. Of course this means a large amount of calls are made to malloc considering the number sizes I am sorting.
int* mergeSort(int* nums, int size){
int* left;
int* right;
int middle = size/2;
if(size <= 1)
return nums;
split(nums, size, &left, &right, middle);
//I dont understand why the code below wouldnt work in place of the split()
//when i run it, in main, nothing gets printed out. I guess i lose my pointer to the beginning of my array.
//left = nums;
//right = nums+middle;
left = mergeSort(left, middle);
right = mergeSort(right, size - middle);
merge(nums,left,right,middle,size - middle);
free(left);
free(right);
return nums;
}
void split(int* nums, int size, int** left, int** right, int middle){
int *lft = (int*) malloc ((sizeof(int) * middle));
int *rght = (int*) malloc ((sizeof(int) * size - middle));
int mid = middle;
int upMid = size - middle;
int i;
for(i=0; i < mid; i++)
lft[i] = nums[i];
for(i=0; i < upMid; i++)
rght[i] = nums[i+middle];
*left = lft;
*right = rght;
}
void merge(int* num, int* left, int* right, int sizeLeft, int sizeRight){
int i,j,k,n;
i=j=k=0;
n=sizeLeft + sizeRight;
while(k < n){
if(i< sizeLeft){
if(j<sizeRight){
insert(num,left,right,&i,&j,&k);
}
else{
append(num, left, sizeLeft, &i, &k);
}
}
else{
append(num,right,sizeRight,&j,&k);
}
}
}
void insert(int* num, int* left, int* right, int* i, int* j, int* k){
/*int i,j,k,n;*/
if(left[*i]<right[*j]){
num[*k] = left[*i];
(*i)++;
}
else{
num[*k] = right[*j];
(*j)++;
}
(*k)++;
}
void append(int* num, int* half, int sizeHalf, int* i, int* k){
while(*i < sizeHalf){
num[*k]= half[*i];
(*i)++; (*k)++;
}
}
I would greatly appreciate any feedback on this question of mine, and any advice on maybe making my mergesort function more efficient. Thanks!!
I have implemented a merge sort algorithm, you can have a look. I malloc a bak array at the beginning of mergeSort and every merge use the it afterwards.
#include <string>
#include <stdlib.h>
void _mergeSort(int *array, int *bakArray, int len) ;
void mergeSort(int *array, int len)
{
int *bak = (int *)malloc(sizeof(int)*len) ;
_mergeSort(array, bak, len) ;
free(bak) ;
}
void _mergeSort(int *array, int *bakArray, int len)
{
if (len >= 2) {
int leftLen = len/2 ;
_mergeSort(array, bakArray, leftLen) ;
_mergeSort(array+leftLen, bakArray, len-leftLen) ;
int *pa = array ;
int *pb = array+leftLen ;
int aIndex = 0 ;
int bIndex = 0 ;
while (aIndex < leftLen && bIndex < len-leftLen) {
int a = pa[aIndex] ;
int b = pb[bIndex] ;
if (a < b) {
bakArray[aIndex+bIndex] = a ;
++aIndex ;
} else if (a == b) {
bakArray[aIndex+bIndex] = a ;
bakArray[aIndex+bIndex+1] = a ;
++aIndex ;
++bIndex ;
} else {
bakArray[aIndex+bIndex] = b ;
++bIndex ;
}
}
if (aIndex < leftLen) {
memcpy(bakArray+aIndex+bIndex, pa+aIndex, sizeof(int)*(leftLen-aIndex)) ;
} else if (bIndex < len-leftLen) {
memcpy(bakArray+aIndex+bIndex, pb+bIndex, sizeof(int)*(len-leftLen-bIndex)) ;
}
memcpy(array, bakArray, sizeof(int)*len) ;
}
}
static const int MaxArraySize = 100 ;
int main()
{
srand(time(NULL)) ;
int array[MaxArraySize] ;
for (int i = 0 ; i < MaxArraySize; ++i) {
array[i] = rand() % 10000 ;
}
mergeSort(array, MaxArraySize) ;
for (int i = 0 ; i < MaxArraySize; ++i) {
printf("%d ", array[i]) ;
}
printf("\n") ;
return 0 ;
}

Convert decimal to binary and return array

probably there is a smart way to do that , but anyway i get error on this :
-(int*)decimalBinary:(int)decimal
{
int i=0;
int *bin;
while (decimal!=0)
{
bin[i]=decimal%2;
decimal=decimal/2;
i++;
}
return bin;
}
on the modulo line . why ?
And whats the better way to get it to array ?
Declaring
int *bin;
sets aside space for a pointer but doesn't make it point to an object. It is crucial to initialize bin before using it.
To solve your problem you can declare an array bin[4] in caller function (int main) and then pass *bin to your calling function.
The following code is adapted from This answer on how to print an integer in binary format. Storing "binary digits" into an int array is added into the code below:
#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
const char *byte_to_binary(long x);
int main(void)
{
long lVal;
int i, len, array[18];
char buf[18];
{ /* binary string to int */
char *tmp;
char *b = "11010111001010110";
lVal=strtol(b, &tmp, 2); //convert string in "base 2" format to long int
printf("%d\n", lVal);
}
{
printf("%s", byte_to_binary(lVal));
/* byte to binary string */
sprintf(buf,"%s", byte_to_binary(lVal));
}
len = strlen(buf);
for(i=0;i<len;i++)
{ //store binary digits into an array.
array[i] = (buf[i]-'0');
}
getchar();
return 0;
}
const char *byte_to_binary(long x)
{
static char b[17]; //16 bits plus '\0'
b[0] = '\0';
char *p = b;
int z;
for (z = 65536; z > 0; z >>= 1) //2^16
{
*p++ = (x & z) ? '1' : '0';
}
return b;
}

reading from text file to two dimensional array

I try to read a text file and pass all integers to a 2 dimensional array one by one. But when i print what I tried to pass, I get weird outputs. What could be the problem?
For example if the text is:
0 1 1 1 0 1 1 0 1 1 1 1
I get this:
index=-2 index=1967626458 index=1967694074 index=207568 index=207320 index=2686776 index=1967693597 index=0 index=0 index=2686832 index=236 index=228 index=3
Here is the code:
#include<stdio.h>
int main()
{
FILE *input;
//read file!
if((input = fopen("abc.txt","r"))==NULL){
printf("Error in reading file !\n");
return 0;
}
int C = 4;
int R = 3;
int M[3][4];
int x=0;
int y=0;
int c;
//array of sorted list!
while(!feof(input)){
if(!feof(input)){
fscanf( input, "%d",&c);
M[x][y]=c;
y++;
if(y==C){
x++;
y=0;
}
printf("index=%d \n",M[x][y]);
}
}
system("pause");
}
The printout is wrong because you're changing the values of x and y between when you set the variable and when you try to print it. You need to move the printf() before the part where you increment x and y, but after you assign to the array.
As it stands right now, you assign to the array, then print the next, as yet unassigned, value. It's whatever value happens to be in that memory, such as -2 or 1967626458.
just increment you y variable after printing index.
#include<stdio.h>
int main()
{
FILE *input;
//read file!
if((input = fopen("abcd.txt","r"))==NULL)
{
printf("Error in reading file !\n");
return 0;
}
int C = 4;
int R = 3;
int M[3][4];
int x=0;
int y=0;
int c;
//array of sorted list!
while(!feof(input))
{
if(!feof(input))
{
fscanf( input, "%d",&c);
M[x][y]=c;
//y++ ; not increment here
if(y==C)
{
x++;
y=0;
}
printf("index=%d \n",M[x][y]);
y++;//increment here
}
}
system("pause");
}

variable argument function

while doing a program related to variable argument function i
got the header file stdarg.h and have done some simple problem using it
but now when i a changing the actual argument's type it is showing some weird behaviour
here is my code:
#include<stdio.h>
#include<stdarg.h>
void fun(int a,...)
{
va_list k;
va_start(k,a);
int i=0;
printf("%d ",a);
while((i=va_arg(k,int)!=0)
{
printf(" %d ",i);
}
va_end(k);
}
int main()
{
fun(1,2,3,4,5,6);
printf("\n");
fflush(); //and without flush it is also showing some extra garbage value
fun(2,4,5);
printf("\n");
fflush();
fun('c','f','g','l');
return 0;
}
If you use the integer value 0 to indicate end of the argument list, you should also pass a 0 to fun.
fun(1,2,3,4,5,6,0);
fun(2,4,5,0);
First, end your list with 0, because you check for !=0 to detect the end. And also:
while((i=va_arg(k,int))!=0)
instead of
while(i=va_arg(k,int)!=0)
!= has higher precedence than =
This will give you the expected output:
1 2 3 4 5 6
Here's the complete code:
#include<stdio.h>
#include<stdarg.h>
void fun(int a,...)
{
va_list k;
va_start(k,a);
int i=0;
printf("%d ",a);
while((i=va_arg(k,int))!=0)
{
printf(" %d ",i);
}
va_end(k);
}
int main()
{
fun(1,2,3,4,5,6,0);
printf("\n");
//fun(2,4,5,0);
printf("\n");
//fun('c','f','g','l','\0');
getch();
return 0;
}