Basic C help using arrays and for loops - c

#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;
}

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();
}

C for condition tricks

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("_");}

C Coding: Create Char Array, Print, Reorganize, and Print Again

I would like to create a char array, print it, reorganize it, and then reprint it in C. Here's what I have so far:
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
int i = 0;
int j = 0;
char k[4][2];
char thing[1][1];
strcpy(k[0] , "A");
strcpy(k[1] , "B");
strcpy(k[2] , "C");
strcpy(k[3] , "D");
printf("\nThe original order is: \n");
for (int i = 0; i < 4; i++) { // fill
printf("%s,", k[i]);
}
printf("\nThe reordering is: \n");
for (int i = 0; i < 4; i++) { // reorder
strcpy(thing[0], k[i]);
j = (int)(i + rand() / (RAND_MAX / (5 - i)) );
strcpy(k[i], k[j]);
strcpy(k[j], thing[0]);
printf("%s,", k[i]); // print
}
return(0);
}
Here's my Terminal Output. There are no warnings, just the abort.
mac% clang thing.c -o thing
mac% ./thing
The original order is:
A,B,C,D,
The reordering is:
zsh: abort ./thing
I figured it out! Here's the solution I came up with:
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
int i = 0;
int j = 0;
char k[4] = "ABCD";
char thing[1] = "O";
printf("\nThe original order is: \n");
for (int i = 0; i < 4; i++) { // fill
printf("%c,", k[i]);
}
printf("\nThe reordering is: \n");
for (int i = 0; i < 4; i++) { // reorder
thing[0]= k[i];
j = (int)(i + rand() / (RAND_MAX / (4 - i)) );
k[i]= k[j];
k[j]= thing[0];
printf("%c,", k[i]); // print
}
return(0);
}
And the output is
The original order is:
A,B,C,D,
The reordering is:
A,B,D,C,%

Recursive function for finding same numbers on same positions between two arrays

Here is an example of what the result should be :
1234 and 1344 Have two numbers on same positions.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Proverka(int *num1[], int *num2[], int len, int pom)
{
if (len < 1 && pom < 1)
return 0;
if (*num1 == *num2)
return 1 + Proverka(num1++, num2++, len-1, pom-1);
else {
return Proverka(num1++, num2++, len-1, pom-1);
}
}
int main (void)
{
int *num1[5], *num2[5], pom, len, i, sin, j;
pom = sizeof(num1) / sizeof(num1[0]);
len = sizeof(num2) / sizeof(num2[0]);
for (i = 0; i < pom; i++) {
printf("Enter elements for first array :");
scanf("%d", num1[i]);
}
for (j = 0; j < len; j++){
printf("Enter elements for second array : ");
scanf("%d", num2[j]);
}
sin = Proverka(num1, num2, pom, len);
{
printf("They have %d numbers on same positions", sin);
}
return 0;
}
You have quite a lot of bugs in the code, here's a working version of it.
Read comments to understand what I changed.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Proverka(int *num1, int *num2, int len1, int len2)
{
if (len1 < 1 && len2 < 1) return 0;
// note the pre-increment. Your post-increment wouldn't have worked. Or just add 1.
return (*num1 == *num2) + Proverka(++num1, ++num2, len1 - 1, len2 - 1);
// this works, since "boolean" is really just 0 or 1
}
int main (void)
{
// I make array of ints, not of pointers to ints.
int num1[5], num2[5], len1, len2, i, same;
len1 = sizeof(num1) / sizeof(num1[0]);
len2 = sizeof(num2) / sizeof(num2[0]);
for (i = 0; i < len1; i++) {
printf("First array element %d:", i+1);
scanf("%d", &num1[i]); // pointer at the element
}
for (i = 0; i < len2; i++){
printf("Second array element %d:", i+1);
scanf("%d", &num2[i]);
}
// get pointers at the first array elements
same = Proverka(&num1[0], &num2[0], len1, len2);
printf("They have %d numbers on same positions\n", same); // newline - good practice
return 0;
}
Here's a bit more "optimized" and cleaned up version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ITEMS 5
int Proverka(const int *aa, const int *bb, const int len)
{
if (len == 0) return 0;
return (*aa == *bb) + Proverka(1 + aa, 1 + bb, len - 1);
}
int main (void)
{
int aa[ITEMS], bb[ITEMS], i, same;
for (i = 0; i < ITEMS; i++) {
printf("First array element %d:", i+1);
scanf("%d", &aa[i]);
}
for (i = 0; i < ITEMS; i++) {
printf("Second array element %d:", i+1);
scanf("%d", &bb[i]);
}
same = Proverka(&aa[0], &bb[0], ITEMS);
printf("They have %d numbers on same positions\n", same);
return 0;
}
Using recursion for this is not a very good choice, a loop would be easier and safer. But this works too - for not-too-large arrays.
int *num1[5],*num2[5] ... doesnt give you an array of integer pointers with memory allocated. Fix that. Allocate memory using malloc.
Or just say int num1[5],num2[5] and scanf("%d",&num1[i]);

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

Resources