C Programming Basics: Examples and Explanations

Classified in Computers

Written at on English with a size of 2.72 KB.

C Programming Basics

Printing a Message

int main() { print("Hello!!!"); }

Variables and Mathematical Calculations

int main() // Main function

{

int a = 25; // Initialize a variable to 25

int b = 17; // Initialize b variable to 17

int c = a + b; // Initialize c variable to a + b

print("c = %d ", c); // Display decimal value of c

}

Floating-Point Math

int main() // Main function

{

float r = 1.0; // Set radius to 1.0

float c = 2.0 * PI * r; // Calculate circumference

print("circumference = %f \n", c); // Display circumference

}

Arrays

int main() // Main function

{

int p[] = {1, 2, 3, 5, 7, 11}; // Initialize the array

print("p[0] = %d\n", p[0]); // Display what p[0] stores

print("p[3] = %d\n", p[3]); // Display what p[3] stores

p[3] = 101; // Assignment

}

If Statements

int main() // Main function

{

int a = -25; // Initialize a variable to 25

int b = -17; // Initialize b variable to 17

print("a = %d, b = %d\n", a, b); // Print all

if(a > b) // If a > b condition is true

{

print("a is larger \n"); // ...then print this message

}

}

While Statement

int main() // Main function

{

int n = 0; // Declare n, initialize to zero

while(n < 200) // Repeat while n is less than 200

{

print("n = %d\n", n); // Display name & value of n

n = n + 5; // Add 5 to n each time through

pause(500); // 0.5 s between repetitions

}

print("All done!"); // Display all done

}

For Statement

int main() // Main function

{

for(int n = 1; n <= 10; n++) // Count to ten

{

print("n = %d\n", n); // Display name & value of n

pause(500); // 0.5 s between reps

}

print("All done!"); // Display all done

}

Entradas relacionadas: