PF-Week 08
PF-Week 08
Fundamental
Week 08
Sobia Iftikhar
Sobia.Iftikhar@nu.edu.pk
Class 19
Practice
– uses the for statement to sum all the even integers from 2 to 10
Task
#include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the
value.
}
printf("\n");
}
Nested Loops
– while(condition)
– {
– while(condition)
– {
– // inner loop statements.
– }
– // outer loop statements.
– }
Example
Nested do While()
– do
– {
– do
– {
– // inner loop statements.
– }while(condition);
– // outer loop statements.
– }while(condition);
Example
1.int i=1;
2.do // outer loop
3.{
4. int j=1;
5. do // inner loop
6. {
7. printf("*");
8. j++;
9. }while(j<=8);
10. printf("\n");
11. i++;
12. }while(i<=4);
Task
– Write a program to print all the ASCII values and their equivalent characters
using a while loop. The ASCII values vary from 0 to 255.
main() {
int i=0;
clrscr();
while(i<=255) {
printf(" %d %c \n",i,i);
i++;
}
return 0;
}
#include<stdio.h>
#include<conio.h>
main() {
int i=1,j;
printf("\nPrime numbers between 1 to 300 are:\n\n");
while(i!=10) { if(j==i) {
Task
j=2; printf(" %d",i); Write a program to print all prime
numbers from 1 to 10. (Hint: Use
while(j<i) { } nested loops, break and continue)
if(i%j==0) { i++;
break; printf(" -- i %d\n",i);
} }
j++; getch();
printf(" -- j %d\n",j); return 0;
}
}
– #include<stdio.h>
– #include<conio.h>
– main() {
– int i,j,k;
– printf("All combinations of 1,2,3 are:\n\n");
– for(i=1;i<=3;i++) {
– for(j=1;j<=3;j++) {
– for(k=1;k<=3;k++) {
Task
Write a program to generate all
– printf(" %d%d%d ",i,j,k);
combinations of 1, 2 and 3 using for
– } loop
– }
– }
– getch();
– return 0;
– }
Class 20
Example
– Write a program to find the factorial value of any number entered through the
keyboard. main() {
long i,j,fact=1;
for(j=i;j>=1;j--) {
fact=fact*j;
}
printf("Factorial value = %ld ",fact);
Return 0;
/* loop for making a space between patterns */
#include<stdio.h> for(k=i+1;k<=71;k++) {
#include<conio.h>
main() { if(k==71)
printf(" ");
int i,j,k,l;
clrscr(); if(k<71)
printf(" ");
for(i=71;i>=65;i--) { }
/* loop to print descending letters */ Example
/* loop for printing ascending Write a program to produce the
letters */ for(l=i;l>=65;l--) { following output:
No doubt, this program will print the value of x as 10. Why so?
Because when a value 10 is assigned to x, the earlier value of x, i.e.
5, is lost. Thus, ordinary variables (the ones which we have used so
far) are capable of holding only one value at a time (as in the above
example). However, there are situations in which we would want to
store more than one value at a time in a single variable.
Arrays
An array is a variable that can store multiple values. For example, if you want to store 100
integers, you can create an array for it.
Class 21
Thankyou