I have the following pattern to print in the C programming language.
BBBB
BAAB
BAAB
BBBB
I have tried the following code, but it's not working.
My code :
#include <stdio.h>
int main() {
// Write C code here
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=4;j++)
{
if ((i==1&&j>=i)||(i==4&&j<=i)){
printf("%c",65+1);
}
else{
printf("%c",65);
}
}
printf("\n");
}
return 0;
}
However, the pattern I am getting is the following.
BBBB
AAAA
AAAA
BBBB
The problem with your code is your special case will only fire on the first and fourth row. We can see this a little better if we space things out.
if(
(i==1 && j>=i) || // `i==1` only on the first row
(i==4 && j<=i) // `i==4` only on the fourth row
) {
printf("%c",65+1);
}
Every other iteration will use your else block that just prints A.
else {
printf("%c",65);
}
Note: 'A' is much easier to read than 65, and 'B' much easier than 65+1.
There's plenty of ways to do this. Here's one elegant way with a single loop.
We can observe that we want to print BBBB at the start and every third row. If we start iterating at 0 we can do this when i is divisible by 3. 0/3 has a remainder of 0. 3/3 has a remainder of 0. We use the modulus operator % to get the remainder.
for(int i = 0; i < 4; i++) {
if( i % 3 == 0 ) {
puts("BBBB");
}
else {
puts("BAAB");
}
}
This will continue to repeat the pattern if you extend the loop. 6/3 has a remainder of 0. 9/3 has a remainder of 0. And so on.
(You could also start with i=1 and check i%3 == 1, but get used to starting counting at 0; it makes a lot of things easier.)
Related
Without using an array, I am trying to do this. what is wrong with my code?
n is the number of elements,a is the first element(assumed to be maximum initially), b stores new element every time and sec variable stores the second-largest element. Numbers are all positive. This is from an online contest.
#include<stdio.h>
int main() {
int i,a,b,max,n,sec;
scanf("%d",&n);
scanf("%d",&a);
max=a;
while(n-1!=0) {
scanf("%d",&b);
if(b>max) {
sec=max;
max=b;
}
else if(b<max && b>sec)
sec=b;
else{}
n--;
}
printf("%d",sec);
return 0;
}
getting wrong answers in some test cases( i don't know )
Consider sequence 2, 12, 10 (leaving out surrounding code):
int sec; // unitialised!!!
max = a; // 12
if(b > max) // b got 10, so false!
{
sec = max; // this code is not hit! (b remains uninitalised)
max = b;
}
else if(b < max && b > sec)
// ^ comparing against uninitialised
// -> UNDEFINED BEHAVIOUR
You need to initialise sec appropriately, e. g. with INT_MIN (defined in <limits.h>); this is the minimal allowed value, with 32-bit int that would be a value of -232 - 1, i. e. -2 147 483 648. Pretty unlikely anybody would enter that value, so you could use it as sentinel.
You even could initialise max with that value, then you woudn't need special handling for the first value:
int sec = INT_MIN, max = INT_MIN;
int n;
scanf("%d", &n); // you should check the return value, which is number of
// successfully scanned values, i. e. 1 in given case,
// to catch invalid user input!
// you might check value of n for being out of valid range, at very least < 0
while(n--) // you can do the decrement inside loop header already...
{
// keep scope of variables as local as possible:
int a;
// scanf and comparisons as you had already
// again don't forget to check scanf's return value
}
if(sec == INT_MAX)
{
// likely hasn't been modified -> error, no second largest element
}
else
{
// ...
}
Now what if you do expect user to give you the value of INT_MIN as input?
You could have a separate counter, initialised to 0, you increment in both of the two if branches inside the loop; if this counter is < 2 after the loop, you didn't get at least two distinct numbers...
Lets look at the input
2 4 3
Two is the number of inputs.
4 ends up in max.
3 ends up in b.
b is not greater than max, the if does not do anything.
b is less than max, but b is not necessarily greater than sec,
because sec at this point can be anything - whatever currently is inside that non-initialised variable. sec at this point is for example not guaranteed to be 0. So the else if does not trigger and we end up in else {}.
So we end up executing the printf() at the end of the program with a still uninitialised sec. And that is unlikely to satisfy the judge.
To solve the problem, you need to initialise sec. Initialising to 0 might work, but actually you need to use the lowest possible input value.
Since you chose int, instead of unsigned int, I assume that 0 is NOT the lowest possible value. But you would have to quote the assignment/challenge to allow determining the lowest possible value. So you need to find that out yourself in order to make a solution code.
Alernatively, you can analyse the first input values to initialise max and sec (need to watch them coming in until you get two distinct values; credits to Aconcagua).
Usually it is however easier to determine the lowest possible value from requirements or the lowest possible int value from your environment.
At some level of nitpicking, you need to know the lowest possible value anyway, in order to select the correct data type for your implementation. I.e. even with analysing the first two values, you might fail for selecting the most narrow data type.
In case you "successfully" (as judged by the challenge) use 0 to initialise sec, try the input 2 1 -1.
It should fail.
Then try to find in your challenge/assignment description a reason why using 0 is allowed. It should be there, otherwise find a different challenge site to improve your coding skills.
I liked how OP initialized max with the first input value.
This brought me to the idea that the same can be done for sec.
(The value of max is a nice indicator that sec could not be determined whatever max contains. In regular case, max and sec can never be equal.)
Hence, one possibility is to initialize max and sec with the first input
and use max != sec as indicator whether sec has been written afterwards at all.
Demo:
#include <stdio.h>
int main()
{
/* read number of inputs */
int n;
if (scanf("%d", &n) != 1 || n < 1) {
fprintf(stderr, "ERROR!\n");
return -1;
}
/* read 1st input */
int max;
if (scanf("%d", &max) != 1) {
fprintf(stderr, "ERROR!\n");
return -1;
}
--n;
int sec = max;
/* read other input */
while (n--) {
int a;
if (scanf("%d", &a) != 1) {
fprintf(stderr, "ERROR!\n");
return -1;
}
if (max < a) { sec = max; max = a; }
else if (sec == max || (sec < a && a < max)) sec = a;
}
/* evaluate result */
if (sec == max) {
puts("No second largest value occurred!\n");
} else printf("%d\n", sec);
/* done */
return 0;
}
Output:
$ gcc -std=c11 -O2 -Wall -pedantic main.c
$ echo -e "3 3 4 5" | ./a.out
4
$ echo -e "3 3 5 4" | ./a.out
4
$ echo -e "3 4 3 5" | ./a.out
4
$ echo -e "3 4 5 3" | ./a.out
4
$ echo -e "3 5 3 4" | ./a.out
4
$ echo -e "3 5 4 3" | ./a.out
4
$ # edge case:
$ echo -e "2 3 3" | ./a.out
No second largest value occurred!
Live Demo on coliru
I'm stuck on how to make a for loop that will alternate increments in a series. For example:
i x
2. 7
3. 12
4. 14
Where x is some combination of i. It first increments by 5, and then by 2 and then back to 5. I've tried using modulus to start an alternating series, but I can't seem to get the number to increase. Any ideas? Thank you.
Does it have to be a for loop? There's still the while loop.
int i = 0;
char switcher = 0; /*in this case it could also be a bool.*/
while(some statement)
{
switch(switcher)
{
case 0:
i+=5;
break;
case 1:
i+=2;
break;
}
switcher++;
if(switcher > 1)
switcher = 0;
//do something
}
You could easily add more different increments to that code.
It'd be best to use a while loop with a flag that keeps track of whether or not you need to increment by 2 or 5.
incrementFlag = true;
while(someCondition)
{
[code...]
if (incrementFlag)
i += 5;
else
i+=2
incrementFlag = !incrementFlag; // Alternate incrementing
}
I have a program that is stuck in a loop because of a possible bug in gcc. I have tested this on multiple versions of the compiler, and it seems to stick around. A mockup version of the bug is
#include <stdio.h>
#include <stdlib.h>
#define db printf("t=%d\n", t)
size_t t = 9;
int main(int argc, char** args) {
l: //label so we can repeat
t-(t^14) //works as expected if this line is changed to t-7, but t xor 14 = 7... this line is also executed ONCE
==2?db,t=1: //end of first conditional, next line starts the second
t==1?db,t=41: //buggy ONLY if t=40 or 41 on this and next line
t==41?db,t=0: //bug in this line (after this line executes, t = 1 no matter what)
t==0?exit(0): //terminates if not buggy
0;
goto l; //repeat
}
Please don't ask why I use this because it's for an obfuscated code contest, and I am using this particular method.
I would also like to know if this is even unexpected behavior, but I suspect it is.
Thanks
I re-wrote your expression with indenting and comments so that it can be traced.
t-(t^14)==2?
/*True */ db,t=1
/*else */ :
/*False*/ t==1?
/*True */ db,t=41
/*else */ :
/*False*/ t==41?
/*True */ db,t=0
/*else */ :
/*False*/ t==0?
/*True */ exit(0)
/*else */ :
/*False*/ 0;
Now a trace-through:
Pass #1
t = 9
t^14 = 7
t-7 == 9 - 7 == 2, therefore Condition 1 is True.
printf 9, t = 1, goto top.
Pass #2
t=1
t^14 = 15
t-15 = -14 != 2, therefore condition 1 is False.
Condition 2: t==1? TRUE,
printf 1, t = 41, goto top.
Pass #3
t = 41
t^14 = 39
41-39 = 2, therefore Condition 1 is true.
Printf 41, t = 1, goto top.
Because t is now back to value 1, we're back in the same scenario as Pass #2.
The cycle continually flips between Pass #2 and Pass #3. (t=1 and t=41).
An infinite loop is the proper outcome.
(You need to be a million times smarter before you honestly believe you found a compiler bug.)
The value of t printed alternates between 1 and 41, so when your program is unravelled it becomes quite obvious why exit(0) is never executed.
In the first iteration t==9 and t-(t^14)==2 so t becomes 1.
In the second iteration t==1 and t-(t^14)!=2 so t becomes 41.
In the third iteration t==41 and t-(t^14)==2 so t becomes 1.
Now repeat as second iteration.
#include <stdio.h>
#include <stdlib.h>
size_t t = 9;
int main(int argc, char** args) {
l: //label so we can repeat
if (t-(t^14) == 2) {
printf("t=%d\n", t);
t=1;
}
else if (t==1) {
printf("t=%d\n", t);
t=41;
}
else if (t==41) {
printf("t=%d\n", t);
t=0;
}
else if (t==0)
exit(0);
else
0;
goto l;
}
I want to ask something that I write in C.
I use the fopen() command to open and read a text file that contains only two lines. in
first line is an integer N number, and in the second line is the N integer numbers that the first line says.
Eg.
-------------- nubmers.txt --------------
8 <-- we want 8 numbers for the 2nd line
16 8 96 46 8 213 5 16 <-- and we have 8 numbers! :)
but I want to take restrictions when the file openend.
the number N should be between 1 ≤ Ν ≤ 1.000.000. If not then show an error message. If the file is ok then the programm continue to run with another code.
Here is what I done until now:
int num;
....
fscanf(fp,"%d",&num); // here goes the fscanf() command
if(num<1 || num>1000000) // set restrictions to integer
{
printf("The number must be 1<= N <= 1.000.000",strerror(errno)); // error with the integer number
getchar(); // wait the user press a key
return 0; // returning an int of 0, exit the program
}
else // if everything works.....
{
printf("work until now"); // Everything works until now! :)
getchar(); // wait the user press a key
return 0; // returning an int of 0, exit the program
}
But the problem is that the restriction checks only for the first line number , it's correct though, but don't read the numbers in the second line.
What I mean is that :
Lets say that I have the number 10 in the first line.
The code will analyze the number, will check for restrictions and will proceed to the 'else' part
else // if everything works.....
{
printf("work until now"); // Everything works until now! :)
getchar(); // wait the user press a key
return 0; // returning an int of 0, exit the program
}
..and it will said that everything is working.
But what if I have 20 numbers in the second line? -when I need only 10
Eg.
-------------- nubmers.txt --------------
10
16 8 96 46 8 213 5 16 8 9 21 5 69 64 58 10 1 7 3 6
So I hoped be as cleared as I could. My question is that I need a code in the program, besides the 1st restriction, that have also another one restriction under the first that will read the second line of the txt file with the numbers and check if there are as many numbers as the first line says!
How do I do that?
If you guys want any other declarations feel free to ask!
Hope I was clear with my problem :)
This will check the number of integers and report too many or not enough. The integers are not saved except for each one being read into the value. Do you want to store each integer?
fscanf(fp,"%d",&num); // here goes the fscanf() command
if(num<1 || num>1000000) // set restrictions to integer
{
printf("The number must be 1<= N <= 1.000.000",strerror(errno)); // error with the integer number
getchar(); // wait the user press a key
return 0; // returning an int of 0, exit the program
}
else // if everything works.....
{
int i = 0;
int value = 0;
while ( fscanf ( fp, "%d", &value) == 1) { // read one integer
i++; // this loop will continue until EOF or non-integer input
}
if ( i > num) {
printf ( "too many integers\n");
}
if ( i < num) {
printf ( "not enough integers\n");
}
getchar(); // wait the user press a key
return 0; // returning an int of 0, exit the program
}
use a loop that takes the first num and checks is is the number of integers in next line:
int z = num;
while(z--){
if (getchar() == EOF)
printf("err")
}
Do it like this:
fscanf(fp,"%d",&num);
// next lines of code (restrictions). Then place the below code before getchar in the else
int temp[num+1];// space to store num integers to temp and 1 space to check for extra number
for(i=0;i<num;i++)
{
if(fscanf(fp,"%d",&temp[i]) != 1)// fscanf will automatically read 2nd line and store them in temp array
//error ! Less numbers in file !
}
if(fscanf(fp,"%d",&temp[num]==1) //if still numbers can be scanned
//Extra numbers found in line 2
I'm actually working on a projecteuler.com problem (#12 specifically) and I thought I had this nailed when I wasn't getting any compile errors.
It runs and gives me several results that appear to be correct, but it's not finishing. I haven't been using C all that long so I am probably overlooking something I'm just not familiar with. Can someone tell me why it's stopping? It is giving me correct triangle numbers up to 12.5M. I would also gladly accept optimization suggestions in the comments.
The results are first, even after a few hours it didn't move on past the first number with 30 factors, which it found rather quickly.
It gives me this, from the code following it:
$ ./euler12
Current= 1
Factors= 1
Current= 3
Factors= 2
Current= 6
Factors= 4
Current= 28
Factors= 6
Current= 36
Factors= 9
Current= 120
Factors= 16
Current= 300
Factors= 18
Current= 528
Factors= 20
Current= 630
Factors= 24
Current= 1008
Factors= 30
where Current gives me the number it got the factors from and obviously then Factors is the number of factors. I doesn't give me any errors and the only warning from -Wall is that I don't actually use the "useless" variable for anything.
#include <stdio.h>
#include <time.h>
/*
Tristen
euler12.c
December 23, 2013
What's the value of the first triangle number to have over 500 divisors?
*/
int main(void)
{
/*---------Variables----------*/
time_t t1 = time(NULL);
int g,l,i,j,k,t,number,val,flag1,flag2;
int h=1,x=0,p=0,n=5000,m=500,m2=600,twitch=0
int answer=0,count=0,useless=0,linlen=0; /*modify n to change size*/
/*----------Arrays------------*/
int numtocheck[n];
int factors[m2];
/*find triangle numbers*/
for(i=0;i<=n+1;i++){
x+=i;
if(x!=0){
numtocheck[i]=x;
}
else{
useless=0;
}
}
/*begin checking for factors*/
while(twitch!=1){
count=0;
for(l=1;l<m2;l++){
factors[l]=0;
}
number=numtocheck[h];
for(j=0;j<=number;j++){
for(k=0;k<=number;k++){
val=j*k;
if(val==number){
flag1=0,flag2=0;
for(g=0;g<m2;g++){
if(factors[g]==j){
flag1=1;
}
else if(factors[g]==k){
flag2=1;
}
else{
useless=0;
}
}
if(flag1==0){
factors[p]=j;
p+=1;
}
else if(flag2==0){
factors[p]=k;
p+=1;
}
else{
useless=0;
}
}
}
}
for(l=0;l<m2;l++){
if(factors[l]!=0){
count+=1;
}
}
if(count>=m){
answer=number;
printf("Current= %d\n",number);
printf("Factors= %d\n",linlen);
twitch=1;
}
else{
if(count>linlen){
linlen=count;
printf("Current= %d\n",number);
printf("Factors= %d\n",linlen);
}
else{
useless=0;
}
}
h+=1;
}
time_t t2 = time(NULL);
t=t2-t1;
printf("Survey says %d\n", answer);
printf("time %d\n", t);
getchar();
return 0;
}
Here are some points to consider (point 5 is the big problem):
1) you forgot a semicolon so this code won't compile, based on this, I'm a little concerned you don't have everything in here verbatim to how you have it...
int h=1,x=0,p=0,n=5000,m=500,m2=600,twitch=0 //<- ; needed
2) as noted in the comments your first for loop overflows the array:
int n=5000;
int numtocheck[n];
/* so numtocheck[] goes from 0 to 4999 */
/*find triangle numbers*/
for(i=0;i<=n+1;i++){ // this loops from 0 to 5001
So this needs to be:
for(i=0;i<n;i++){
3) since you don't initialize the 0th element of numtocheck that means there is garbage data in numtocheck[0]. Same thing later for factors[0], the latter is OK since you over write it, but it's just something to be careful about.
4) You use useless to avoid empty else cases... this is, as you aptly named it, useless. If you don't have anything to do, don't do anything.
For example instead of writing this:
if(count>linlen){
linlen=count;
printf("Current= %d\n",number);
printf("Factors= %d\n",linlen);
}
else{
useless=0;
}
Just remove the else, a if can be paired with an else, it does not need to be.
5) OK, here's the big problem:
if(flag1==0){
factors[p]=j;
p+=1;
}
else if(flag2==0){
factors[p]=k;
p+=1;
}
factors[] is an array of 600 elements, and you access using p a value that's initially 0 but is incremented every time it enters either of these checks. By the time your number is around 2346 p more than overflows the 600 elements in factors[] and you start doing bad things. This causes undefined behavior. On one implantation in Linux this caused a very nice setfault. On a different one in Windows this simply over wrote the values in numtocheck basically making you go into an infinite loop.