C for condition tricks - c

I found a challenge on the internet and I'm really stuck.
The goal is to print 20 times _ by adding/changing only 1 character (only one operation performed in total):
#include <stdio.h>
int main(void)
{
int i;
int n=20;
for(i=0;i<n;i--)
{
printf("_");
}
return 0;
}
I have already found 1 solution but I can't find the last one? Is there some tricks I need to know about for loops ?

Replace i by n
#include <stdio.h>
int main()
{
int i, n = 20;
for (i = 0; i < n; n--)
printf("*");
getchar();
return 0;
}
Put - before i
#include <stdio.h>
int main()
{
int i, n = 20;
for (i = 0; -i < n; i--)
printf("*");
getchar();
return 0;
}
Replace < by +
#include <stdio.h>
int main()
{
int i, n = 20;
for (i = 0; i + n; i--)
printf("*");
getchar();
return 0;
}
Source: https://www.geeksforgeeks.org/changeadd-only-one-character-and-print-exactly-20-times/

to correct the posted code to only output 20 times, you could use:
#include <stdio.h>
int main(void)
{
int i;
int n=-20; // note the minus 20
for(i=0;i<n;i--)
{
printf("_");
}
return 0;
}

If it is allowed you could write:
n=10; for(i=0;i<n;i++){printf("__");}
or
n=10; for(i=0;i<n;i++){printf("_");printf("_");}

Related

Printing pascal's triangle in C

I have to print the pascal's triangle given a certain number of levels desired. The max levels that will be asked for is 28. I am able to print the some of the rows correctly but then it starts printing negative numbers in the rest of my rows. I can't figure out why, help would be much appreciated!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printTriangle() {
int numLevels;
printf("Please enter how many levels of Pascal's Triangle you would like to see: ");
scanf("%d", &numLevels);
char pascalTriangle[28][28];
for (int k = 1; k <= numLevels; ++k) {
for (int i = 0; i < k; ++i) {
int val = (i == 0) || (i == k - 1) ? 1 : (pascalTriangle[k-1][i-1] + pascalTriangle[k-1][i]);
pascalTriangle[k][i] = val;
printf(" %d", val);
}
printf("\n");
}
}
int main() {
printTriangle();
}
Change char pascalTriangle[28][28]; to int pascalTriangle[28][28];. You're going over the max char value so it goes to negative.
There is no "array" type, only a collection of pointers. You can also change char to short, long, etc.
Also, change k <= numLevels to k < numLevels. This prevents the segmentation fault. To fix the logic, you have to change for(int i = 0; to for(int i = -1;
The fixed code is:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printTriangle() {
int numLevels;
printf("Please enter how many levels of Pascal's Triangle you would like to see: ");
scanf("%d", &numLevels);
long long pascalTriangle[28][28];
for (int k = 0; k < numLevels; ++k) {
for (int i = -1; i < k; ++i) {
long long val = (i == 0) || (i == k - 1) ? 1 : (pascalTriangle[k-1][i-1] + pascalTriangle[k-1][i]);
pascalTriangle[k][i] = val;
printf(" %lld", val);
}
printf("\n");
}
}
int main() {
printTriangle();
}

Find how many positive numbers there are in my array

How to find how many positive numbers there are in my code? I am getting the wrong output, please explain in detail where my mistake here is. I wish to have the exact output as desired. If I entered 6 as n then I will insert six numbers and the output will show me how many positive numbers I have inserted.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main() {
int n;
scanf("%d",&n);
int arr[n];
int i;
int p = 0;
int arr_i;
for (arr_i = 0; arr_i < n; arr_i++) {
scanf("%d",&arr[arr_i]);
}
for (i = 0; i < n; i++) {
int arr_index=i;
if (arr[arr_index] > 0) {
p++;
}
printf("%d",p);
}
return 0;
}
Try this:
Just Print p outside the for loop.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main() {
int n;
scanf("%d",&n);
int arr[n];
int i;
int p = 0;
int arr_i;
for (arr_i = 0; arr_i < n; arr_i++)
{
scanf("%d",&arr[arr_i]);
}
for (i = 0; i < n; i++)
{
int arr_index=i;
if (arr[arr_index] > 0)
{
p++;
}
}
printf("%d",p);
return 0;
}
YOu need t allocate dynamic memory using malloc - hope this helps
#include <stdio.h>
#include <stdlib.h>
int main() {
char c;
int n;
scanf("%d", &n);
int * arr;
int i;
int p = 0;
arr = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
if (arr[i] > 0)
{
p++;
}
}
printf(" %d", p);
return 0;
}

Basic C help using arrays and for loops

#include "stdafx.h"
#include "stdio.h"
#include <string.h>
void main() {
int Results[8];
int i = 0;
int max = 0;
int maxindex;
printf("Enter the results of your 7 leavin cert subjects: ");
do {
printf("\nSubject %d: ", i + 1);
scanf_s("%d", Results);
i++;
} while (i < 7);
for (i < 7; Results[i] > 0; i++)
if (Results[i] > max)
max = Results[i];
printf("The best grade is %d", max);
}
Hello, so basically I'm trying to print out the largest number(Best result) by using a for loop. However it keeps telling me the that the best result is 0.
Does anybody know what I'm doing wrong. Any help would be greatly appreciated.
There are 2 major problems in your code:
You read all numbers into Results[0] with the scanf_s("%d", Results);. You should instead write:
if (scanf_s("%d", &Results[i]) != 1) {
/* not a number, handle the error */
}
The second loop is incorrect: for (i < 7; Results[i] > 0; i++) has multiple issues. Write instead for (i = 0; i < 7; i++)
And smaller ones too:
#include "stdio.h" should be written #include <stdio.h>
#include "stdafx.h" is not used, and so can be removed - regardless, it should be written as #include <stdafx.h> if it were to be used.
The Results array has size 8, but you only use 7 slots.
main should have prototype int main(void) or int main(int argc, char *argv[]) or equivalent.
favor idiomatic for (i = 0; i < 7; i++) loops over error prone do / while loops.
use braces for a non trivial loop body.
Here is a simpler and better version:
#include <stdio.h>
#include <string.h>
int main(void) {
int Results[7];
int i, n, max;
printf("Enter the results of your 7 leavin cert subjects: ");
for (i = 0; i < 7; i++) {
printf("\nSubject %d: ", i + 1);
if (scanf_s("%d", &Results[i]) != 1) {
printf("invalid number\n");
exit(1);
}
}
for (n = i, max = 0, i = 0; i < n; i++) {
if (Results[i] > max)
max = Results[i];
}
printf("The best grade is %d\n", max);
return 0;
}

Counting number of searches

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)++;

Trying to return input from a function in C

#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.

Resources