Note: This code should be appropriately commented.
#include <stdlib.h> #include <stdio.h> int main (int argc, char * argv[]) { //get number int n; scanf("%d",&n); int i = 1;//set counter to first odd number //loop until i is greater than n while (i <= n) { printf("%d\n",i); i += 2;//i = i + 2 to get next odd number } return EXIT_SUCCESS; }
#include <stdlib.h> #include <stdio.h> int main (int argc, char * argv[]) { //get number int num; scanf ("%d",&num); //set counters --> both are used decreasing! int line = num; int star; while (line > 0) { star = line;//number of stars per line is current line counter //print all the stars while (star > 0) { printf("*"); star--; } printf("\n"); line--; } return EXIT_SUCCESS; }
#define TRUE 1 #define FALSE 0 int power_of_two(int k) { //continually divide k by two until you reach an odd number while (k % 2 == 0) {//while k is still divisbile by two k /= 2; //k = k / 2 } int isPow = FALSE;//assume not true //mathematically, if k ends up as 1, k is a power of 2 //as it is always reached when you continually divide //powers of two by two. if (k == 1) { isPow = TRUE; } return isPow; }
void average(int n, int a[]) { float sum = 0;//use a flaot so that later when you divide int i = 0; //you don't just get the integer part of the answer //adds the value of every element of the array to sum while (i < n) { sum += a[i];//sum = sum + a[i] i++; } float avg = n / sum;//get the average printf("avg = %.2f\n", avg); }
#include <stdlib.h> #include <stdio.h> #define FALSE 0 #define TRUE 1 #define NUM_DIGITS 10 int isDigit(char c); int digitVal(char c); int main (int argc, char * argv[]) { int count[NUM_DIGITS] = {}; //set up empty array to count each digit int val; char c = getchar();//getchar() loop to read each character while (c != EOF) { //if it's a digit increment its count by one if (isDigit(c)) { val = digitVal(c);//convert char to int value count[val]++; } c = getchar(); } //loop through each digit and print the count int i = 0; while (i < NUM_DIGITS) { printf("%d %d\n", i, count[i]); i++; } return EXIT_SUCCESS; } int isDigit(char c) { //this function takes in a character //and returns FALSE or TRUE //depending on whether the char is a digit int flag = FALSE;//assume not a digit if (c >= '0' && c <= '9') {//if it is in the digit range of characters flag = TRUE; } return flag; } int digitVal(char c) { //this function takes in a character and //returns the integer value represented //note: character passed in must be a digit //subtract ascii value of '0' from c's ascii value to get the value of the number int val = c - '0'; return val; }